Algorithm Search⌘K

Algorithmcore

Ensemble Kalman filter

Also called EnKF.

Propagates an ensemble of states through the model and uses its sample covariance in the Kalman update, with perturbed observations for each member.

Time
Θ(N p (n + p) + p^3) worst
Space
Θ(n p + p^2 + N (n + p)) extra
Where
N = the ensemble size; n = the size of the state; p = the number of observations
Properties
derivative freerandomizedperturbed observations
Origin
Geir Evensen, Gerrit Burgers, Peter Jan van Leeuwen, Peter L. Houtekamer, Herschel L. Mitchell, 1994

The ensemble Kalman filter (EnKF) is a Monte Carlo form of the Kalman filter for large and nonlinear models. It keeps an ensemble of NN model states. In the forecast step every member is run through the model, so the ensemble carries the error statistics forward with no tangent linear model and no n×nn \times n covariance matrix. In the analysis step the sample covariance of the ensemble takes the place of the forecast covariance in the Kalman gain, and each member moves towards its own randomly perturbed copy of the observations. The perturbations are needed: without them the analysis spread is too small. With localization a few tens of members can be enough for a model with many more variables, as the measurement below shows for a small model.

In plain words

Instead of carrying one best guess and a large table of its error variances, carry a few dozen possible states and run each through the model. Their spread shows how uncertain the forecast is, and their joint variations show which variables go up and down together. When observations arrive, each member is pulled towards the data by the amount that the Kalman rule gives for that spread. Each member sees a slightly different, randomly disturbed copy of the data. This keeps the cloud of members as wide as the uncertainty after the update really is.

The problem

Input. A forecast ensemble x1,…,xN∈Rnx_1, \ldots, x_N \in \mathbb R^n, observations yo∈Rpy^o \in \mathbb R^p, an observation operator HH (it may be nonlinear), a symmetric positive definite observation error covariance RR, a source of random numbers, and optional localization weights. The notation is that of Ide, Courtier, Ghil and Lorenc (1997). In the letters of the Kalman filter page, 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. For a linear HH and no localization, its mean is the Kalman mean xˉ+K(yo−Hxˉ)\bar x + K(y^o - H\bar x) plus KK times the mean of the perturbations, and its expected sample covariance is (I−KH)Pf(I - KH)P^f, where PfP^f is the sample covariance of the forecast and K=PfH⊤(HPfH⊤+R)−1K = P^f H^\top(HP^fH^\top + R)^{-1}.

The algorithm

The forecast step runs each member through the model, xif←M(xia)x^f_i \leftarrow M(x^a_i), usually followed by covariance inflation. The analysis step is below. XX and YY hold the unscaled perturbations of the state and of the predicted observations.

  1. EnKF-ANALYSIS(x_1..x_N, y^o, H, R)
  2. 1y_i <- H(x_i) for each member i
  3. 2xbar, ybar <- means; X, Y <- perturbations
  4. 3PH^T <- X Y^T / (N - 1); HPH^T <- Y Y^T / (N - 1) ▷ times the weights, if localized
  5. 4draw ε_i ~ N(0, R) for each member i
  6. 5S <- HPH^T + R
  7. 6d_i <- y^o + ε_i - y_i
  8. 7x^a_i <- x_i + PH^T S^-1 d_i for each member i
  9. 8return x^a_1..x^a_N

Line L3 is where the ensemble replaces the covariance. For a linear HH the two products are exactly PfH⊤P^fH^\top and HPfH⊤HP^fH^\top, and the full n×nn \times n matrix PfP^f is never formed. Line L4 draws a new perturbation for each member and each analysis. Line L7 solves one p×pp \times p system with NN right sides.

Example

Take two members x=(−1,1)x = (-1, 1), a scalar state observed directly with yo=1y^o = 1 and R=1R = 1, and the perturbations ε=(−1/2,1/2)\varepsilon = (-1/2, 1/2). The sample variance is Pf=2P^f = 2, so K=2/3K = 2/3. Line L7 gives x1a=−1+23(1−12+1)=0x^a_1 = -1 + \tfrac23(1 - \tfrac12 + 1) = 0 and x2a=1+23(1+12−1)=4/3x^a_2 = 1 + \tfrac23(1 + \tfrac12 - 1) = 4/3. The mean 2/32/3 is the Kalman mean, because the perturbations have mean zero. The variance is 8/98/9, while the Kalman value is (1−K)Pf=2/3(1 - K)P^f = 2/3: with only two members the perturbations add sampling error. Over many draws of ε\varepsilon the expected variance is 2/32/3 (Theorem 3 of the proof).

For the check value of the page group: with two members ∓1/2\mp 1/\sqrt 2 (sample mean 00, variance 11), yo=1y^o = 1 and R=1R = 1, the mean and the variance over 20000 draws of the perturbations were 0.50.5 and 0.50.5 within 0.010.01.

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, N=20N = 20, multiplicative inflation ρ\rho of the forecast covariance and a Gaspari-Cohn weight with half-width cc grid units on the gain, the mean analysis RMSE over cycles 501 to 1500 was (one seed, about 3 ms for each analysis in pure Python):

