Algorithm Search⌘K

Algorithmadvanced

Ensemble transform Kalman filter

Also called ETKF.

Computes the analysis in the space spanned by the ensemble perturbations, with a symmetric square root transform of the ensemble.

Time
Θ(p^3 + p^2 N + p N^2 + N^3 + n N^2) worst
Space
Θ(N^2 + p N + n N) extra
Where
N = the ensemble size; n = the size of the state; p = the number of observations
Properties
analysis in ensemble spandeterministicnot perturbed observations
Origin
Craig H. Bishop, Brian J. Etherton, Sharanya J. Majumdar, 2001

The ensemble transform Kalman filter (ETKF) is an ensemble square root filter that does all of its algebra in the space of the ensemble. It writes each analysis member as the forecast mean plus a combination of the NN forecast perturbations, and it finds the coefficients from one N×NN \times N symmetric eigenproblem. The coefficients of the mean give the Kalman update of the mean, and a symmetric square root gives perturbations with exactly the Kalman analysis covariance of the sample prior. It uses no perturbed observations. Because NN is usually much smaller than the size of the state, the cost of the analysis is small, and the form is the basis of the LETKF.

In plain words

Run a model NN times from slightly different starts. Every forecast is the average forecast plus a difference. The ETKF says that the corrected forecasts should be the average plus mixes of these same differences. It then only has to find NN numbers for the new average and an N×NN \times N table of numbers for the new members, which is a small problem even when each forecast has millions of values. The table is chosen in a special symmetric way, so that the new members are spread out by exactly the right amount and their average stays where the Kalman filter puts it.

The problem

Input. A forecast ensemble x1,…,xN∈Rnx_1, \ldots, x_N \in \mathbb R^n, observations yo∈Rpy^o \in \mathbb R^p with error covariance RR, an observation operator HH (it may be nonlinear), and a multiplicative inflation ρ≥1\rho \ge 1 of the covariance. The notation is that of Ide, Courtier, Ghil and Lorenc (1997). In the letters of the Kalman filter page, HH is its CC, the model MM is its AA, the forecast xfx^f and PfP^f are its predicted m−m^- and P−P^-, and the analysis xax^a and PaP^a are its filtered mm and PP.

Output. An analysis ensemble x1a,…,xNax^a_1, \ldots, x^a_N whose mean is xˉ+K(yo−Hxˉ)\bar x + K(y^o - H\bar x) and whose sample covariance is (I−KH)ρPf(I - KH)\rho P^f, where PfP^f is the sample covariance of the forecast and K=ρPfH⊤(HρPfH⊤+R)−1K = \rho P^f H^\top(H\rho P^f H^\top + R)^{-1} (for a linear HH).

The algorithm

XX and YY are the unscaled perturbations, so Pf=XX⊤/(N−1)P^f = X X^\top/(N - 1).

  1. ETKF(x_1..x_N, y^o, H, R, rho)
  2. 1xbar <- mean of x_i; X <- [x_1 - xbar, ..., x_N - xbar]
  3. 2y_i <- H(x_i); ybar <- mean of y_i; Y <- [y_1 - ybar, ..., y_N - ybar]
  4. 3C <- Y^T R^-1 ▷ N x p
  5. 4A <- (N - 1)/rho I + C Y ▷ N x N, symmetric positive definite
  6. 5Q, Λ <- eigendecomposition of A
  7. 6P~ <- Q Λ^-1 Q^T; W <- Q ((N - 1) Λ^-1)^(1/2) Q^T
  8. 7wbar <- P~ C (y^o - ybar)
  9. 8x^a_i <- xbar + X (wbar + W_i) for each member i
  10. 9return x^a_1..x^a_N

Line L2 is the only place that uses the observation operator, and it calls it once for each member. Line L4 is the inverse of the analysis covariance in ensemble space: the prior part (N−1)/ρ I(N - 1)/\rho\, I plus the information from the observations. Line L6 takes the inverse and the symmetric square root from the same eigenpairs. Line L7 gives the weights of the mean and line L8 the members. The code uses the cyclic Jacobi method for line L5. With a diagonal RR, line L3 is a scaling of the rows of YY.

Example

Take one variable, two members x1=−1x_1 = -1 and x2=1x_2 = 1, H=1H = 1, R=1R = 1, ρ=1\rho = 1 and yo=1y^o = 1. Then xˉ=0\bar x = 0, X=Y=(−1,1)X = Y = (-1, 1), Pf=2P^f = 2 and the Kalman gain is K=2/3K = 2/3.

