Algorithmadvanced
Local ensemble transform Kalman filter
Also called LETKF.
Runs an ETKF independently at each grid point with only nearby observations, which localizes and parallelizes the analysis.
- Time
- Θ(N p + n (p + s^2 N + s^3)) worst
- Space
- Θ(N (n + p) + s N + s^2) extra
- Where
- N = the ensemble size; n = the number of grid values; p = the number of observations; s = the largest number of local observations of one grid value, written p_l in the text
- Model
- Real RAM
- Properties
- deterministicmean preservingnot perturbed observations
- Evidence
- Proof sketchCode in 1 languages
- Origin
- Brian R. Hunt, Eric J. Kostelich, Istvan Szunyogh, 2007
The local ensemble transform Kalman filter (LETKF) is the analysis step of an ensemble filter that works one grid point at a time. For each grid value it takes only the observations within a fixed distance, gives the far ones less weight by increasing their error variance, and solves the ETKF problem in the -dimensional space of the ensemble. The result at each point is a set of weights for the forecast members. Neighbouring points use almost the same observations, so their weights are almost the same and the analysis is smooth. Because the points are independent, the analysis runs in parallel on any number of processors, and the cost grows linearly with the size of the grid. It is one of the two standard ways to localize an ensemble filter, with the Schur product of covariance localization.
In plain words
A forecast is made times with small changes, and the forecasts disagree a little. At one grid point, the filter looks at the observations close to that point and asks which mix of the forecasts matches them best. Observations that are a bit further away count less. The answer is a list of weights, and the new value at the point is the weighted mix of the forecasts. The filter also makes a new set of values, spread out by the right amount for the error that is left. Then it goes to the next point and does the same with the observations close to it. A far observation can not change the point, even if the small ensemble shows a false link between the two places.
The problem
Input. A forecast ensemble (the background, in the notation of Ide, Courtier, Ghil and Lorenc 1997), observations with independent errors of variances (a diagonal ), an observation operator that may be nonlinear, the positions of the grid values and of the observations, a distance, the half-width of the Gaspari-Cohn weight, and a multiplicative inflation of the covariance. In the letters of the Kalman filter page, is its , the model is its , the forecast mean and covariance and are its predicted and , and the analysis and are its filtered and .
Output. An analysis ensemble . Component of its mean and of its sample variance should be the Kalman analysis of grid value from its local observations, with the inflated sample covariance and the error variances .
The algorithm
and hold the unscaled perturbations and , so . Write . The matrix has one row for each local observation and columns.
LETKF(x_1..x_N, y^o, H, r, c, rho)- 1
y_i <- H(x_i) for each i; ybar <- mean of y_i; Y <- [y_i - ybar] - 2
xbar <- mean of x_i; X <- [x_i - xbar] - 3
for each grid point j do - 4
L <- {k : dist(j, k) < 2c}; w_k <- GC(dist(j, k) / c) for k in L - 5
S <- rows sqrt(w_k / r_k) Y_k for k in L; d <- entries sqrt(w_k / r_k)(y^o_k - ybar_k) - 6
eigenpairs (σ_m, v_m) of S S^T; u_m <- S^T v_m / sqrt(σ_m) for σ_m > 0 - 7
wbar <- P~ S^T d, where P~ = (γ I + S^T S)^-1 = I/γ + Σ_m (1/(γ + σ_m) - 1/γ) u_m u_m^T - 8
W <- sqrt(N - 1) P~^(1/2) = sqrt(ρ) I + Σ_m (sqrt((N - 1)/(γ + σ_m)) - sqrt(ρ)) u_m u_m^T - 9
x^a_{j,i} <- xbar_j + X_j (wbar + W_i) for each member i - 10
return x^a_1..x^a_N
Lines L1 and L2 apply the observation operator to each member once and form the perturbations. Line L4 picks the local observations. Line L5 scales each one by , which is the same as dividing its error variance by the weight : a far observation looks less accurate, and it has no effect at distance or more. This is R-localization. Lines L6 to L8 are the ETKF in ensemble space. Hunt, Kostelich and Szunyogh (2007) form the matrix and find its eigenpairs. The code finds the eigenpairs of the smaller matrix instead and applies and through them, which gives the same result. Line L9 is the only line that touches the state: row of times the weights.
Example
Take two grid points at positions and , two members and , one observation of point with , and . The sample covariance is : the two points look perfectly correlated, which is the kind of correlation that two members always show.
At point the weight is . With , , , , and . Then , the mean is , and shrinks the perturbations by . The members are and , with sample variance , which is the Kalman answer with .
At point the distance is , and the Gaspari-Cohn weight is exactly . The observation now acts as if its error variance were . The mean moves from to and the perturbations shrink by the factor , so the members are about and . Without localization point would copy point exactly. The test file checks these numbers.
A measurement. On the Lorenz-96 model with , , classical RK4 with step , every other variable observed every time units with , and members started from states on the attractor, the reference code gives these mean analysis RMSE values over cycles 501 to 1500 (one seed, pure Python):
| half-width | |||
|---|---|---|---|
| 2 | 0.495 | 0.475 | 0.487 |
| 3 | 0.406 | 0.411 | 0.436 |
| 4 | 0.365 | 0.381 | 0.402 |
| 5 | 0.342 | ||
| 6 | 0.329 |
With and no inflation the RMSE was , and a second seed with , gave . The mean of the same ensemble run without observations had an RMSE of over the same cycles (a single free member, ), so all runs track the truth well below the target of . In this setting a wider localization was better up to , the largest value tried. These are measurements for one model and one observing network, not general rules. The test file runs a short version with , , .
Correctness
The proof shows that lines L6 to L8 compute and exactly from the small eigenproblem (Lemma 1), and that for a linear the mean and the sample variance at grid point are exactly the Kalman analysis with the inflated sample covariance and the error variances (Theorem 3, a theorem). The symmetric square root keeps the mean: . A grid point with no local observations keeps . Without localization the method is the global ETKF, so for a linear Gaussian model it converges to the Kalman filter as (Kwiatkowski and Mandel 2015, a theorem). With localization there is no such result, and the benefit is a measurement.
Proof: The local analysis of the LETKF is an exact ETKF analysis with localized observation errorsfull
Setting. There are forecast members and observations with independent errors of variances . is the matrix with columns and is the matrix with columns (lines L1 and L2). These are unscaled perturbations, so the sample covariance is . Fix a grid point (line L3) and its local observations with weights (line L4). Write , so and (line L5). Let with the inflation , and
where is the symmetric positive definite square root. Lines L7 to L9 claim to return , where is row of and is column of .
Lemma 1 (the dual eigenpairs). Let with orthonormal (line L6), and for each let . Then the are orthonormal, , and for every function on
Proof. . . A vector orthogonal to all has : indeed over the with (the other have , so ), and . So has the eigenvalue on and on the orthogonal complement, which gives the formula.
With , line L7 computes . With , for which , line L8 computes the row vector . So line L9 returns the stated .
Lemma 2 (push-through identity). For any matrix and positive definite,
Proof. . Both factors in brackets are invertible. Multiply on the left and on the right by their inverses.
Theorem 3 (exact local Kalman moments). Let be linear, , and write for the inflated sample covariance. Then the mean and the sample covariance of the values are component of
In words: grid point gets the Kalman analysis of its local observations with the error variances and the inflated ensemble covariance.
Proof. and , so . Since , , and by Lemma 2 . Hence .
The vector of ones satisfies , so and . So , and the mean of the is , the first claim.
The perturbations are , so the sample covariance is . On the other side, , whose entry is the same.
The same computation shows that the full matrix has the covariance , so without localization (every weight 1, so one serves all points) the output is an ensemble whose mean and covariance are the Kalman analysis and . This is the global ETKF, and with , , and it gives the mean and the variance .
Corollary 4 (no local observations). If is empty, then .
Proof. There are no , so and by Lemma 1.
What is not proved. Different grid points use different and therefore different , so the analysis ensemble as a whole is not the Kalman analysis for any single covariance. The cross covariance between two grid points is not controlled by Theorem 3, and the localized update is not a Bayes update of any joint prior. The gain in accuracy from localization is a measurement, not a theorem. For a nonlinear the use of in place of is the usual linearization of the ensemble methods and is a heuristic.
Termination. Lines L1 and L2 are finite loops. The loop of line L3 runs times. In each pass, line L6 runs the cyclic Jacobi method on a matrix, which the code stops after at most a fixed number of sweeps (the method converges quadratically, so the limit is never reached in practice). The other lines are finite sums. So the algorithm returns at line L10.
Complexity
Lines L1 and L2 cost plus applications of , and . For one grid point, line L4 costs with a plain scan (a spatial index brings this down to the number of local observations), line L6 costs to form and for a fixed number of Jacobi sweeps, and lines L7 to L9 cost , and . The total is for one analysis, without the model runs. Forming the matrices as in Hunt et al. (2007) costs for each point, which is better when . The extra space is the perturbations and one local problem.
Properties
- No perturbed observations. The analysis is deterministic for a given forecast ensemble, so it has no extra sampling noise from the observations.
- Exact local moments. For a linear each grid value gets exactly the Kalman mean and variance of its local problem.
- Smooth in space. The weights go to zero smoothly at distance , so the local problems of neighbouring points change smoothly. A hard cutoff makes the analysis jump.
- Embarrassingly parallel. Each grid point needs only , , and the local data, so the points can go to different processors without communication.
- Nonlinear H allowed. Only the values are needed, never a Jacobian or an adjoint.
- Low rank locally. At each point the update stays in the span of the local forecast perturbations, but different points use different weights, so the global analysis is not limited to the span of the global perturbations.
Variants and improvements
- LEKF. The local ensemble Kalman filter of Ott et al. (2004) did the same analysis in a local basis of the perturbations on a patch of grid points, and used the patch only for its centre.
- Hard cutoff. Use all observations within a radius with weight . This is simpler but makes the analysis less smooth.
- 4D-LETKF. Use observations at several times within a window, with taken from the forecasts at those times (Hunt et al. 2007).
- Weight interpolation. Compute and only on a coarse set of points and interpolate them, which saves most of the work for a fine grid.
- Adaptive inflation. Estimate from the innovations at each point (see covariance inflation).
- Ensemble-variational hybrids. Use the same ensemble in a variational analysis (see hybrid ensemble-variational and 4DEnVar).
When to use it
Use the LETKF for large spatial models with many observations, such as weather, ocean and atmospheric chemistry models, when the observations have local effects and errors that can be taken as independent. It is a good choice when a parallel analysis is needed and when the observation operator has no tangent linear code. For observations that integrate over a deep column or a long path, such as satellite radiances, the position of an observation is not well defined and R-localization is harder to set up. For a small state, the global ETKF is simpler.
Pitfalls
- Wrong scaling of the weight (line L5). The weight must divide the error variance, so both the row of and the innovation are multiplied by . Scaling only one of them gives an update that is not the Kalman update for any error variance.
- Inflation by or by (line L7). Here multiplies the covariance, so the perturbations grow by . Mixing the two conventions gives an inflation that is too large or too small.
- A non-symmetric square root (line L8). A Cholesky factor of is also a square root, but it does not map to a multiple of , so the members no longer have the right mean. Use the symmetric square root.
- Too small a half-width (line L4). If is smaller than the distance between observations, most points see one or no observation and the analysis has gaps. In the measurement above, (an observation every second grid point) was the worst value tried.
- Ill-conditioned weights. The eigenvalues can be very small. The code drops those below a relative tolerance, which is exact because their terms are zero.
- Correlated observation errors. The scaling of line L5 assumes a diagonal . With correlated errors, use the local block of and localize it with care.
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/local-ensemble-transform-kalman-filter/. The authors are listed in prov/HEPB83.jsonl.
"""Local ensemble transform Kalman filter (LETKF) with R-localization.
Notation of Ide, Courtier, Ghil and Lorenc (1997) and of Hunt, Kostelich and
Szunyogh (2007). The forecast ensemble has N members x_1..x_N in R^n. The
observations y^o in R^p have independent errors with variances r_k. The
observation operator h maps a state to R^p and may be nonlinear.
X and Y hold the unscaled perturbations x_i - xbar and h(x_i) - ybar. For each
grid point j the LETKF takes the observations k within distance 2c, divides
row k of Y by sqrt(r_k / w_k) with w_k = GC(dist / c) (Gaspari-Cohn), and
solves the ETKF problem in the N-dimensional ensemble space:
P~ = ((N - 1) / rho I + S^T S)^-1, wbar = P~ S^T d, W = sqrt(N - 1) P~^(1/2)
x^a_{j,i} = xbar_j + X_j (wbar + W_i)
S has p_l rows, one per local observation, and N columns. The code does not
form the N by N matrices. It finds the eigenpairs of the small p_l by p_l
matrix S S^T and uses them to apply P~ and W, so one grid point costs
O(p_l^2 N + p_l^3) and the analysis costs O(n (p_l^2 N + p_l^3)) after the
O(N (n + p)) set up. rho multiplies the covariance (the perturbations grow by
sqrt(rho)).
"""
import math
import scimat
def gaspari_cohn(r, c):
"""Return the Gaspari-Cohn function (eq. 4.10 of Gaspari and Cohn 1999) at distance r.
c is the half-width: the value is 1 at r = 0, 5/24 at r = c and 0 for
|r| >= 2c. Integer and Fraction arguments give exact values.
"""
z = abs(r) / c
if z >= 2:
return 0 * z
if z <= 1:
return -z**5 / 4 + z**4 / 2 + 5 * z**3 / 8 - 5 * z**2 / 3 + 1
return z**5 / 12 - z**4 / 2 + 5 * z**3 / 8 + 5 * z**2 / 3 - 5 * z + 4 - 2 / (3 * z)
def periodic_distance(period):
"""Return dist(a, b) = the distance between positions a and b on a circle of length period."""
def dist(a, b):
r = abs(a - b) % period
return min(r, period - r)
return dist
def sym_eig(a, tol=1e-14, max_sweeps=60):
"""Return (values, V) with a = V diag(values) V^T, by the cyclic Jacobi method.
a is a symmetric matrix (list of rows). The columns of V are orthonormal
eigenvectors. The values are not sorted.
"""
n = len(a)
a = [[float(v) for v in row] for row in a]
v = [[1.0 if i == j else 0.0 for j in range(n)] for i in range(n)]
for _ in range(max_sweeps):
off = sum(a[p][q] ** 2 for p in range(n) for q in range(p + 1, n))
diag = sum(a[p][p] ** 2 for p in range(n))
if off <= tol * tol * diag or off == 0.0:
break
for p in range(n - 1):
for q in range(p + 1, n):
apq = a[p][q]
if apq == 0.0:
continue
theta = (a[q][q] - a[p][p]) / (2.0 * apq)
t = (1.0 if theta >= 0 else -1.0) / (abs(theta) + math.sqrt(theta * theta + 1.0))
cs = 1.0 / math.sqrt(t * t + 1.0)
sn = t * cs
for k in range(n):
akp, akq = a[k][p], a[k][q]
a[k][p] = cs * akp - sn * akq
a[k][q] = sn * akp + cs * akq
for k in range(n):
apk, aqk = a[p][k], a[q][k]
a[p][k] = cs * apk - sn * aqk
a[q][k] = sn * apk + cs * aqk
a[p][q] = 0.0
a[q][p] = 0.0
for k in range(n):
vkp, vkq = v[k][p], v[k][q]
v[k][p] = cs * vkp - sn * vkq
v[k][q] = sn * vkp + cs * vkq
return [a[i][i] for i in range(n)], v
def letkf_analysis(ens, yo, h, r_var, grid_pos=None, obs_pos=None, c=None, rho=1.0, dist=None):
"""Return the LETKF analysis ensemble (a list of N members).
ens: the forecast members, each a list of n floats.
yo: the p observations. h(x): the observation operator. r_var: the p
observation error variances (R is diagonal).
grid_pos, obs_pos: the positions of the n state values and the p
observations. c: the Gaspari-Cohn half-width; None uses every observation
with weight 1 at every point, which is the global ETKF.
rho: multiplicative inflation of the covariance. dist(a, b): the distance,
by default |a - b|.
"""
N, n, p = len(ens), len(ens[0]), len(yo)
if dist is None:
dist = lambda a, b: abs(a - b)
hx = [list(h(x)) for x in ens] # @line L1
ybar = [sum(hx[i][k] for i in range(N)) / N for k in range(p)]
Y = [[hx[i][k] - ybar[k] for i in range(N)] for k in range(p)]
xbar = [sum(ens[i][j] for i in range(N)) / N for j in range(n)] # @line L2
X = [[ens[i][j] - xbar[j] for i in range(N)] for j in range(n)]
gamma = (N - 1) / rho
sr = math.sqrt(rho)
out = [[0.0] * n for _ in range(N)]
for j in range(n): # @line L3
if c is None: # @line L4
loc = [(k, 1.0) for k in range(p)]
else:
loc = []
for k in range(p):
w = gaspari_cohn(dist(grid_pos[j], obs_pos[k]), c)
if w > 0:
loc.append((k, w))
scl = [math.sqrt(w / r_var[k]) for k, w in loc] # @line L5
S = [[s * v for v in Y[k]] for (k, _), s in zip(loc, scl)]
dl = [s * (yo[k] - ybar[k]) for (k, _), s in zip(loc, scl)]
G = [[scimat.dot(S[a], S[b]) for b in range(len(S))] for a in range(len(S))] # @line L6
sig, V = sym_eig(G) if S else ([], [])
top = max(sig) if sig else 0.0
modes = []
for m, s in enumerate(sig):
if s > 1e-12 * top:
u = [sum(V[a][m] * S[a][i] for a in range(len(S))) / math.sqrt(s) for i in range(N)]
modes.append((s, u))
b = [sum(S[a][i] * dl[a] for a in range(len(S))) for i in range(N)] # @line L7
wbar = [bi / gamma for bi in b]
for s, u in modes:
f = (1.0 / (gamma + s) - 1.0 / gamma) * scimat.dot(u, b)
wbar = [wi + f * ui for wi, ui in zip(wbar, u)]
xj = X[j] # @line L8
row = [sr * v for v in xj]
for s, u in modes:
f = (math.sqrt((N - 1) / (gamma + s)) - sr) * scimat.dot(xj, u)
row = [ri + f * ui for ri, ui in zip(row, u)]
base = xbar[j] + scimat.dot(xj, wbar)
for i in range(N):
out[i][j] = base + row[i] # @line L9
return out # @line L10
def mean_and_spread(ens):
"""Return (mean, var): the ensemble mean and the sample variance (divisor N - 1) of each component."""
N, n = len(ens), len(ens[0])
mean = [sum(x[j] for x in ens) / N for j in range(n)]
var = [sum((x[j] - mean[j]) ** 2 for x in ens) / (N - 1) for j in range(n)]
return mean, var
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_local_ensemble_transform_kalman_filter.py 205 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/local-ensemble-transform-kalman-filter/. The authors are listed in prov/HEPB83.jsonl.
import math
import random
from fractions import Fraction as Fr
import scimat
from local_ensemble_transform_kalman_filter import (
gaspari_cohn,
letkf_analysis,
mean_and_spread,
periodic_distance,
sym_eig,
)
def lorenz96(x, forcing=8.0):
n = len(x)
return [(x[(k + 1) % n] - x[k - 2]) * x[k - 1] - x[k] + forcing for k in range(n)]
def rk4(x, dt):
k1 = lorenz96(x)
k2 = lorenz96([a + 0.5 * dt * b for a, b in zip(x, k1)])
k3 = lorenz96([a + 0.5 * dt * b for a, b in zip(x, k2)])
k4 = lorenz96([a + dt * b for a, b in zip(x, k3)])
return [a + dt / 6.0 * (b + 2.0 * c + 2.0 * d + e) for a, b, c, d, e in zip(x, k1, k2, k3, k4)]
def dense_point_update(ens, yo, h, r_var, j, weights, rho):
"""Oracle for one grid point: form the N by N ETKF matrices of Hunt et al. (2007)."""
N = len(ens)
hx = [h(x) for x in ens]
ybar = [sum(v[k] for v in hx) / N for k in range(len(yo))]
xbar = sum(x[j] for x in ens) / N
Xj = [x[j] - xbar for x in ens]
S = [[math.sqrt(w / r_var[k]) * (hx[i][k] - ybar[k]) for i in range(N)] for k, w in weights]
d = [math.sqrt(w / r_var[k]) * (yo[k] - ybar[k]) for k, w in weights]
A = scimat.add(scimat.scale((N - 1) / rho, scimat.eye(N)), scimat.matmul(scimat.transpose(S), S))
Pt = scimat.inv(A)
wbar = scimat.matvec(Pt, scimat.matvec(scimat.transpose(S), d)) if S else [0.0] * N
vals, V = sym_eig(scimat.scale(N - 1, Pt))
W = [[sum(V[a][m] * math.sqrt(vals[m]) * V[b][m] for m in range(N)) for b in range(N)] for a in range(N)]
return [xbar + sum(Xj[k] * (wbar[k] + W[k][i]) for k in range(N)) for i in range(N)]
def random_ensemble(rng, N, n):
return [[rng.gauss(0, 1) for _ in range(n)] for _ in range(N)]
def test_scalar_check_value():
s = 1 / math.sqrt(2.0)
out = letkf_analysis([[-s], [s]], [1.0], lambda x: [x[0]], [1.0])
mean, var = mean_and_spread(out)
assert abs(mean[0] - 0.5) < 1e-12
assert abs(var[0] - 0.5) < 1e-12
def test_two_member_example():
out = letkf_analysis([[-1.0], [1.0]], [1.0], lambda x: [x[0]], [1.0])
assert abs(out[0][0] - (2 / 3 - 1 / math.sqrt(3))) < 1e-12
assert abs(out[1][0] - (2 / 3 + 1 / math.sqrt(3))) < 1e-12
def test_page_example():
# Two grid points at 0 and 3, one observation at 0, half-width c = 2.
ens = [[-1.0, -1.0], [1.0, 1.0]]
out = letkf_analysis(ens, [1.0], lambda x: [x[0]], [1.0], [0, 3], [0], 2)
assert gaspari_cohn(Fr(3), Fr(2)) == Fr(19, 1152)
assert abs(out[0][0] - (2 / 3 - 1 / math.sqrt(3))) < 1e-12
assert abs(out[1][0] - (2 / 3 + 1 / math.sqrt(3))) < 1e-12
spread = math.sqrt(1152 / 1190)
assert abs(out[0][1] - (19 / 595 - spread)) < 1e-12
assert abs(out[1][1] - (19 / 595 + spread)) < 1e-12
def test_gaspari_cohn_values():
assert gaspari_cohn(0, 3) == 1
assert gaspari_cohn(Fr(3), Fr(3)) == Fr(5, 24)
assert gaspari_cohn(Fr(-3), Fr(3)) == Fr(5, 24)
assert gaspari_cohn(6, 3) == 0
assert gaspari_cohn(7.5, 3) == 0
assert gaspari_cohn(Fr(599, 100), Fr(3)) > 0
def test_sym_eig_reconstructs():
rng = random.Random(3)
for n in (1, 2, 5, 8):
L = [[rng.uniform(-1, 1) for _ in range(n)] for _ in range(n)]
A = scimat.add(L, scimat.transpose(L))
vals, V = sym_eig(A)
B = [[sum(V[i][m] * vals[m] * V[j][m] for m in range(n)) for j in range(n)] for i in range(n)]
VtV = scimat.matmul(scimat.transpose(V), V)
for i in range(n):
for j in range(n):
assert abs(B[i][j] - A[i][j]) < 1e-12
assert abs(VtV[i][j] - (1.0 if i == j else 0.0)) < 1e-12
def test_global_matches_kalman_moments():
# With every observation at weight 1 and rho = 1 the analysis mean is xbar + K d
# and the analysis sample covariance is (I - K H) P^f, with the sample P^f.
rng = random.Random(5)
for _ in range(30):
n, p, N = rng.randint(1, 5), rng.randint(1, 4), rng.randint(2, 8)
ens = random_ensemble(rng, N, n)
H = [[rng.uniform(-1, 1) for _ in range(n)] for _ in range(p)]
r = [rng.uniform(0.2, 2.0) for _ in range(p)]
yo = [rng.gauss(0, 2) for _ in range(p)]
out = letkf_analysis(ens, yo, lambda x: scimat.matvec(H, x), r)
xbar = [sum(x[j] for x in ens) / N for j in range(n)]
X = [[x[j] - xbar[j] for j in range(n)] for x in ens]
Pf = [[sum(X[i][a] * X[i][b] for i in range(N)) / (N - 1) for b in range(n)] for a in range(n)]
Rm = [[r[a] if a == b else 0.0 for b in range(p)] for a in range(p)]
PHt = scimat.matmul(Pf, scimat.transpose(H))
K = scimat.transpose(scimat.solve(scimat.add(scimat.matmul(H, PHt), Rm), scimat.transpose(PHt)))
d = scimat.sub(yo, scimat.matvec(H, xbar))
xa = scimat.add(xbar, scimat.matvec(K, d))
Pa = scimat.matmul(scimat.sub(scimat.eye(n), scimat.matmul(K, H)), Pf)
ma = [sum(x[j] for x in out) / N for j in range(n)]
Xa = [[x[j] - ma[j] for j in range(n)] for x in out]
Pe = [[sum(Xa[i][a] * Xa[i][b] for i in range(N)) / (N - 1) for b in range(n)] for a in range(n)]
for a in range(n):
assert abs(ma[a] - xa[a]) < 1e-9 * (1 + abs(xa[a]))
for b in range(n):
assert abs(Pe[a][b] - Pa[a][b]) < 1e-9 * (1 + abs(Pf[a][b]))
def test_local_equals_dense_oracle():
rng = random.Random(7)
n, N = 12, 6
obs_idx = [0, 3, 4, 8, 11]
dist = periodic_distance(n)
for rho in (1.0, 1.2):
ens = random_ensemble(rng, N, n)
h = lambda x: [x[k] ** 2 / 4 + x[k] for k in obs_idx] # nonlinear operator
r = [rng.uniform(0.3, 1.5) for _ in obs_idx]
yo = [rng.gauss(0, 1) for _ in obs_idx]
out = letkf_analysis(ens, yo, h, r, list(range(n)), obs_idx, 2.0, rho, dist)
for j in range(n):
w = [(k, gaspari_cohn(dist(j, q), 2.0)) for k, q in enumerate(obs_idx)]
w = [(k, v) for k, v in w if v > 0]
ref = dense_point_update(ens, yo, h, r, j, w, rho)
for i in range(N):
assert abs(out[i][j] - ref[i]) < 1e-9
def test_useless_observations_keep_forecast():
rng = random.Random(9)
n, N = 10, 5
obs_idx = [1, 4, 7]
ens = random_ensemble(rng, N, n)
out = letkf_analysis(ens, [0.5, -1.0, 2.0], lambda x: [x[k] for k in obs_idx], [1e12] * 3,
list(range(n)), obs_idx, 1.5, 1.0, periodic_distance(n))
for i in range(N):
for j in range(n):
assert abs(out[i][j] - ens[i][j]) < 1e-9
def test_far_point_keeps_inflated_forecast():
rng = random.Random(10)
n, N = 20, 4
ens = random_ensemble(rng, N, n)
obs_idx = [0]
out = letkf_analysis(ens, [3.0], lambda x: [x[0]], [1.0], list(range(n)), obs_idx, 2.0, 1.44,
periodic_distance(n))
for j in range(4, 17): # distance at least 4 = 2c from point 0
xbar = sum(x[j] for x in ens) / N
for i in range(N):
assert abs(out[i][j] - (xbar + 1.2 * (ens[i][j] - xbar))) < 1e-12
assert abs(out[0][0] - ens[0][0]) > 1e-3
def test_lorenz96_twin_rmse():
# Measurement on the page: n = 40, every other variable observed every 0.05 with R = I.
rng = random.Random(1)
n, N, dt = 40, 10, 0.05
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_idx = list(range(0, n, 2))
h = lambda s: [s[k] for k in obs_idx]
dist = periodic_distance(n)
errs, free_errs = [], []
for _ in range(150):
x = rk4(x, dt)
ens = [rk4(e, dt) for e in ens]
free = [rk4(e, dt) for e in free]
yo = [x[k] + rng.gauss(0, 1) for k in obs_idx]
ens = letkf_analysis(ens, yo, h, [1.0] * len(yo), list(range(n)), obs_idx, 2.0, 1.1, dist)
m, _ = mean_and_spread(ens)
mf, _ = mean_and_spread(free)
errs.append(math.sqrt(sum((m[j] - x[j]) ** 2 for j in range(n)) / n))
free_errs.append(math.sqrt(sum((mf[j] - x[j]) ** 2 for j in range(n)) / n))
tail = errs[50:]
assert sum(tail) / len(tail) < 0.7
assert sum(free_errs[50:]) / 100 > 2.0
History
Edward Ott, Brian Hunt, Istvan Szunyogh and their coauthors at the University of Maryland published the local ensemble Kalman filter in Tellus A in 2004. Hunt, Kostelich and Szunyogh then gave the transform form in ensemble space, with the symmetric square root and the smooth increase of the observation error with distance, in Physica D in 2007, and Szunyogh and coauthors tested it with the global model of the US National Centers for Environmental Prediction in 2008. Greybush and coauthors compared its R-localization with the Schur product localization of the covariance in 2011.
References
- B. R. Hunt, E. J. Kostelich and I. Szunyogh, Efficient data assimilation for spatiotemporal chaos: a local ensemble transform Kalman filter, Physica D 230(1-2) (2007) 112-126, the derivation in ensemble space, the symmetric square root, the local analysis and the smooth increase of R with distance
- E. Ott, B. R. Hunt, I. Szunyogh, A. V. Zimin, E. J. Kostelich, M. Corazza, E. Kalnay, D. J. Patil and J. A. Yorke, A local ensemble Kalman filter for atmospheric data assimilation, Tellus A 56(5) (2004), from page 415, the local ensemble Kalman filter, the predecessor of the LETKF
- I. Szunyogh, E. J. Kostelich, G. Gyarmati, E. Kalnay, B. R. Hunt, E. Ott, E. Satterfield and J. A. Yorke, A local ensemble transform Kalman filter data assimilation system for the NCEP global model, Tellus A 60(1) (2008), from page 113, the application to a global weather model
- S. J. Greybush, E. Kalnay, T. Miyoshi, K. Ide and B. R. Hunt, Balance and ensemble Kalman filter localization techniques, Monthly Weather Review 139(2) (2011) 511-522, the comparison of R-localization and B-localization
- G. Gaspari and S. E. Cohn, Construction of correlation functions in two and three dimensions, Quarterly Journal of the Royal Meteorological Society 125(554) (1999) 723-757, eq. (4.10), the compactly supported weight
- E. Kwiatkowski and J. Mandel, Convergence of the square root ensemble Kalman filter in the large ensemble limit, SIAM/ASA Journal on Uncertainty Quantification 3(1) (2015) 1-17, the large ensemble limit of the ETKF and other square root filters for linear models
- 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 HEPB83 Edit this page History Report an error Markdown