cc ρ\rho RMSE
4 1.02 0.398
4 1.05 0.384
4 1.1 0.409
6 1.05 0.352
8 1.02 1.486
8 1.05 0.347
8 1.1 0.355
10 1.1 0.345
none 1.2 4.65
none 1.5 4.85

The free ensemble mean has an RMSE of about 3.73.7. On the same runs the serial EnSRF had 0.3730.373 with c=4c = 4 and ρ=1.02\rho = 1.02, and without localization it reached 0.4090.409 with ρ=1.2\rho = 1.2, where the EnKF fails. The noise of the perturbed observations costs accuracy, most of all with weak localization.

Correctness

The proof shows for a linear HH that line L3 gives the Kalman gain of the sample prior (Lemma 1), that the analysis mean is the Kalman mean plus KεˉK\bar\varepsilon (Lemma 2), and that for independent draws εi∼N(0,R)\varepsilon_i \sim N(0, R) the expected analysis covariance is (I−KH)Pf(I - KH)P^f (Theorem 3, from Burgers, van Leeuwen and Evensen 1998). Without the perturbations the covariance is too small by KRK⊤KRK^\top (Corollary 4). For a linear model, Mandel, Cobb and Beezley (2011) prove that the EnKF converges to the Kalman filter as N→∞N \to \infty. For a finite ensemble, a nonlinear model or localization, the filter is an approximation whose quality is measured, not proved. The update is linear in the data, so for non-Gaussian errors it is not the Bayesian update. A particle filter aims at the Bayesian posterior, at a much higher cost.

Proof: The perturbed observation EnKF gives the Kalman mean and, in expectation, the Kalman covariance of the sample priorfull

Setting. There are N≥2N \ge 2 forecast members x1,…,xN∈Rnx_1, \ldots, x_N \in \mathbb R^n with mean xˉ\bar x, unscaled perturbations XX (n×Nn \times N, column ii is xi−xˉx_i - \bar x) and sample covariance P=XX⊤/(N−1)P = XX^\top/(N - 1). The observations are yo∈Rpy^o \in \mathbb R^p with a linear operator HH and a symmetric positive definite error covariance RR. There is no localization until the remarks. The Kalman values for the sample prior are

K=PH⊤(HPH⊤+R)−1,xˉa=xˉ+K(yo−Hxˉ),Pa=(I−KH)P.K = PH^\top(HPH^\top + R)^{-1}, \qquad \bar x^a = \bar x + K(y^o - H\bar x), \qquad P^a = (I - KH)P.

The perturbations ε1,…,εN\varepsilon_1, \ldots, \varepsilon_N of line L4 have the mean εˉ\bar\varepsilon, the centred values ei=εi−εˉe_i = \varepsilon_i - \bar\varepsilon (columns of EE) and the sample covariance C=EE⊤/(N−1)C = EE^\top/(N - 1).

Lemma 1 (the gain). For a linear HH, line L3 computes PH⊤PH^\top and HPH⊤HPH^\top, so the matrix used in line L7 is the Kalman gain KK of the sample prior.

Proof. Line L1 gives yi=Hxiy_i = Hx_i, so yˉ=Hxˉ\bar y = H\bar x and Y=HXY = HX. Then XY⊤/(N−1)=XX⊤H⊤/(N−1)=PH⊤XY^\top/(N - 1) = XX^\top H^\top/(N - 1) = PH^\top and YY⊤/(N−1)=HPH⊤YY^\top/(N - 1) = HPH^\top. Lines L5 and L7 use PH⊤S−1PH^\top S^{-1} with S=HPH⊤+RS = HPH^\top + R. □\square

Lemma 2 (members, mean and perturbations). The analysis members are xia=xi+K(yo+εi−Hxi)x^a_i = x_i + K(y^o + \varepsilon_i - Hx_i). Their mean is xˉa+Kεˉ\bar x^a + K\bar\varepsilon and their perturbations are

Xa=(I−KH)X+KE.X^a = (I - KH)X + KE.

Proof. Lines L6 and L7 give the first formula. Average it over ii to get xˉ+K(yo+εˉ−Hxˉ)=xˉa+Kεˉ\bar x + K(y^o + \bar\varepsilon - H\bar x) = \bar x^a + K\bar\varepsilon. Subtract the mean from each member to get column ii of XaX^a: (xi−xˉ)−KH(xi−xˉ)+Kei(x_i - \bar x) - KH(x_i - \bar x) + K e_i. □\square

Theorem 3 (Burgers, van Leeuwen and Evensen 1998). Let the forecast ensemble be fixed and let ε1,…,εN\varepsilon_1, \ldots, \varepsilon_N be independent draws of N(0,R)N(0, R). Then the expected analysis mean is xˉa\bar x^a and the expected sample covariance of the analysis is PaP^a.

Proof. KK depends only on the forecast ensemble, so it is fixed. E[εˉ]=0E[\bar\varepsilon] = 0 gives the mean by Lemma 2. By Lemma 2 the sample covariance is