Line L4 gives A=(2−1−12)A = \begin{pmatrix} 2 & -1 \\ -1 & 2 \end{pmatrix}, with the eigenvalue 11 on (1,1)/2(1, 1)/\sqrt 2 and 33 on (1,−1)/2(1, -1)/\sqrt 2. So P~=13(2112)\tilde P = \tfrac13\begin{pmatrix} 2 & 1 \\ 1 & 2\end{pmatrix} and line L7 gives wˉ=(−1/3,1/3)\bar w = (-1/3, 1/3), so the mean is Xwˉ=2/3X\bar w = 2/3. Line L6 gives

W=12(1+1/31−1/31−1/31+1/3),W = \frac12\begin{pmatrix} 1 + 1/\sqrt 3 & 1 - 1/\sqrt 3 \\ 1 - 1/\sqrt 3 & 1 + 1/\sqrt 3\end{pmatrix},

and the members are 2/3∓1/3≈0.0892/3 \mp 1/\sqrt 3 \approx 0.089 and 1.2441.244, with the sample variance 2/3=(1−K)Pf2/3 = (1 - K)P^f. The rows of WW sum to 11, so the mean stays at 2/32/3. If WW is replaced by the Cholesky factor of P~\tilde P, the members become 2/3−1/62/3 - 1/\sqrt 6 and 2/3+1/22/3 + 1/\sqrt 2, and their mean moves to about 0.8160.816. With x=∓1/2x = \mp 1/\sqrt 2 (sample mean 00, variance 11) the analysis has the mean 1/21/2 and the variance 1/21/2, the check value of the posterior of a N(0,1)N(0, 1) prior with y=1y = 1 and R=1R = 1.

A measurement. On the Lorenz-96 model with n=40n = 40, F=8F = 8, RK4 with step 0.050.05, every other variable observed every 0.050.05 time units with R=IR = I, the reference code without localization gave these mean analysis RMSE values over cycles 501 to 1500 (one seed):

NN ρ=1.02\rho = 1.02 1.051.05 1.11.1 1.21.2 1.31.3 1.51.5
20 4.54 4.21 1.21 0.409 0.472 0.606
40 0.275 0.298

With N=20N = 20 the filter loses the truth unless the inflation is large, and the RMSE of 4.54.5 is worse than the 3.73.7 of the mean of a free ensemble. With N=40N = 40 it works with little inflation. The LETKF with N=20N = 20 reached 0.330.33 with localization on the same problem.

Correctness

The proof shows that AA is positive definite with eigenvalues at least (N−1)/ρ(N - 1)/\rho, so every step is defined (Lemma 1). The symmetric square root maps the vector of ones to ρ\sqrt\rho times itself, so the members keep the mean (Lemma 2). For a linear HH the analysis ensemble has exactly the mean xˉ+Kd\bar x + K d and the sample covariance (I−KH)ρPf(I - KH)\rho P^f (Theorem 4, a theorem), and every member stays in xˉ\bar x plus the span of the forecast perturbations. For a linear Gaussian model the ETKF converges to the Kalman filter as N→∞N \to \infty (Kwiatkowski and Mandel 2015). For finite NN and a nonlinear model there is no such guarantee.

Proof: The ETKF gives an ensemble with exactly the Kalman analysis mean and covariance of the sample priorfull

Setting. There are N≥2N \ge 2 forecast members x1,…,xN∈Rnx_1, \ldots, x_N \in \mathbb R^n and observations yo∈Rpy^o \in \mathbb R^p with a symmetric positive definite error covariance RR. XX (n×Nn \times N) has the columns xi−xˉx_i - \bar x (line L1) and YY (p×Np \times N) has the columns h(xi)−yˉh(x_i) - \bar y (line L2). They are unscaled, so the sample covariance is Pf=XX⊤/(N−1)P^f = X X^\top/(N - 1), and X1=0X\mathbf 1 = 0, Y1=0Y \mathbf 1 = 0 for the vector of ones 1\mathbf 1. Let ρ>0\rho > 0 be the inflation, γ=(N−1)/ρ\gamma = (N - 1)/\rho and P=ρPf=XX⊤/γP = \rho P^f = X X^\top/\gamma. Lines L3 to L7 compute C=Y⊤R−1C = Y^\top R^{-1}, A=γI+CYA = \gamma I + C Y, P~=A−1\tilde P = A^{-1}, W=N−1 P~1/2W = \sqrt{N - 1}\,\tilde P^{1/2} (symmetric) and wˉ=P~C(yo−yˉ)\bar w = \tilde P C (y^o - \bar y). Line L8 returns xia=xˉ+X(wˉ+Wi)x^a_i = \bar x + X(\bar w + W_i), with WiW_i the column ii of WW.

