Algorithmadvanced
Ensemble adjustment Kalman filter
Also called EAKF.
Adjusts the ensemble members by a linear map so the analysis ensemble has exactly the Kalman posterior mean and covariance of the sample prior.
- Time
- Θ(p N (n + p)) worst
- Space
- Θ(N (n + p)) extra
- Where
- N = the ensemble size; n = the size of the state; p = the number of observations
- Model
- Real RAM
- Properties
- deterministicnot perturbed observations
- Evidence
- Proof sketchCode in 1 languages
- Origin
- Jeffrey L. Anderson, 2001
The ensemble adjustment Kalman filter (EAKF) of Anderson (2001) is an ensemble Kalman filter without perturbed observations. It moves the ensemble mean with the Kalman gain and maps each forecast perturbation to an analysis perturbation with one linear map, the adjustment matrix . The map is chosen so that the analysis ensemble has exactly the Kalman mean and covariance for the sample covariance of the forecast. In practice the filter is used in the serial two step form of Anderson (2003): for each scalar observation it first adjusts the ensemble of the predicted observation, and then it carries the increments to the state by linear regression. It is one of the ensemble square root filters, and for a linear the serial form gives the same members as the serial EnSRF.
In plain words
Look at one observed number. Each member predicts a value for it, so the members give a small cloud of predicted values. The filter first moves this cloud to where Bayes' rule says it should be: it shifts the centre towards the data and shrinks the cloud about the new centre by a fixed factor. It does not add noise, and the order of the members stays the same. Then each member changes every other value by the amount that a straight line fit from the observed value predicts. A value that varies together with the observed one moves a lot, and a value with no relation to it does not move.
The problem
Input. A forecast ensemble , observations with an observation operator , and the error variances of independent observation errors (a diagonal ) for the serial form, or a full error covariance and a linear for the joint form. The serial form takes 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 . The adjustment matrix of this page is not the model.
Output. An analysis ensemble with mean and sample covariance , where is the sample covariance of the forecast and (for a linear and no localization).
The algorithm
The serial form keeps an ensemble of predicted observations next to the state ensemble and processes one scalar observation at a time.
EAKF-SERIAL(x_1..x_N, y^o, H, r)- 1
y_i <- H(x_i) for each member i ▷ the only use of H - 2
for k <- 1 to p do - 3
ybar <- mean of y_ik; s <- sample variance of y_ik - 4
s^a <- 1 / (1/s + 1/r_k); y^a <- s^a (ybar/s + y^o_k/r_k) - 5
Δy_i <- y^a + sqrt(s^a/s) (y_ik - ybar) - y_ik ▷ adjust in observation space - 6
b_x <- cov(x, y_k) / s; x_i <- x_i + b_x Δy_i ▷ regression onto the state - 7
b_y <- cov(y, y_k) / s; y_i <- y_i + b_y Δy_i ▷ and onto the other observations - 8
return x_1..x_N
Line L4 is the posterior of a scalar Gaussian prior after an observation with error variance . Line L5 moves the predicted values so that they have exactly this mean and variance, by a shift and a shrink about the mean. Lines L6 and L7 compute the regression coefficients from the values before the update. With localization, and are multiplied entry by entry by the weights of observation . An observation with carries no information about the ensemble and is skipped.
The joint form of Anderson (2001) treats all observations together for a linear and any positive definite .
EAKF-JOINT(x_1..x_N, y^o, H, R)J1 xbar, X <- mean and perturbations of x_i; P <- X X^T / (N - 1)J2 P = F D F^T with the positive eigenvalues only; G <- D^(1/2)J3 M <- G F^T H^T R^-1 H F G = U Λ U^TJ4 A <- F G U (I + Λ)^(-1/2) U^T G^-1 F^T ▷ the adjustment matrixJ5 x^a <- xbar + P H^T (H P H^T + R)^-1 (y^o - H xbar)J6 return x^a_i <- x^a + A X_i for each member i
Line J2 keeps only the positive eigenvalues of , so that can be inverted. This matters because has rank at most , which is usually smaller than .
Example
Take three members with two values each, , and . The first value is observed, with . The predicted values are , so and . Line L4 gives and , and the shrink factor is . Line L5 moves the predicted values to , so the increments are .
The second value has the covariance with the first value, so . The analysis members are , and . The second value has the mean and the variance . The Kalman update with the sample covariance gives the gain , the same mean and the same variance .
For the check value of the page group: with two members , and , both forms return the mean and the variance to rounding.
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 and , the serial EAKF had the mean analysis RMSE over cycles 501 to 1500 (one seed). In every cycle its members differed from those of the serial EnSRF, run from the same forecast, by at most . This is Lemma 2 of the proof, which also holds with localization.
Correctness
The proof shows that line L5 gives the predicted values the Gaussian posterior mean and variance (Lemma 1). The regression of lines L6 and L7 then makes exactly the update of the serial EnSRF, with (Lemma 2). So for a linear and a diagonal the serial EAKF has the Kalman mean and covariance (Theorem 3). For the joint form, by the Woodbury identity (Lemma 4), so the members of line J6 have the Kalman mean and covariance for any positive definite (Theorem 5). For one scalar observation the two forms give the same members (Corollary 6). These are theorems. As for a linear Gaussian model the filter converges to the Kalman filter (Kwiatkowski and Mandel 2015). With localization or a nonlinear the update is a heuristic.
Proof: The EAKF gives exactly the Kalman analysis mean and 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 (rows ) and an error covariance . The serial form needs with ; the joint form needs symmetric positive definite. There is no localization until the last remark. The Kalman values are , and .
Lemma 1 (the step in observation space). Fix one observation with , and let be the predicted values of line L1 with mean and sample variance (line L3). Lines L4 and L5 give new values with mean and sample variance .
Proof. Line L4 sets and . Since , this is with . Line L5 sets with . The deviations from are times the old deviations, which sum to zero, so the mean is and the variance is .
These are the mean and the variance of the posterior of a scalar Gaussian prior after one observation with error variance . Note that , which is the number of the EnSRF proof.
Lemma 2 (the serial EAKF step is the serial EnSRF step). Let be the perturbations of observation and suppose the predicted observations are applied to the members. With , , and , lines L6 and L7 change member to
and change the predicted observations by times the same increments.
Proof. Line L6 sets , the regression coefficients of the state on observation . By Lemma 1, . So . Now , so
and the second term is . Line L7 uses with , which is , so the predicted observations change by . Both coefficients use the values before the update, as the lines of the code do.
Theorem 3 (serial form). With a linear , a diagonal and no localization, the serial EAKF returns the same members as the serial EnSRF, so its output has the mean and the sample covariance . If for an observation, the code skips it, which is the Kalman update with .
Proof. By Lemma 2 each pass of the loop of line L2 makes the EnSRF update of lines L8 and L9 of the EnSRF, and keeps the predicted observations equal to applied to the members. Theorem 3 of the EnSRF proof says that the serial EnSRF ends with the Kalman mean and covariance. If , then , so , ( is positive semidefinite) and .
Lemma 4 (the adjustment matrix). Let where () has orthonormal columns and holds the positive eigenvalues (line J2). Put , , and (line J3), and
Then .
Proof. and , so . With , which is symmetric, . On the other side,
and the Woodbury identity gives .
is invertible because only positive eigenvalues are kept. Anderson (2001, Appendix A) gives this matrix with singular value decompositions, and Grooms (2020) discusses the case where is singular, which is the usual case with .
Theorem 5 (joint form). For a linear and a symmetric positive definite , the members of line J6 have the mean and the sample covariance .
Proof. Line J5 computes with , which is the Kalman mean. The new perturbations are . Their columns sum to times the sum of the columns of , which is zero, so the mean is . Their sample covariance is by Lemma 4.
Corollary 6 (one scalar observation). If , the joint form gives the same members as the serial form.
Proof. With (one row) and , is one row, and has the single positive eigenvalue with the unit eigenvector (if , then , and , which is the skipped update). So with , and
because and . The columns of lie in the range of , which is the range of , so and by the identity in the proof of Lemma 2. The mean is the Kalman mean in both forms, so the members agree.
For more than one observation the joint and the serial members differ in general. The covariance of the analysis fixes the perturbations only up to an orthogonal transform in ensemble space (Tippett et al. 2003), and the two forms make different choices.
With , , , and , , and , so both forms return the mean and the variance .
With localization. If the weights multiply and entry by entry, the proof of Lemma 2 still shows that the serial EAKF makes the same step as the serial EnSRF with the same weights on its gain. The step is then no longer an exact Kalman update, as the EnSRF proof explains, and its use is a heuristic.
A nonlinear . The serial form evaluates only at line L1 and then updates the predicted observations by regression. The theorems above do not cover this case. Anderson (2003) describes it as a least squares fit of each state value on each observed value.
Termination. The serial form makes passes of a finite number of sums over members. It skips an observation with , so line L4 divides only by and , and line L6 by . The joint form calls the Jacobi method twice with a fixed upper limit on the number of sweeps, and solves two linear systems with and , which are positive definite. Both forms return.
Complexity
Each pass of the serial loop costs for lines L6 and L7 and for the rest, so the analysis costs plus applications of . With localization only the values with a nonzero weight need work. The extra space is the observation ensemble and the copy of the state ensemble, . The joint form needs the matrix and two eigendecompositions, about time and space. It is useful for checks and small problems, not for large models.
Properties
- No perturbed observations. The update is deterministic, so it adds no sampling noise from random observations.
- Exact second moments. For a linear and no localization, the analysis mean and covariance are the Kalman values for the sample covariance. The serial form needs a diagonal for this.
- Order of the members is kept. Line L5 shifts and shrinks the predicted values without reordering them, so each analysis member stays close to its forecast member.
- Same members as the serial EnSRF. For a linear the two serial filters are the same algorithm written in two ways, also with localization of the gain.
- A square root filter. The EAKF, the ETKF and the EnSRF give the same mean and covariance. Their members differ by an orthogonal transform in ensemble space (Tippett et al. 2003).
- Low rank. The analysis stays in the span of the forecast perturbations.
Variants and improvements
- Other adjustments in observation space. Line L5 can be replaced by any rule that gives the predicted values new values from a scalar posterior. Anderson (2003) uses this freedom: the perturbed observation EnKF is the same two step scheme with a random update in line L5.
- Localization. Multiply and by a Gaspari-Cohn weight of the distance between the observation and each value. This is covariance localization of the gain.
- Inflation. The filter is usually run with covariance inflation of the forecast ensemble, as in the measurement above.
- Joint transform in ensemble space. The ETKF computes an transform instead of the matrix , which is much cheaper when . The LETKF does this for each grid point.
When to use it
Use the serial EAKF when the observation errors are independent, when the observation operators are nonlinear or complex and should be run only once for each member, and when localization by distance is needed. Its update of the predicted observations makes it easy to add new kinds of observations. For problems with very many observations on a parallel computer the serial loop is a bottleneck, and the LETKF is easier to run in parallel. Use the joint form only for small problems or to check other code.
Pitfalls
- Forgetting to update the predicted observations (line L7). Without line L7, each later observation uses a prior that does not include the earlier ones, and their information is counted twice.
- Using updated values in the regression (lines L6 and L7). The coefficients must use the predicted values before line L5 is applied. Using the adjusted values gives the wrong increments.
- Inverting a singular (line J2). With the forecast covariance is singular. Keep only the positive eigenvalues, or does not exist.
- Correlated errors in the serial form. The serial form needs a diagonal . For correlated errors, first transform the observations with a square root of , or use the joint form.
- Spread collapse. As with every ensemble filter with few members, the filter underestimates its error. Without inflation or localization it can stop using the data.
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-adjustment-kalman-filter/. The authors are listed in prov/NP9ZCK.jsonl.
"""Ensemble adjustment Kalman filter (EAKF) of Anderson (2001, 2003).
Notation of Ide, Courtier, Ghil and Lorenc (1997). The forecast ensemble has
N members in R^n; the observations y^o have error variances r_k.
eakf_serial is the two step form of Anderson (2003) used in practice: for
each scalar observation, adjust the ensemble of the predicted observation so
that it has the Gaussian posterior mean and variance, then regress the
increments onto every state value and every other predicted observation.
eakf_joint is the matrix form of Anderson (2001, Appendix A): with
P = F D F^T (the nonzero eigenvalues only), G = D^(1/2) and
G F^T H^T R^-1 H F G = U Lam U^T, the adjustment matrix
A = F G U (I + Lam)^(-1/2) U^T G^-1 F^T maps each forecast perturbation to
an analysis perturbation, and A P A^T is the Kalman analysis covariance.
Costs: eakf_serial O(p N (n + p)); eakf_joint O(n^3 + n^2 (N + p) + p^3) with
a fixed number of Jacobi sweeps.
"""
import math
import scimat
def eakf_serial(ens, yo, h, r_var, loc_state=None, loc_obs=None):
"""Return the analysis ensemble of the serial EAKF (a list of N members).
h(x) is evaluated once per member. loc_state[k][j] and loc_obs[k][l] are
optional weights that multiply the regression coefficients.
"""
N, n, p = len(ens), len(ens[0]), len(yo)
x = [list(m) for m in ens]
y = [list(h(m)) for m in ens] # @line L1
for k in range(p): # @line L2
yk = [y[i][k] for i in range(N)]
ybar = sum(yk) / N # @line L3
s = sum((v - ybar) ** 2 for v in yk) / (N - 1)
if s == 0.0:
continue
sa = 1.0 / (1.0 / s + 1.0 / r_var[k]) # @line L4
ya = sa * (ybar / s + yo[k] / r_var[k])
f = math.sqrt(sa / s)
dy = [ya + f * (v - ybar) - v for v in yk] # @line L5
xbar = [sum(x[i][j] for i in range(N)) / N for j in range(n)] # @line L6
bx = [sum((x[i][j] - xbar[j]) * (yk[i] - ybar) for i in range(N)) / ((N - 1) * s) for j in range(n)]
if loc_state is not None:
bx = [b * w for b, w in zip(bx, loc_state[k])]
ymean = [sum(y[i][l] for i in range(N)) / N for l in range(p)] # @line L7
by = [sum((y[i][l] - ymean[l]) * (yk[i] - ybar) for i in range(N)) / ((N - 1) * s) for l in range(p)]
if loc_obs is not None:
by = [b * w for b, w in zip(by, loc_obs[k])]
for i in range(N):
for j in range(n):
x[i][j] += bx[j] * dy[i]
for l in range(p):
y[i][l] += by[l] * dy[i]
return x # @line L8
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."""
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 adjustment_matrix(P, H, R, rel_tol=1e-10):
"""Return A = F G U (I + Lam)^(-1/2) U^T G^-1 F^T for the covariance P (n by n)."""
n = len(P)
d, V = sym_eig(P) # @line J2
top = max(d) if d else 0.0
keep = [m for m in range(n) if d[m] > rel_tol * top]
F = [[V[j][m] for m in keep] for j in range(n)] # n by r
g = [math.sqrt(d[m]) for m in keep]
FG = [[F[j][a] * g[a] for a in range(len(keep))] for j in range(n)]
B = scimat.matmul(H, FG) # @line J3
M = scimat.matmul(scimat.transpose(B), scimat.solve(R, B))
lam, U = sym_eig(M) if keep else ([], [])
rr = len(keep)
core = [[sum(U[a][m] * U[b][m] / math.sqrt(1.0 + lam[m]) for m in range(rr)) for b in range(rr)] for a in range(rr)]
right = [[F[j][b] / g[b] for b in range(rr)] for j in range(n)] # F G^-1, so the last factor is right^T
return scimat.matmul(scimat.matmul(FG, core), scimat.transpose(right)) # @line J4
def eakf_joint(ens, yo, H, R):
"""Return the analysis ensemble of the joint EAKF for a linear H (p by n) and a covariance R."""
N, n = len(ens), len(ens[0])
xbar = [sum(x[j] for x in ens) / N for j in range(n)] # @line J1
X = [[x[j] - xbar[j] for j in range(n)] for x in ens]
P = [[sum(X[i][a] * X[i][b] for i in range(N)) / (N - 1) for b in range(n)] for a in range(n)]
A = adjustment_matrix(P, H, R)
PHt = scimat.matmul(P, scimat.transpose(H)) # @line J5
S = scimat.add(scimat.matmul(H, PHt), R)
z = scimat.solve(S, scimat.sub(yo, scimat.matvec(H, xbar)))
xa = scimat.add(xbar, scimat.matvec(PHt, z))
return [scimat.add(xa, scimat.matvec(A, X[i])) for i in range(N)] # @line J6
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_adjustment_kalman_filter.py 134 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/ensemble-adjustment-kalman-filter/. The authors are listed in prov/NP9ZCK.jsonl.
import math
import random
import scimat
from ensemble_adjustment_kalman_filter import adjustment_matrix, eakf_joint, eakf_serial, ensemble_moments
def kalman_moments(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 xa, Pa
def close_moments(ens, xa, Pa, tol=1e-9):
ma, Pe = ensemble_moments(ens)
for a in range(len(xa)):
assert abs(ma[a] - xa[a]) < tol * (1 + abs(xa[a]))
for b in range(len(xa)):
assert abs(Pe[a][b] - Pa[a][b]) < tol * (1 + abs(Pa[a][b]))
def diag(r):
return [[r[a] if a == b else 0.0 for b in range(len(r))] for a in range(len(r))]
def test_scalar_check_value():
s = 1 / math.sqrt(2.0)
for out in (eakf_serial([[-s], [s]], [1.0], lambda x: [x[0]], [1.0]),
eakf_joint([[-s], [s]], [1.0], [[1.0]], [[1.0]])):
mean, P = ensemble_moments(out)
assert abs(mean[0] - 0.5) < 1e-12
assert abs(P[0][0] - 0.5) < 1e-12
def test_page_example():
ens = [[0.0, 1.0], [1.0, 3.0], [2.0, 2.0]]
out = eakf_serial(ens, [2.0], lambda x: [x[0]], [1 / 3])
expect = [[5 / 4, 13 / 8], [7 / 4, 27 / 8], [9 / 4, 17 / 8]]
for a, b in zip(out, expect):
assert abs(a[0] - b[0]) < 1e-12 and abs(a[1] - b[1]) < 1e-12
mean, P = ensemble_moments(out)
assert abs(mean[1] - 19 / 8) < 1e-12
assert abs(P[1][1] - 13 / 16) < 1e-12
def test_serial_matches_kalman_moments():
rng = random.Random(41)
for _ in range(80):
n, p, N = rng.randint(1, 5), rng.randint(1, 5), 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)]
r = [rng.uniform(0.1, 2.0) for _ in range(p)]
yo = [rng.gauss(0, 2) for _ in range(p)]
out = eakf_serial(ens, yo, lambda x: scimat.matvec(H, x), r)
xa, Pa = kalman_moments(ens, yo, H, diag(r))
close_moments(out, xa, Pa)
def test_joint_matches_kalman_moments_with_correlated_R():
rng = random.Random(42)
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)]
out = eakf_joint(ens, yo, H, R)
xa, Pa = kalman_moments(ens, yo, H, R)
close_moments(out, xa, Pa)
def test_adjustment_matrix_identity():
# A P A^T equals the Kalman analysis covariance, also when P is singular (N < n + 1).
rng = random.Random(43)
n, N, p = 5, 3, 2
ens = [[rng.gauss(0, 1) for _ in range(n)] for _ in range(N)]
_, P = ensemble_moments(ens)
H = [[rng.uniform(-1, 1) for _ in range(n)] for _ in range(p)]
R = diag([0.5, 2.0])
A = adjustment_matrix(P, H, R)
APAt = scimat.matmul(scimat.matmul(A, P), scimat.transpose(A))
_, Pa = kalman_moments(ens, [0.0, 0.0], H, R)
for a in range(n):
for b in range(n):
assert abs(APAt[a][b] - Pa[a][b]) < 1e-9
def test_one_observation_serial_equals_joint_and_square_root_filter():
# For one scalar observation the serial EAKF, the joint EAKF and the reduced gain
# update x' - alpha K h x' of the serial EnSRF give the same members.
rng = random.Random(44)
for _ in range(20):
n, N = rng.randint(1, 4), rng.randint(2, 7)
ens = [[rng.gauss(0, 1) for _ in range(n)] for _ in range(N)]
h = [rng.uniform(-1, 1) for _ in range(n)]
r = rng.uniform(0.2, 2.0)
a = eakf_serial(ens, [0.3], lambda x: [scimat.dot(h, x)], [r])
b = eakf_joint(ens, [0.3], [h], [[r]])
xbar, P = ensemble_moments(ens)
Ph = scimat.matvec(P, h)
s = scimat.dot(h, Ph)
K = [v / (s + r) for v in Ph]
alpha = 1 / (1 + math.sqrt(r / (s + r)))
d = 0.3 - scimat.dot(h, xbar)
for i in range(N):
xp = scimat.sub(ens[i], xbar)
hxp = scimat.dot(h, xp)
c = [xbar[j] + K[j] * d + xp[j] - alpha * K[j] * hxp for j in range(n)]
for j in range(n):
assert abs(a[i][j] - c[j]) < 1e-9
assert abs(b[i][j] - c[j]) < 1e-9
def test_observation_with_no_spread_is_skipped():
ens = [[1.0, 0.0], [1.0, 2.0]]
out = eakf_serial(ens, [5.0], lambda x: [x[0]], [1.0])
assert out == ens
def test_localization_weight_zero_freezes_value():
rng = random.Random(45)
ens = [[rng.gauss(0, 1) for _ in range(3)] for _ in range(5)]
out = eakf_serial(ens, [1.0], lambda x: [x[0]], [0.5], loc_state=[[1.0, 0.3, 0.0]])
for x, z in zip(ens, out):
assert z[2] == x[2]
History
Anderson introduced the filter in 2001 for atmospheric models. His paper defined the adjustment matrix and showed in an appendix how to compute it with singular value decompositions. In 2003 he described the serial form as a least squares framework: a scalar update in observation space followed by a regression onto each state value. In the same year Tippett, Anderson, Bishop, Hamill and Whitaker showed that the EAKF, the ETKF and the filter of Whitaker and Hamill are all square root filters.
References
- J. L. Anderson, An ensemble adjustment Kalman filter for data assimilation, Monthly Weather Review 129(12) (2001) 2884-2903, the adjustment matrix A, and Appendix A for its existence and its computation with singular value decompositions
- J. L. Anderson, A local least squares framework for ensemble filtering, Monthly Weather Review 131(4) (2003) 634-642, the two step update: the scalar update in observation space and the regression onto the state
- M. K. Tippett, J. L. Anderson, C. H. Bishop, T. M. Hamill and J. S. Whitaker, Ensemble square root filters, Monthly Weather Review 131(7) (2003) 1485-1490, the EAKF as a square root filter and the nonuniqueness of the square root
- I. Grooms, A note on the formulation of the ensemble adjustment Kalman filter, arXiv:2006.02941 (2020), the adjustment matrix when the forecast covariance is singular
- 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, convergence of the EAKF to the Kalman filter as N goes to infinity, for linear models
- Geir Evensen, Data Assimilation: The Ensemble Kalman Filter, 2nd edition, Springer, 2009, Chapter 13, Square root analysis schemes
- 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 NP9ZCK Edit this page History Report an error Markdown