XaXa⊤N−1=(I−KH)P(I−KH)⊤+KCK⊤+(I−KH)XE⊤K⊤+KEX⊤(I−KH)⊤N−1.\frac{X^aX^{a\top}}{N - 1} = (I - KH)P(I - KH)^\top + KCK^\top + \frac{(I - KH)XE^\top K^\top + KEX^\top(I - KH)^\top}{N - 1}.

The centred sample covariance of NN independent draws is unbiased, so E[C]=RE[C] = R. Each entry of EE has mean zero and XX is fixed, so the last term has mean zero. Hence the expectation is (I−KH)P(I−KH)⊤+KRK⊤(I - KH)P(I - KH)^\top + KRK^\top. Expand it and use K(HPH⊤+R)=PH⊤K(HPH^\top + R) = PH^\top:

(I−KH)P−(I−KH)PH⊤K⊤+KRK⊤=(I−KH)P−PH⊤K⊤+K(HPH⊤+R)K⊤=(I−KH)P.□(I - KH)P - (I - KH)PH^\top K^\top + KRK^\top = (I - KH)P - PH^\top K^\top + K(HPH^\top + R)K^\top = (I - KH)P. \quad\square

Corollary 4 (without perturbations the spread is too small). If εi=0\varepsilon_i = 0 for every member, the analysis covariance is (I−KH)P(I−KH)⊤=Pa−KRK⊤(I - KH)P(I - KH)^\top = P^a - KRK^\top, which is smaller than PaP^a by the positive semidefinite matrix KRK⊤KRK^\top. This is why the observations must be perturbed (Burgers et al. 1998).

Corollary 5 (exact perturbations). If εˉ=0\bar\varepsilon = 0, C=RC = R and XE⊤=0XE^\top = 0, then the analysis has exactly the mean xˉa\bar x^a and the covariance PaP^a. This follows from the formula in the proof of Theorem 3 without the expectation.

With x=(−1,1)x = (-1, 1), H=1H = 1, R=1R = 1, yo=1y^o = 1 and ε=(−1/2,1/2)\varepsilon = (-1/2, 1/2), P=2P = 2 and K=2/3K = 2/3, and the members are 00 and 4/34/3. The mean is 2/32/3, which is the Kalman mean because εˉ=0\bar\varepsilon = 0, but the variance is 8/98/9 instead of Pa=2/3P^a = 2/3, because C=1/2C = 1/2 and XE⊤=1≠0XE^\top = 1 \ne 0. With three members −1,0,1-1, 0, 1 and ε=c(1,−2,1)\varepsilon = c(1, -2, 1), c=R/3c = \sqrt{R/3}, the conditions of Corollary 5 hold and the result is exact.

Large ensembles. For a linear model and Gaussian data, Mandel, Cobb and Beezley (2011) prove that the EnKF members converge in LpL^p to the Kalman filter as N→∞N \to \infty. This is cited, not proved here.

Remark (localization). If HH picks state values at the positions q1,…,qpq_1, \ldots, q_p, and the weights are ρ(j,qk)\rho(j, q_k) in locxy\mathrm{loc}_{xy} and ρ(qk,ql)\rho(q_k, q_l) in locyy\mathrm{loc}_{yy} for a weight matrix ρ\rho on the grid, then line L3 computes (ρ∘P)H⊤(\rho\circ P)H^\top and H(ρ∘P)H⊤H(\rho\circ P)H^\top, where ∘\circ is the entrywise product. So the gain is the Kalman gain of the localized covariance ρ∘P\rho\circ P. For other operators the localized gain is a heuristic.

A nonlinear HH. Line L3 then uses the sample covariances of the state and the predicted observations. Lemma 1 no longer holds, and the update is the usual heuristic of the ensemble filters.

Termination. Line L1 makes NN calls of hh. HPH⊤HPH^\top is positive semidefinite and RR is positive definite, so SS is positive definite and line L7 can solve with it. With localization SS stays positive definite if the weight matrix of the observations is positive semidefinite, by the Schur product theorem. The loop of line L7 runs NN times, and the algorithm returns at line L8. ■\blacksquare

Complexity

Line L3 costs Θ(Np(n+p))\Theta(Np(n + p)), lines L5 to L7 cost Θ(p3+p2N+npN)\Theta(p^3 + p^2N + npN), and line L1 costs NN calls of HH. So one analysis costs Θ(Np(n+p)+p3)\Theta(Np(n + p) + p^3). The extra space is Θ(np+p2)\Theta(np + p^2) for the two covariance blocks and Θ(N(n+p))\Theta(N(n + p)) for the ensembles. The forecast costs NN model runs, which usually dominates. With localization, the observations can be processed in local batches, which removes the p3p^3 term.

Properties

  • Randomized. The analysis depends on the draws of the perturbations. Two runs with different seeds give different members.
  • Derivative free. It needs no tangent linear or adjoint model, unlike the extended Kalman filter.
  • Exact in expectation. For a linear HH the expected analysis mean and covariance are the Kalman values for the sample prior.
  • Low rank. Without localization the analysis stays in xˉ+span(X)\bar x + \mathrm{span}(X), because the gain XY⊤S−1/(N−1)XY^\top S^{-1}/(N - 1) has its columns in the span of the forecast perturbations.
  • Consistent as N→∞N \to \infty. For linear Gaussian models the filter converges to the Kalman filter.
  • Parallel forecast. The members are run through the model independently.