Lemma 1 (the matrices exist). AA is symmetric positive definite, with eigenvalues at least γ\gamma. So P~\tilde P and its symmetric square root exist, and WW is symmetric positive definite.

Proof. z⊤Az=γ∥z∥2+(Yz)⊤R−1(Yz)≥γ∥z∥2z^\top A z = \gamma \|z\|^2 + (Y z)^\top R^{-1}(Y z) \ge \gamma\|z\|^2. With A=QΛQ⊤A = Q\Lambda Q^\top (line L5), P~=QΛ−1Q⊤\tilde P = Q\Lambda^{-1}Q^\top and P~1/2=QΛ−1/2Q⊤\tilde P^{1/2} = Q \Lambda^{-1/2} Q^\top, which is what line L6 forms. □\square

Lemma 2 (the transform keeps the mean). W1=ρ 1W \mathbf 1 = \sqrt\rho\,\mathbf 1 and 1⊤wˉ=0\mathbf 1^\top \bar w = 0.

Proof. A1=γ1+CY1=γ1A \mathbf 1 = \gamma \mathbf 1 + C Y \mathbf 1 = \gamma\mathbf 1, so 1\mathbf 1 is an eigenvector of AA with eigenvalue γ\gamma, and of every function of AA: P~1=1/γ\tilde P \mathbf 1 = \mathbf 1/\gamma and W1=(N−1)/γ 1=ρ 1W\mathbf 1 = \sqrt{(N - 1)/\gamma}\,\mathbf 1 = \sqrt\rho\,\mathbf 1. Then 1⊤wˉ=(P~1)⊤C(yo−yˉ)=γ−1(Y1)⊤R−1(yo−yˉ)=0\mathbf 1^\top \bar w = (\tilde P \mathbf 1)^\top C (y^o - \bar y) = \gamma^{-1}(Y\mathbf 1)^\top R^{-1}(y^o - \bar y) = 0. □\square

Lemma 3 (push-through identity). Y⊤(YY⊤+γR)−1=(Y⊤R−1Y+γI)−1Y⊤R−1=P~CY^\top (Y Y^\top + \gamma R)^{-1} = (Y^\top R^{-1} Y + \gamma I)^{-1} Y^\top R^{-1} = \tilde P C.

Proof. (Y⊤R−1Y+γI)Y⊤=Y⊤R−1(YY⊤+γR)(Y^\top R^{-1} Y + \gamma I) Y^\top = Y^\top R^{-1}(Y Y^\top + \gamma R), and both brackets are invertible. □\square

Theorem 4 (exact Kalman moments). Let h(x)=Hxh(x) = H x be linear and K=PH⊤(HPH⊤+R)−1K = P H^\top (H P H^\top + R)^{-1}. The analysis ensemble has the mean xˉ+K(yo−Hxˉ)\bar x + K(y^o - H \bar x) and the sample covariance (I−KH)P(I - KH)P.

Proof. Y=HXY = H X and yˉ=Hxˉ\bar y = H \bar x. K=XY⊤(YY⊤+γR)−1=XP~CK = X Y^\top (Y Y^\top + \gamma R)^{-1} = X \tilde P C by Lemma 3, so K(yo−Hxˉ)=XwˉK(y^o - H\bar x) = X \bar w. By Lemma 2 the members have the mean xˉ+Xwˉ+XW1/N=xˉ+Xwˉ+ρX1/N=xˉ+Xwˉ\bar x + X\bar w + X W\mathbf 1/N = \bar x + X \bar w + \sqrt\rho X \mathbf 1/N = \bar x + X\bar w. Their perturbations are the columns of XWX W, so the sample covariance is XWW⊤X⊤/(N−1)=XP~X⊤X W W^\top X^\top/(N - 1) = X \tilde P X^\top. Finally