Variants and improvements

  • Square root filters. The EnSRF, the EAKF and the ETKF replace the perturbed observations by a deterministic transform, which removes the sampling noise.
  • Localization. Multiply PH⊤PH^\top and HPH⊤HPH^\top entry by entry by a Gaspari-Cohn weight of the distance, as Houtekamer and Mitchell (2001) did. For an HH that picks grid values this is the Kalman gain of the localized covariance ρ∘Pf\rho\circ P^f. See covariance localization.
  • Inflation. Multiply the forecast perturbations by ρ\sqrt\rho or add noise, see covariance inflation.
  • Centred perturbations. Subtract the mean of the εi\varepsilon_i before line L6, so the mean is the Kalman mean exactly.
  • Smoothing. The ensemble Kalman smoother applies the same update to past states.
  • Inverse problems. Ensemble Kalman inversion applies the update in an artificial time to estimate parameters.

When to use it

Use the EnKF when the model is large and nonlinear, when no adjoint model is available, and when a flow dependent estimate of the forecast error is needed. It is simple to code around an existing model. If the extra noise of the perturbed observations matters, as with small ensembles or weak localization, use a square root filter. For strongly non-Gaussian errors with a small state, a particle filter may be better. For a small linear model, use the Kalman filter itself.

Pitfalls

  • No perturbed observations (line L4). Using the same yoy^o for every member gives the covariance (I−KH)P(I−KH)⊤(I - KH)P(I - KH)^\top, which is too small. The filter then trusts its forecast too much and can stop using the data.
  • Perturbations with the wrong covariance (line L4). The perturbations must be drawn from N(0,R)N(0, R) with the same RR that is in SS. With a correlated RR, use a Cholesky factor to draw them.
  • Small ensembles without localization (line L3). With NN much smaller than nn, the sample covariance has spurious long range correlations. Distant observations then change the state where they should not. In the measurement, no inflation factor made the filter work without localization.
  • Spread collapse. The sample error makes the ensemble too confident over many cycles. Use inflation.
  • Forming PfP^f. For large nn the n×nn \times n matrix does not fit in memory. Line L3 forms only the n×pn \times p and p×pp \times p blocks.
  • A singular SS (line L7). If the localization weights of the observations are not positive semidefinite, SS can lose positive definiteness. Weights from a valid correlation function avoid this, such as the Gaspari-Cohn function of the distance in the plane. The Gaspari-Cohn function of the distance along a ring is not one when its support is more than half the ring: on the 40-point ring of Lorenz-96 its matrix has a negative eigenvalue for c≥11c \ge 11.

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_kalman_filter.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/ensemble-kalman-filter/. The authors are listed in prov/JS3602.jsonl.

"""Ensemble Kalman filter (EnKF) with perturbed observations.

Notation of Ide, Courtier, Ghil and Lorenc (1997). The forecast ensemble has
N members in R^n, the observations y^o in R^p have the error covariance R,
and h is the observation operator (it may be nonlinear).

enkf_analysis forms the gain from the sample covariances of the state and of
the predicted observations and moves each member towards its own perturbed
copy of the observations (Burgers, van Leeuwen and Evensen 1998; Houtekamer
and Mitchell 1998). The optional weights loc_xy (n by p) and loc_yy (p by p)
multiply the two sample covariances entry by entry, which localizes the gain.

enkf_forecast runs every member through the model.

Cost of one analysis: O(N p (n + p) + p^3) and N calls of h.
"""

import random

import scimat


def enkf_forecast(ens, model):
    """Return the forecast ensemble [model(x) for each member x]."""
    return [list(model(x)) for x in ens]


def observation_perturbations(R, N, rng):
    """Return N draws of N(0, R), one list of length p for each member."""
    low = scimat.cholesky(R)
    p = len(R)
    out = []
    for _ in range(N):
        z = [rng.gauss(0.0, 1.0) for _ in range(p)]
        out.append([sum(low[a][b] * z[b] for b in range(a + 1)) for a in range(p)])
    return out