(I−KH)P=XX⊤−XP~CYX⊤γ=XP~(A−CY)X⊤γ=XP~X⊤.□(I - KH)P = \frac{X X^\top - X \tilde P C Y X^\top}{\gamma} = \frac{X \tilde P (A - C Y) X^\top}{\gamma} = X \tilde P X^\top. \qquad\square

With N=2N = 2, x=(−1/2,1/2)x = (-1/\sqrt 2, 1/\sqrt 2), H=1H = 1, R=1R = 1, ρ=1\rho = 1 and yo=1y^o = 1, P=1P = 1 and K=1/2K = 1/2, so the analysis has the mean 1/21/2 and the variance 1/21/2, which is the check value of the page.

Corollary 5 (the analysis stays in the ensemble space). Every analysis member lies in xˉ+range(X)\bar x + \mathrm{range}(X), a space of dimension at most N−1N - 1.

Proof. xia−xˉ=X(wˉ+Wi)x^a_i - \bar x = X(\bar w + W_i). □\square

Remarks. The Kalman update here uses the sample covariance, so it is the true posterior only when PfP^f is the true forecast covariance and the errors are Gaussian. For a linear Gaussian model and exact forecasts the sample covariance converges as N→∞N \to \infty, and the ETKF converges to the Kalman filter (Kwiatkowski and Mandel 2015). For a nonlinear hh the matrix YY replaces HXH X, which is a heuristic, and Theorem 4 does not apply. Any W′=WUW' = W U with UU orthogonal and U1=1U \mathbf 1 = \mathbf 1 gives the same mean and covariance. A square root W′W' with W′1W'\mathbf 1 not a multiple of 1\mathbf 1, such as a Cholesky factor of (N−1)P~(N - 1)\tilde P, gives members with the mean xˉ+Xwˉ+XW′1/N\bar x + X\bar w + X W'\mathbf 1/N. In general this is not the Kalman mean, and the sample covariance about the new mean is then smaller than XP~X⊤X\tilde P X^\top.

Termination. Lines L1 to L4 and L6 to L8 are finite sums and one linear solve with the positive definite RR. Line L5 runs the cyclic Jacobi method for at most a fixed number of sweeps. So the algorithm returns at line L9. ■\blacksquare

Complexity

Line L3 costs Θ(p3+p2N)\Theta(p^3 + p^2 N) with a dense RR (one factorization and NN solves) and Θ(pN)\Theta(p N) with a diagonal RR. Line L4 costs Θ(pN2)\Theta(p N^2), line L5 Θ(N3)\Theta(N^3) for a fixed number of Jacobi sweeps, line L6 Θ(N3)\Theta(N^3), line L7 Θ(pN+N2)\Theta(p N + N^2) and line L8 Θ(nN2)\Theta(n N^2). The total is Θ(p3+p2N+pN2+N3+nN2)\Theta(p^3 + p^2 N + p N^2 + N^3 + n N^2), without the NN model runs and the NN applications of HH. The cost is linear in nn and in pp for a diagonal RR, which is why the method suits large models. The extra space is Θ(N2+pN+nN)\Theta(N^2 + pN + nN) for AA, WW, YY and XX.

Properties

  • Deterministic. For a given forecast ensemble the result is fixed, with no sampling noise from perturbed observations.
  • Exact second moments. For a linear HH, the mean and covariance of the members are exactly the Kalman values for the sample covariance.
  • Mean preserving. The symmetric square root keeps the mean of the members equal to the analysis mean.
  • Low rank. The analysis stays in the span of the forecast perturbations, so observations can only correct N−1N - 1 directions.
  • Linear in the state. Line L8 is one n×Nn \times N by N×NN \times N product, so the members can be updated in place, block by block.
  • Same as the other square root filters. The EnSRF of Whitaker and Hamill and the EAKF give the same mean and covariance; they differ in the choice of the orthogonal factor (Tippett et al. 2003).

Variants and improvements

  • The original form. Bishop, Etherton and Majumdar (2001) used the eigendecomposition CΓC⊤C\Gamma C^\top of the scaled Y⊤R−1YY^\top R^{-1} Y and the transform C(Γ+I)−1/2C(\Gamma + I)^{-1/2}. Wang, Bishop and Julier (2004) showed that it does not always keep the mean and gave a centered form. Multiplying the transform by C⊤C^\top on the right gives the symmetric square root used here.
  • LETKF. Do the analysis for each grid point with the nearby observations only (LETKF), which adds localization at almost no cost.
  • Inflation. Multiply PfP^f by ρ\rho as in line L4, or use the relaxation methods of covariance inflation.
  • Transforms for the smoother. The same weights apply to past states, which gives an ensemble smoother at the cost of line L8 for each stored time (see the ensemble Kalman smoother).
  • Random rotations. The transform can be followed by a random orthogonal UU with U1=1U\mathbf 1 = \mathbf 1, which keeps the moments and changes the higher order statistics.