def enkf_analysis(ens, yo, h, R, rng=None, eps=None, loc_xy=None, loc_yy=None):
    """Return the analysis ensemble of the perturbed observation EnKF.

    eps, if given, is the list of the N observation perturbations; otherwise
    they are drawn from N(0, R) with rng (a random.Random).
    """
    N, n, p = len(ens), len(ens[0]), len(yo)
    y = [list(h(x)) for x in ens]  # @line L1
    xbar = [sum(x[j] for x in ens) / N for j in range(n)]  # @line L2
    ybar = [sum(v[k] for v in y) / N for k in range(p)]
    X = [[x[j] - xbar[j] for j in range(n)] for x in ens]
    Y = [[v[k] - ybar[k] for k in range(p)] for v in y]
    PHt = [[sum(X[i][j] * Y[i][k] for i in range(N)) / (N - 1) for k in range(p)] for j in range(n)]  # @line L3
    HPHt = [[sum(Y[i][a] * Y[i][b] for i in range(N)) / (N - 1) for b in range(p)] for a in range(p)]
    if loc_xy is not None:
        PHt = [[PHt[j][k] * loc_xy[j][k] for k in range(p)] for j in range(n)]
    if loc_yy is not None:
        HPHt = [[HPHt[a][b] * loc_yy[a][b] for b in range(p)] for a in range(p)]
    if eps is None:  # @line L4
        eps = observation_perturbations(R, N, rng if rng is not None else random.Random(0))
    S = scimat.add(HPHt, R)  # @line L5
    D = [[yo[k] + eps[i][k] - y[i][k] for i in range(N)] for k in range(p)]  # @line L6
    Z = scimat.solve(S, D)  # p by N
    out = []
    for i in range(N):  # @line L7
        out.append([ens[i][j] + sum(PHt[j][k] * Z[k][i] for k in range(p)) for j in range(n)])
    return out  # @line L8


def ensemble_moments(ens):
    """Return (mean, P): the ensemble mean and the sample covariance with divisor N - 1."""
    N, n = len(ens), len(ens[0])
    mean = [sum(x[j] for x in ens) / N for j in range(n)]
    P = [[sum((x[a] - mean[a]) * (x[b] - mean[b]) for x in ens) / (N - 1) for b in range(n)] for a in range(n)]
    return mean, P
scimat.py 227 lines
# SPDX-License-Identifier: MIT
# Shared helper of the scientific-computing pages of https://algorithm.tamnd.com/. The authors are listed in prov/.

"""Small dense linear algebra and error norms for the scientific-computing pages.

A matrix is a list of rows and a vector is a list. Entries may be int,
float or fractions.Fraction. The routines that do not take a square root
(solve, inv, det and the arithmetic) keep Fraction entries exact.
cholesky, cholesky_solve and norm2 take square roots and return floats.

API (fixed; other pages copy this file byte for byte):
    zeros(m, n=None)        m by n zero matrix (n = m if not given)
    eye(n)                  n by n identity
    add(A, B), sub(A, B)    entrywise sum and difference (vectors or matrices)
    scale(c, A)             c times A (vector or matrix)
    matmul(A, B)            matrix product
    matvec(A, x)            matrix times vector
    transpose(A)            transpose
    dot(x, y)               inner product of two vectors
    norm2(x)                Euclidean norm of a vector, as a float
    outer(x, y)             outer product x y^T
    solve(A, b)             Gaussian elimination with partial pivoting;
                            b is a vector or a matrix of right sides
    inv(A)                  inverse of A
    det(A)                  determinant of A
    cholesky(A)             lower triangular L with A = L L^T (floats)
    cholesky_solve(L, b)    solve L L^T x = b for a vector b
    err_l1(e, dx=1)         sum |e_j| dx
    err_l2(e, dx=1)         sqrt(sum e_j^2 dx), as a float
    err_linf(e, dx=1)       max |e_j| (dx is not used)
    observed_order(errors)  [log2(E_i / E_(i+1)) for successive errors]
"""

import math


def zeros(m, n=None):
    """Return an m by n matrix of zeros (n = m if n is None)."""
    if n is None:
        n = m
    return [[0] * n for _ in range(m)]


def eye(n):
    """Return the n by n identity matrix."""
    out = zeros(n, n)
    for i in range(n):
        out[i][i] = 1
    return out


def _is_matrix(a):
    return len(a) > 0 and isinstance(a[0], list)


def add(a, b):
    """Return a + b for two vectors or two matrices of the same shape."""
    if _is_matrix(a):
        return [[x + y for x, y in zip(ra, rb)] for ra, rb in zip(a, b)]
    return [x + y for x, y in zip(a, b)]


def sub(a, b):
    """Return a - b for two vectors or two matrices of the same shape."""
    if _is_matrix(a):
        return [[x - y for x, y in zip(ra, rb)] for ra, rb in zip(a, b)]
    return [x - y for x, y in zip(a, b)]


def scale(c, a):
    """Return c times a, for a vector or a matrix a."""
    if _is_matrix(a):
        return [[c * x for x in row] for row in a]
    return [c * x for x in a]


def transpose(a):
    """Return the transpose of the matrix a."""
    return [list(col) for col in zip(*a)]


def matmul(a, b):
    """Return the matrix product a b."""
    bt = transpose(b)
    return [[sum(x * y for x, y in zip(row, col)) for col in bt] for row in a]


def matvec(a, x):
    """Return the product of the matrix a and the vector x."""
    return [sum(aij * xj for aij, xj in zip(row, x)) for row in a]


def dot(x, y):
    """Return the inner product of the vectors x and y."""
    return sum(a * b for a, b in zip(x, y))


def norm2(x):
    """Return the Euclidean norm of the vector x, as a float."""
    return math.sqrt(float(dot(x, x)))


def outer(x, y):
    """Return the outer product x y^T as a matrix."""
    return [[a * b for b in y] for a in x]