When to use it

Use the ETKF for a model with a modest number of observations or as the building block of the LETKF, when the observation errors are known and the observation operator can be evaluated but not linearized. It is a good choice when a deterministic analysis without sampling noise is wanted. When the ensemble is small compared with the number of growing directions of the model, the global ETKF needs strong inflation or fails, as in the measurement above. Then use a localized filter such as the LETKF or the EnKF with covariance localization.

Pitfalls

  • A triangular square root (line L6). A Cholesky factor of P~\tilde P has the right product but moves the mean of the members, as in the example. Use the symmetric square root.
  • Scaled and unscaled perturbations (line L4). With XX divided by N−1\sqrt{N - 1} the prior term becomes I/ρI/\rho and W=P~1/2W = \tilde P^{1/2}. Mixing the two conventions gives a covariance that is wrong by the factor N−1N - 1.
  • Inflation of the perturbations or of the covariance (line L4). Here ρ\rho multiplies the covariance. If ρ\rho is meant for the perturbations, use ρ2\rho^2.
  • Too few members. With N−1N - 1 smaller than the number of unstable directions, the filter can diverge. The spread becomes small, the filter ignores the observations, and the error grows.
  • A nonlinear H. The update uses the linear regression of the predicted observations on the state. For a strongly nonlinear HH the analysis can be poor, and an iterative ensemble method is better.

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.

ensemble_transform_kalman_filter.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/ensemble-transform-kalman-filter/. The authors are listed in prov/5GQ96N.jsonl.

"""Ensemble transform Kalman filter (ETKF), in the form of Hunt, Kostelich and Szunyogh (2007).

Notation of Ide, Courtier, Ghil and Lorenc (1997). The forecast ensemble has
N members x_1..x_N in R^n, the observations y^o in R^p have the error
covariance R, and h maps a state to R^p (it may be nonlinear).

X and Y hold the unscaled perturbations x_i - xbar and h(x_i) - ybar, so the
sample covariance is P^f = X X^T / (N - 1). The analysis works in the
N-dimensional ensemble space:

    A = (N - 1) / rho I + Y^T R^-1 Y = Q diag(lam) Q^T
    P~ = A^-1,  wbar = P~ Y^T R^-1 (y^o - ybar),  W = sqrt(N - 1) P~^(1/2)
    x^a_i = xbar + X (wbar + W_i)

W is the symmetric square root. rho multiplies the covariance, so the
perturbations grow by sqrt(rho). Cost: O(p^3 + p^2 N) for R^-1 Y with a dense
R, O(p N^2) for A, O(N^3) for the Jacobi eigendecomposition with a fixed
number of sweeps, and O(n N^2) for the update.
"""

import math

import scimat


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 etkf_transform(Y, R, innov, rho=1.0):
    """Return (wbar, W) for the unscaled observation perturbations Y (p by N).

    innov = y^o - ybar. W is the symmetric matrix sqrt(N - 1) P~^(1/2).
    """
    N = len(Y[0])
    C = scimat.transpose(scimat.solve(R, Y))  # @line L3
    A = scimat.add(scimat.scale((N - 1) / rho, scimat.eye(N)), scimat.matmul(C, Y))  # @line L4
    lam, Q = sym_eig(A)  # @line L5
    Pt = [[sum(Q[a][m] * Q[b][m] / lam[m] for m in range(N)) for b in range(N)] for a in range(N)]  # @line L6
    W = [[sum(Q[a][m] * math.sqrt((N - 1) / lam[m]) * Q[b][m] for m in range(N)) for b in range(N)] for a in range(N)]
    wbar = scimat.matvec(Pt, scimat.matvec(C, innov))  # @line L7
    return wbar, W