def _eliminate(a, rhs):
    """Reduce a to upper triangular form with partial pivoting.

    a is a copy of the square matrix, rhs a list of right side rows (one
    row per row of a) that receives the same row operations. Return the
    number of row swaps. Raise ValueError if a pivot is zero.
    """
    n = len(a)
    swaps = 0
    for k in range(n):
        p = max(range(k, n), key=lambda i: abs(a[i][k]))
        if a[p][k] == 0:
            raise ValueError("matrix is singular")
        if p != k:
            a[k], a[p] = a[p], a[k]
            rhs[k], rhs[p] = rhs[p], rhs[k]
            swaps += 1
        for i in range(k + 1, n):
            f = a[i][k] / a[k][k]
            if f == 0:
                continue
            for j in range(k, n):
                a[i][j] -= f * a[k][j]
            for j in range(len(rhs[i])):
                rhs[i][j] -= f * rhs[k][j]
    return swaps


def solve(a, b):
    """Solve a x = b by Gaussian elimination with partial pivoting.

    b is a vector (the result is a vector) or a matrix with one column per
    right side (the result is a matrix). Fraction entries stay exact.
    Raise ValueError if a is singular.
    """
    n = len(a)
    work = [list(row) for row in a]
    vector = not _is_matrix(b)
    rhs = [[v] for v in b] if vector else [list(row) for row in b]
    _eliminate(work, rhs)
    m = len(rhs[0]) if n else 0
    x = [[0] * m for _ in range(n)]
    for i in range(n - 1, -1, -1):
        for j in range(m):
            s = rhs[i][j]
            for k in range(i + 1, n):
                s -= work[i][k] * x[k][j]
            x[i][j] = s / work[i][i]
    if vector:
        return [row[0] for row in x]
    return x


def inv(a):
    """Return the inverse of the square matrix a."""
    return solve(a, eye(len(a)))


def det(a):
    """Return the determinant of the square matrix a (0 if singular)."""
    work = [list(row) for row in a]
    rhs = [[] for _ in a]
    try:
        swaps = _eliminate(work, rhs)
    except ValueError:
        return 0
    d = -1 if swaps % 2 else 1
    for i in range(len(a)):
        d *= work[i][i]
    return d


def cholesky(a):
    """Return the lower triangular L with a = L L^T, in floats.

    Raise ValueError if a is not symmetric positive definite.
    """
    n = len(a)
    low = [[0.0] * n for _ in range(n)]
    for j in range(n):
        s = float(a[j][j]) - sum(low[j][k] ** 2 for k in range(j))
        if s <= 0.0:
            raise ValueError("matrix is not positive definite")
        low[j][j] = math.sqrt(s)
        for i in range(j + 1, n):
            t = float(a[i][j]) - sum(low[i][k] * low[j][k] for k in range(j))
            low[i][j] = t / low[j][j]
    return low


def cholesky_solve(low, b):
    """Solve L L^T x = b, with L from cholesky, for a vector b."""
    n = len(low)
    y = [0.0] * n
    for i in range(n):
        y[i] = (float(b[i]) - sum(low[i][k] * y[k] for k in range(i))) / low[i][i]
    x = [0.0] * n
    for i in range(n - 1, -1, -1):
        x[i] = (y[i] - sum(low[k][i] * x[k] for k in range(i + 1, n))) / low[i][i]
    return x


def err_l1(e, dx=1):
    """Return the discrete L1 norm sum |e_j| dx."""
    return sum(abs(v) for v in e) * dx


def err_l2(e, dx=1):
    """Return the discrete L2 norm sqrt(sum e_j^2 dx), as a float."""
    return math.sqrt(float(sum(v * v for v in e) * dx))


def err_linf(e, dx=1):
    """Return the max norm max |e_j|. dx is accepted for a uniform call and not used."""
    return max(abs(v) for v in e)


def observed_order(errors):
    """Return [log2(E_i / E_(i+1))] for a list of errors on meshes h, h/2, h/4, ..."""
    return [math.log2(float(errors[i]) / float(errors[i + 1])) for i in range(len(errors) - 1)]
test_ensemble_kalman_filter.py 177 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/ensemble-kalman-filter/. The authors are listed in prov/JS3602.jsonl.

import math
import random

import scimat
from ensemble_kalman_filter import enkf_analysis, enkf_forecast, ensemble_moments, observation_perturbations


def kalman(ens, yo, H, R):
    n = len(ens[0])
    xbar, P = ensemble_moments(ens)
    PHt = scimat.matmul(P, scimat.transpose(H))
    S = scimat.add(scimat.matmul(H, PHt), R)
    K = scimat.transpose(scimat.solve(S, scimat.transpose(PHt)))
    xa = scimat.add(xbar, scimat.matvec(K, scimat.sub(yo, scimat.matvec(H, xbar))))
    Pa = scimat.matmul(scimat.sub(scimat.eye(n), scimat.matmul(K, H)), P)
    return K, xa, Pa


def test_page_example():
    out = enkf_analysis([[-1.0], [1.0]], [1.0], lambda x: x, [[1.0]], eps=[[-0.5], [0.5]])
    assert abs(out[0][0] - 0.0) < 1e-12
    assert abs(out[1][0] - 4 / 3) < 1e-12
    mean, P = ensemble_moments(out)
    assert abs(mean[0] - 2 / 3) < 1e-12
    assert abs(P[0][0] - 8 / 9) < 1e-12


def test_exact_when_perturbations_match_R_and_are_orthogonal():
    # eps has sample variance R and no sample covariance with the prior, so the
    # analysis has exactly the Kalman mean and variance.
    R = 0.7
    c = math.sqrt(R / 3)
    ens = [[-1.0], [0.0], [1.0]]
    out = enkf_analysis(ens, [2.0], lambda x: x, [[R]], eps=[[c], [-2 * c], [c]])
    _, xa, Pa = kalman(ens, [2.0], [[1.0]], [[R]])
    mean, P = ensemble_moments(out)
    assert abs(mean[0] - xa[0]) < 1e-12
    assert abs(P[0][0] - Pa[0][0]) < 1e-12


def test_scalar_check_value_in_expectation():
    s = 1 / math.sqrt(2.0)
    rng = random.Random(7)
    trials, m_sum, v_sum = 20000, 0.0, 0.0
    for _ in range(trials):
        out = enkf_analysis([[-s], [s]], [1.0], lambda x: x, [[1.0]], rng=rng)
        mean, P = ensemble_moments(out)
        m_sum += mean[0]
        v_sum += P[0][0]
    assert abs(m_sum / trials - 0.5) < 0.01
    assert abs(v_sum / trials - 0.5) < 0.01


def test_mean_is_kalman_mean_plus_gain_times_mean_perturbation():
    rng = random.Random(8)
    for _ in range(40):
        n, p, N = rng.randint(1, 4), rng.randint(1, 4), rng.randint(2, 8)
        ens = [[rng.gauss(0, 1) for _ in range(n)] for _ in range(N)]
        H = [[rng.uniform(-1, 1) for _ in range(n)] for _ in range(p)]
        L = [[rng.uniform(-1, 1) for _ in range(p)] for _ in range(p)]
        R = scimat.add(scimat.matmul(L, scimat.transpose(L)), scimat.scale(0.3, scimat.eye(p)))
        yo = [rng.gauss(0, 2) for _ in range(p)]
        eps = observation_perturbations(R, N, rng)
        out = enkf_analysis(ens, yo, lambda x: scimat.matvec(H, x), R, eps=eps)
        K, xa, _ = kalman(ens, yo, H, R)
        ebar = [sum(e[k] for e in eps) / N for k in range(p)]
        want = scimat.add(xa, scimat.matvec(K, ebar))
        mean, _ = ensemble_moments(out)
        for a in range(n):
            assert abs(mean[a] - want[a]) < 1e-9 * (1 + abs(want[a]))


def test_covariance_is_kalman_in_expectation():
    rng = random.Random(9)
    ens = [[0.0, 1.0], [1.0, 3.0], [2.0, 2.0], [0.5, -1.0]]
    H = [[1.0, 0.0]]
    R = [[0.5]]
    _, _, Pa = kalman(ens, [1.0], H, R)
    trials = 6000
    acc = [[0.0, 0.0], [0.0, 0.0]]
    for _ in range(trials):
        out = enkf_analysis(ens, [1.0], lambda x: [x[0]], R, rng=rng)
        _, P = ensemble_moments(out)
        for a in range(2):
            for b in range(2):
                acc[a][b] += P[a][b] / trials
    for a in range(2):
        for b in range(2):
            assert abs(acc[a][b] - Pa[a][b]) < 0.04


def test_observation_perturbations_have_covariance_R():
    rng = random.Random(10)
    R = [[2.0, 0.6], [0.6, 1.0]]
    eps = observation_perturbations(R, 40000, rng)
    _, C = ensemble_moments(eps)
    for a in range(2):
        for b in range(2):
            assert abs(C[a][b] - R[a][b]) < 0.05


def test_localization_weights_one_change_nothing_and_zero_freezes():
    rng = random.Random(11)
    ens = [[rng.gauss(0, 1) for _ in range(3)] for _ in range(6)]
    h = lambda x: [x[0], x[1]]
    R = [[0.5, 0.0], [0.0, 0.8]]
    eps = observation_perturbations(R, 6, rng)
    a = enkf_analysis(ens, [1.0, -1.0], h, R, eps=eps)
    ones_xy = [[1.0, 1.0] for _ in range(3)]
    ones_yy = [[1.0, 1.0], [1.0, 1.0]]
    b = enkf_analysis(ens, [1.0, -1.0], h, R, eps=eps, loc_xy=ones_xy, loc_yy=ones_yy)
    assert all(abs(u - v) < 1e-12 for x, z in zip(a, b) for u, v in zip(x, z))
    zero_last = [[1.0, 1.0], [1.0, 1.0], [0.0, 0.0]]
    c = enkf_analysis(ens, [1.0, -1.0], h, R, eps=eps, loc_xy=zero_last, loc_yy=ones_yy)
    for x, z in zip(ens, c):
        assert z[2] == x[2]