def etkf_analysis(ens, yo, h, R, rho=1.0):
    """Return the ETKF analysis ensemble (a list of N members).

    ens: the forecast members, each a list of n numbers. yo: the observations.
    h(x): the observation operator. R: the p by p observation error
    covariance (symmetric positive definite). rho: multiplicative inflation
    of the covariance.
    """
    N, n = len(ens), len(ens[0])
    xbar = [sum(x[j] for x in ens) / N for j in range(n)]  # @line L1
    X = [[ens[i][j] - xbar[j] for i in range(N)] for j in range(n)]
    hx = [list(h(x)) for x in ens]  # @line L2
    p = len(yo)
    ybar = [sum(v[k] for v in hx) / N for k in range(p)]
    Y = [[hx[i][k] - ybar[k] for i in range(N)] for k in range(p)]
    wbar, W = etkf_transform(Y, R, [yo[k] - ybar[k] for k in range(p)], rho)
    out = []
    for i in range(N):  # @line L8
        coef = [wbar[k] + W[k][i] for k in range(N)]
        out.append([xbar[j] + scimat.dot(X[j], coef) for j in range(n)])
    return out  # @line L9


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_transform_kalman_filter.py 127 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/ensemble-transform-kalman-filter/. The authors are listed in prov/5GQ96N.jsonl.

import math
import random

import scimat
from ensemble_transform_kalman_filter import ensemble_moments, etkf_analysis, etkf_transform, sym_eig


def kalman_moments(ens, yo, H, R, rho=1.0):
    """Oracle: the Kalman analysis mean and covariance for the inflated sample covariance."""
    n = len(ens[0])
    xbar, Pf = ensemble_moments(ens)
    P = scimat.scale(rho, Pf)
    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 random_spd(rng, n):
    L = [[rng.uniform(-1, 1) for _ in range(n)] for _ in range(n)]
    return scimat.add(scimat.matmul(L, scimat.transpose(L)), scimat.scale(0.5, scimat.eye(n)))


def test_scalar_check_value():
    s = 1 / math.sqrt(2.0)
    out = etkf_analysis([[-s], [s]], [1.0], lambda x: [x[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():
    out = etkf_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
    wbar, W = etkf_transform([[-1.0, 1.0]], [[1.0]], [1.0])
    assert abs(wbar[0] + 1 / 3) < 1e-12 and abs(wbar[1] - 1 / 3) < 1e-12
    a, b = (1 + 1 / math.sqrt(3)) / 2, (1 - 1 / math.sqrt(3)) / 2
    for i, j, v in ((0, 0, a), (0, 1, b), (1, 0, b), (1, 1, a)):
        assert abs(W[i][j] - v) < 1e-12


def test_cholesky_square_root_moves_the_mean():
    # The pitfall of the page: a triangular square root of P~ does not keep the mean.
    Pt = [[2 / 3, 1 / 3], [1 / 3, 2 / 3]]
    L = scimat.cholesky(Pt)
    X = [-1.0, 1.0]
    members = [2 / 3 + sum(X[k] * L[k][i] for k in range(2)) for i in range(2)]
    mean = sum(members) / 2
    assert abs(mean - (2 / 3 + (1 / math.sqrt(2) - 1 / math.sqrt(6)) / 2)) < 1e-12
    assert mean - 2 / 3 > 0.14


def test_matches_kalman_moments():
    rng = random.Random(21)
    for _ in range(60):
        n, p, N = rng.randint(1, 5), 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)] for _ in range(p)]
        R = random_spd(rng, p)
        yo = [rng.gauss(0, 2) for _ in range(p)]
        rho = rng.choice([1.0, 1.1, 1.5])
        out = etkf_analysis(ens, yo, lambda x: scimat.matvec(H, x), R, rho)
        ma, Pe = ensemble_moments(out)
        xa, Pa = kalman_moments(ens, yo, H, R, rho)
        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(Pa[a][b]))


def test_transform_is_symmetric_and_keeps_ones():
    rng = random.Random(22)
    for _ in range(30):
        p, N = rng.randint(1, 5), rng.randint(2, 8)
        Y = [[rng.gauss(0, 1) for _ in range(N)] for _ in range(p)]
        Y = [[v - sum(row) / N for v in row] for row in Y]
        rho = rng.choice([1.0, 1.21])
        wbar, W = etkf_transform(Y, random_spd(rng, p), [rng.gauss(0, 1) for _ in range(p)], rho)
        for a in range(N):
            assert abs(sum(W[a]) - math.sqrt(rho)) < 1e-10
            for b in range(N):
                assert abs(W[a][b] - W[b][a]) < 1e-12
        assert abs(sum(wbar)) < 1e-10  # wbar is orthogonal to the ones vector


def test_analysis_stays_in_ensemble_span():
    # n = 6 and N = 3: the analysis members lie in xbar + span of the forecast perturbations.
    rng = random.Random(23)
    n, N = 6, 3
    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(4)]
    out = etkf_analysis(ens, [1.0, 0.0, -1.0, 2.0], lambda x: scimat.matvec(H, x), scimat.eye(4))
    xbar, _ = ensemble_moments(ens)
    D = [[ens[i][j] - xbar[j] for j in range(n)] for i in range(2)]  # two perturbations span the space
    G = scimat.matmul(D, scimat.transpose(D))
    for x in out:
        z = scimat.sub(x, xbar)
        c = scimat.solve(G, scimat.matvec(D, z))
        resid = scimat.sub(z, scimat.matvec(scimat.transpose(D), c))
        assert scimat.norm2(resid) < 1e-10


def test_nonlinear_operator_runs_and_reduces_spread():
    rng = random.Random(24)
    n, N = 3, 10
    ens = [[1.0 + rng.gauss(0, 1) for _ in range(n)] for _ in range(N)]
    h = lambda x: [x[0] ** 2, x[1] + x[2] ** 3 / 10]
    out = etkf_analysis(ens, [1.5, 1.0], h, [[0.1, 0.0], [0.0, 0.1]])
    _, Pf = ensemble_moments(ens)
    _, Pa = ensemble_moments(out)
    assert sum(Pa[j][j] for j in range(n)) < sum(Pf[j][j] for j in range(n))


def test_sym_eig_reconstructs():
    rng = random.Random(25)
    for n in (1, 3, 7):
        A = random_spd(rng, n)
        vals, V = sym_eig(A)
        for i in range(n):
            for j in range(n):
                assert abs(sum(V[i][m] * vals[m] * V[j][m] for m in range(n)) - A[i][j]) < 1e-12

History

Craig Bishop, Brian Etherton and Sharanya Majumdar introduced the ETKF in 2001 to predict how much targeted extra observations would reduce the forecast error. Tippett, Anderson, Bishop, Hamill and Whitaker (2003) showed that it, the EAKF and the EnSRF are square root filters that differ only in the choice of the square root. Wang, Bishop and Julier (2004) showed that the original transform does not always keep the mean and gave a centered form. Hunt, Kostelich and Szunyogh (2007) wrote the analysis with the symmetric square root in the form used here and made it local, and Sakov and Oke (2008) studied which transforms keep the mean.

References

  1. C. H. Bishop, B. J. Etherton and S. J. Majumdar, Adaptive sampling with the ensemble transform Kalman filter. Part I: Theoretical aspects, Monthly Weather Review 129(3) (2001) 420-436, the transformation matrix of the ensemble perturbations from an eigendecomposition in ensemble space
  2. X. Wang, C. H. Bishop and S. J. Julier, Which is better, an ensemble of positive-negative pairs or a centered spherical simplex ensemble?, Monthly Weather Review 132(7) (2004) 1590-1605, the condition that the transform keeps the ensemble mean, and a centered form of the ETKF
  3. 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 analysis in ensemble space with P~ = ((N - 1)I/rho + Y^T R^-1 Y)^-1 and the symmetric square root
  4. 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 ETKF as one of the ensemble square root filters
  5. P. Sakov and P. R. Oke, Implications of the form of the ensemble transformation in the ensemble square root filters, Monthly Weather Review 136(3) (2008) 1042-1053, the transforms that keep the mean, and the symmetric solution
  6. 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 ETKF to the Kalman filter as N goes to infinity, for linear models
  7. Geir Evensen, Data Assimilation: The Ensemble Kalman Filter, 2nd edition, Springer, 2009, Chapter 13, Square root analysis schemes
  8. K. Ide, P. Courtier, M. Ghil and A. C. Lorenc, Unified notation for data assimilation, operational, sequential and variational, Journal of the Meteorological Society of Japan 75(1B) (1997) 181-189, the notation used here

Where this leads

About this page

The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.

LadderLevelWhat the next level needs
Human proofH1 sketch
  • a full proof of time.worst
  • a full proof of space.extra
LeanL0 no Lean part
  • name a Lean module in the lean field (07)
Code (python)I0 not checked yet
  • the tests did not run in this build
VisualV0 none
  • add viz/scene.ts or a figure (10)
WritingW2 basic
  • a scene preset for the example