def l96(x, F=8.0):
    n = len(x)
    return [(x[(j + 1) % n] - x[j - 2]) * x[j - 1] - x[j] + F for j in range(n)]


def rk4(x, dt):
    k1 = l96(x)
    k2 = l96([a + 0.5 * dt * b for a, b in zip(x, k1)])
    k3 = l96([a + 0.5 * dt * b for a, b in zip(x, k2)])
    k4 = l96([a + dt * b for a, b in zip(x, k3)])
    return [a + dt * (b + 2 * c + 2 * d + e) / 6 for a, b, c, d, e in zip(x, k1, k2, k3, k4)]


def gaspari_cohn(r, c):
    z = abs(r) / c
    if z <= 1:
        return -z**5 / 4 + z**4 / 2 + 5 * z**3 / 8 - 5 * z**2 / 3 + 1
    if z < 2:
        return z**5 / 12 - z**4 / 2 + 5 * z**3 / 8 + 5 * z**2 / 3 - 5 * z + 4 - 2 / (3 * z)
    return 0.0


def test_lorenz96_twin_tracks_the_truth():
    n, N, dt, rho, c = 40, 10, 0.05, 1.1, 4.0
    rng, prng = random.Random(1), random.Random(101)
    x = [8.0] * n
    x[0] += 0.01
    for _ in range(1000):
        x = rk4(x, dt)
    ens, z = [], list(x)
    for _ in range(N):
        for _ in range(50):
            z = rk4(z, dt)
        ens.append(list(z))
    free = [list(e) for e in ens]
    obs = list(range(0, n, 2))
    p = len(obs)
    dist = lambda a, b: min(abs(a - b), n - abs(a - b))
    lxy = [[gaspari_cohn(dist(j, q), c) for q in obs] for j in range(n)]
    lyy = [[gaspari_cohn(dist(q, q2), c) for q2 in obs] for q in obs]
    R = [[1.0 if a == b else 0.0 for b in range(p)] for a in range(p)]
    model = lambda s: rk4(s, dt)
    errs, ferrs = [], []
    for _ in range(150):
        x = rk4(x, dt)
        ens = enkf_forecast(ens, model)
        free = enkf_forecast(free, model)
        m = [sum(e[j] for e in ens) / N for j in range(n)]
        ens = [[m[j] + math.sqrt(rho) * (e[j] - m[j]) for j in range(n)] for e in ens]
        yo = [x[k] + rng.gauss(0, 1) for k in obs]
        ens = enkf_analysis(ens, yo, lambda s: [s[k] for k in obs], R, rng=prng, loc_xy=lxy, loc_yy=lyy)
        for e_list, out in ((ens, errs), (free, ferrs)):
            m = [sum(e[j] for e in e_list) / N for j in range(n)]
            out.append(math.sqrt(sum((m[j] - x[j]) ** 2 for j in range(n)) / n))
    assert sum(errs[50:]) / 100 < 0.7
    assert sum(ferrs[50:]) / 100 > 2.0

History

Evensen proposed the ensemble Kalman filter in 1994 for a quasi-geostrophic ocean model, as a way to forecast the error statistics by Monte Carlo instead of with the extended Kalman filter. In 1998 Burgers, van Leeuwen and Evensen showed that the observations must be perturbed to give the right analysis spread, and in the same year Houtekamer and Mitchell used an EnKF with perturbed observations for atmospheric data assimilation. In 2001 Houtekamer and Mitchell localized the gain with a compactly supported correlation. The square root filters of 2001 to 2003 removed the perturbed observations. In 2011 Mandel, Cobb and Beezley proved that the filter converges to the Kalman filter for linear models as the ensemble grows.

References

  1. G. Evensen, Sequential data assimilation with a nonlinear quasi-geostrophic model using Monte Carlo methods to forecast error statistics, Journal of Geophysical Research: Oceans 99(C5) (1994) 10143-10162, the ensemble forecast of the error statistics and the ensemble form of the Kalman update
  2. G. Burgers, P. J. van Leeuwen and G. Evensen, Analysis scheme in the ensemble Kalman filter, Monthly Weather Review 126(6) (1998) 1719-1724, the need to perturb the observations, and the expected analysis covariance (I - KH)P
  3. P. L. Houtekamer and H. L. Mitchell, Data assimilation using an ensemble Kalman filter technique, Monthly Weather Review 126(3) (1998) 796-811, an EnKF with perturbed observations for atmospheric data assimilation
  4. P. L. Houtekamer and H. L. Mitchell, A sequential ensemble Kalman filter for atmospheric data assimilation, Monthly Weather Review 129(1) (2001) 123-137, the localized gain with a compactly supported correlation function
  5. J. Mandel, L. Cobb and J. D. Beezley, On the convergence of the ensemble Kalman filter, Applications of Mathematics 56(6) (2011) 533-541, convergence of the EnKF to the Kalman filter as N goes to infinity, for linear models
  6. J. S. Whitaker and T. M. Hamill, Ensemble data assimilation without perturbed observations, Monthly Weather Review 130(7) (2002) 1913-1924, the sampling error that the perturbed observations add
  7. 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