Algorithm Search⌘K

Algorithmadvanced

Ensemble Kalman smoother

Also called EnKS.

Updates past states as well as the current one with each new observation, using ensemble cross covariances in time.

Time
Θ(T (p^3 + p^2 N + N^3 + N^2 n (L + 1))) worst
Space
Θ(N n (L + 1) + N^2 + p (p + N)) extra
Where
L = the lag; N = the ensemble size; T = the number of time steps; n = the size of the state; p = the number of observations at one time
Properties
deterministic
Origin
Geir Evensen, Peter Jan van Leeuwen, 2000

The ensemble Kalman smoother (EnKS) of Evensen and van Leeuwen (2000) estimates past states as well as the current one. An ensemble Kalman filter uses each observation to correct only the state at the time of the observation. The smoother also corrects the stored ensembles of earlier times, through the sample covariances between the earlier states and the predicted observations. Each analysis of the filter writes the new members as linear combinations of the forecast members. The smoother applies the same combinations to the stored ensembles of the last LL times. This page uses the deterministic weights of the ETKF. For a linear model without model noise the result is the exact smoothing distribution, the one the Rauch-Tung-Striebel smoother computes.

In plain words

A filter answers the question "where is the system now, given the data so far". A smoother answers "where was the system then, given the data that came later as well". The ensemble keeps a set of possible histories, one for each member. When a new observation arrives, the filter decides how much to trust each member now. A member that fits the new data well was probably also right a little earlier, so the smoother gives its past states the same extra weight. It keeps the past states for LL steps, then stops changing them.

The problem

Input. An initial ensemble x1,…,xN∈Rnx_1, \ldots, x_N \in \mathbb R^n at time 00, a model MM, observations ytoy^o_t for t=1,…,Tt = 1, \ldots, T (some times may have none) with an observation operator HH and an error covariance RR, a lag L≥0L \ge 0 and an optional inflation factor ρ\rho. 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. For every time ss, a filtered ensemble that has used the data up to time ss and a smoothed ensemble that has used the data up to time min⁡(s+L,T)\min(s + L, T). For a linear model without noise, a linear HH and an initial ensemble with the exact prior moments, their moments are those of xsx_s given these data.

The algorithm

sˉ\bar s and SS are the mean and the perturbations of a stored ensemble, and WiW_i is column ii of WW.

  1. EnKS(x_1..x_N, M, H, R, y^o_1..y^o_T, L)
  2. 1for t <- 1 to T do
  3. 2x_i <- M(x_i) for each member; inflate; add time t to the window
  4. 3if there are observations at time t then
  5. 4y_i <- H(x_i); Y <- perturbations; d <- y^o_t - ybar
  6. 5P~ <- ((N - 1) I + Y^T R^-1 Y)^-1; wbar <- P~ Y^T R^-1 d; W <- sqrt(N - 1) P~^(1/2)
  7. 6for each time s in the window: s_i <- sbar + S (wbar + W_i)
  8. 7drop the times s < t - L + 1 from the window ▷ their ensembles are final
  9. 8return the filtered and the smoothed ensembles

Lines L4 and L5 are the ETKF analysis at time tt. Line L6 applies its weights to the current ensemble, which gives the filter, and to the stored ensembles of the window, which gives the smoother. The weights depend only on the predicted observations, so the past states need no model run and no observation operator. The filtered ensemble of time tt is saved right after line L6, before later analyses change it.

Example

Take the scalar model x1=2x0x_1 = 2x_0, two members x0=(−1,1)x_0 = (-1, 1) with the sample variance 22, and one observation y1o=4y^o_1 = 4 of x1x_1 with R=8R = 8 and the lag L=1L = 1. The forecast is (−2,2)(-2, 2) with the variance 88, so the Kalman gain is 1/21/2. The filter moves x1x_1 to the mean 22 with the variance 44, and the members to 2∓22 \mp \sqrt 2.

The sample covariance of x0x_0 and x1x_1 is 44, so the gain for x0x_0 is 4/16=1/44/16 = 1/4. The smoothed x0x_0 has the mean 0+14⋅4=10 + \tfrac14\cdot 4 = 1 and the variance 2−4⋅4/16=12 - 4\cdot 4/16 = 1, and the members are 1∓1/21 \mp 1/\sqrt 2. These are exactly half the members of x1x_1: the same weights act on both times, so the model relation x1=2x0x_1 = 2x_0 holds member by member (Corollary 4 of the proof).

For the check value of the page group: with two members ∓1/2\mp 1/\sqrt 2, the model x1=x0x_1 = x_0, y1o=1y^o_1 = 1, R=1R = 1 and L=1L = 1, the smoothed ensemble of time 00 has the mean 1/21/2 and the variance 1/21/2, while the filtered ensemble of time 00 keeps the mean 00 and the variance 11.

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 step with R=IR = I, N=20N = 20 and multiplicative inflation ρ=1.2\rho = 1.2 of the forecast covariance, without localization, the mean RMSE of the smoothed ensemble mean over cycles 501 to 1500 was (about 25 ms for each cycle with L=8L = 8 in pure Python):

lag LL 0 (filter) 1 2 4 8
seed 1 0.481 0.439 0.405 0.363 0.331
seed 2 0.421 0.384 0.354 0.315 0.282

The filter with L=0L = 0 is the ETKF. On the ETKF page the same filter gave 0.4090.409 with seed 1. There the inflation is applied inside the transform, which gives the same members in exact arithmetic, so the gap shows how much one chaotic run depends on rounding. With both seeds the lag of 88 steps lowered the error by about a third.

Correctness

The proof shows that one analysis of the smoother is the ETKF analysis of the state stacked over the window (Lemma 1). For a linear HH it changes the moments of every stored state by the Gaussian conditioning formulas with the ensemble cross covariances (Lemma 2). For a linear model without model noise, a linear HH and an initial ensemble with the exact prior mean and covariance, the smoothed ensembles have exactly the moments of xsx_s given the data up to time s+Ls + L (Theorem 3, by induction over time). With L≥TL \ge T these are the moments of the fixed interval smoother. With model noise, nonlinear models, or inflation, the result is an approximation that is measured, not proved.

Proof: The square root EnKS is the ETKF of the state over the lag window, and is exact for linear models without model noisefull

Setting. The ensemble has N≥2N \ge 2 members. For an ensemble s1,…,sNs_1, \ldots, s_N of any vector, sˉ\bar s is its mean and SS the matrix of its unscaled perturbations (column ii is si−sˉs_i - \bar s). At an observation time tt the forecast members xix_i give the predicted observations yi=H(xi)y_i = H(x_i) with perturbations YY (p×Np \times N) and the innovation d=yto−yˉd = y^o_t - \bar y. The weights of line L5 are those of the ETKF:

P~=((N−1)I+Y⊤R−1Y)−1,wˉ=P~Y⊤R−1d,W=N−1 P~1/2,\tilde P = \bigl((N - 1)I + Y^\top R^{-1} Y\bigr)^{-1}, \qquad \bar w = \tilde P Y^\top R^{-1} d, \qquad W = \sqrt{N - 1}\,\tilde P^{1/2},

and line L6 replaces each stored ensemble by sia=sˉ+S(wˉ+Wi)s^a_i = \bar s + S(\bar w + W_i), where WiW_i is column ii of WW. There is no inflation (ρ=1\rho = 1) in the lemmas.

Lemma 1 (the smoother is an ETKF of the stacked state). Let ziz_i stack the members of all stored ensembles of the window with the current member xix_i, and let Hz(z)=H(x)H_z(z) = H(x). One analysis of lines L4 to L6 gives the same members as the ETKF analysis of the ensemble ziz_i with the operator HzH_z.

Proof. The ETKF of zz computes its weights from the predicted observations Hz(zi)=H(xi)H_z(z_i) = H(x_i) and from RR and ytoy^o_t only, so they are the weights wˉ\bar w and WW of line L5. It then sets zia=zˉ+Z(wˉ+Wi)z^a_i = \bar z + Z(\bar w + W_i). The mean and the perturbations of a stacked ensemble are the stacked means and perturbations, so this formula acts on each block of zz separately, which is line L6. □\square

Lemma 2 (one analysis is Gaussian conditioning on the sample moments). Suppose HH is linear. Let Css=SS⊤/(N−1)C_{ss} = SS^\top/(N - 1), Csx=SX⊤/(N−1)C_{sx} = SX^\top/(N - 1) and P=XX⊤/(N−1)P = XX^\top/(N - 1). Then line L6 gives a stored ensemble the mean and the sample covariance

sˉ+CsxH⊤(HPH⊤+R)−1d,Css−CsxH⊤(HPH⊤+R)−1HCsx⊤,\bar s + C_{sx}H^\top(HPH^\top + R)^{-1} d, \qquad C_{ss} - C_{sx}H^\top(HPH^\top + R)^{-1} H C_{sx}^\top,

and the same formulas with the stacked state give the joint sample covariance of all blocks.

Proof. Here Y=HXY = HX. Multiply out to get ((N−1)I+Y⊤R−1Y) Y⊤=Y⊤R−1(YY⊤+(N−1)R)((N - 1)I + Y^\top R^{-1}Y)\,Y^\top = Y^\top R^{-1}(YY^\top + (N - 1)R), so P~Y⊤R−1=Y⊤(YY⊤+(N−1)R)−1\tilde P Y^\top R^{-1} = Y^\top (YY^\top + (N - 1)R)^{-1}. So Swˉ=SY⊤(YY⊤+(N−1)R)−1d=CsxH⊤(HPH⊤+R)−1dS\bar w = SY^\top(YY^\top + (N - 1)R)^{-1}d = C_{sx}H^\top(HPH^\top + R)^{-1}d. The columns of WW sum to N−1 P~1/21\sqrt{N - 1}\,\tilde P^{1/2}\mathbf 1, and P~−11=(N−1)1\tilde P^{-1}\mathbf 1 = (N - 1)\mathbf 1 because Y1=0Y\mathbf 1 = 0, so W1=1W\mathbf 1 = \mathbf 1. Hence the new perturbations are SW−1NSW11⊤=SWSW - \tfrac1N SW\mathbf 1\mathbf 1^\top = SW (since S1=0S\mathbf 1 = 0), and the new mean is sˉ+Swˉ\bar s + S\bar w. The new sample covariance is SWW⊤S⊤/(N−1)=SP~S⊤SWW^\top S^\top/(N - 1) = S\tilde P S^\top. By the Woodbury identity P~=1N−1(I−Y⊤(YY⊤+(N−1)R)−1Y)\tilde P = \tfrac{1}{N - 1}\bigl(I - Y^\top(YY^\top + (N - 1)R)^{-1}Y\bigr), so SP~S⊤=Css−CsxH⊤(HPH⊤+R)−1HCsx⊤S\tilde PS^\top = C_{ss} - C_{sx}H^\top(HPH^\top + R)^{-1}HC_{sx}^\top. For two blocks ss and uu the same steps give the cross covariance SP~U⊤S\tilde P U^\top. □\square

These are the formulas for the mean and the covariance of a Gaussian vector after conditioning on a linear observation of a part of it. This is the step that Evensen and van Leeuwen (2000) use with the ensemble cross covariances in time.

Theorem 3 (exact for linear models without model noise). Let the model be xt+1=Axtx_{t+1} = Ax_t with no model noise, let HH be linear, yto=Hxt+ety^o_t = Hx_t + e_t with independent et∼N(0,R)e_t \sim N(0, R), and let x0∼N(m0,P0)x_0 \sim N(m_0, P_0). If the initial ensemble has the sample mean m0m_0 and the sample covariance P0P_0 exactly, then for every s≤Ts \le T the smoothed ensemble of time ss has the mean and the covariance of xsx_s given y1o,…,ymin⁡(s+L,T)oy^o_1, \ldots, y^o_{\min(s + L, T)}, and the filtered ensemble of time ss has those of xsx_s given y1o,…,ysoy^o_1, \ldots, y^o_s.

Proof. By induction on tt we show: after time tt, the stacked ensemble of the times in the window and time tt has the sample mean and the joint sample covariance of these states given y1o,…,ytoy^o_1, \ldots, y^o_t, and every time that has left the window has the moments given the data up to the time when it left. For t=0t = 0 this is the assumption. At time t+1t + 1, line L2 sets xi←Axix_i \leftarrow Ax_i for each member. The stacked members are then a fixed linear map of the old ones, and xt+1=Axtx_{t+1} = Ax_t is the same map of the true states, so the sample moments are still the exact moments given y1o,…,ytoy^o_1, \ldots, y^o_t. If there is an observation, yt+1o=Hxt+1+et+1y^o_{t+1} = Hx_{t+1} + e_{t+1} with et+1e_{t+1} independent of the earlier data and of the states, and the conditional distribution given the earlier data is Gaussian. So conditioning on yt+1oy^o_{t+1} changes the moments by the formulas of Lemma 2, which line L6 applies to every block. Line L7 removes the times ss with s+L=t+1s + L = t + 1 or less, so a time ss leaves the window after it has used the data up to time s+Ls + L. The filtered ensemble of time ss is stored right after the analysis at time ss. □\square

With L≥TL \ge T the smoothed moments are those of the fixed interval smoother. For a linear Gaussian model the Rauch-Tung-Striebel smoother computes the same moments (with Q=0Q = 0).

Corollary 4 (the members keep the model relation). In the setting of Theorem 3, and also for any linear model applied member by member, if two times s<us < u are both in the window, then ui=Au−ssiu_i = A^{u - s}s_i holds for every member and stays true after each analysis, because line L6 applies the same weights to both ensembles and Au−s(sˉ+Sc)=uˉ+UcA^{u - s}(\bar s + S c) = \bar u + U c.

The check value of the page group: with two members ∓1/2\mp 1/\sqrt 2, the model x1=x0x_1 = x_0, H=1H = 1, R=1R = 1, y1o=1y^o_1 = 1 and L=1L = 1, the smoothed ensemble of time 00 and the filtered ensemble of time 11 both have the mean 1/21/2 and the variance 1/21/2, while the filtered ensemble of time 00 keeps the mean 00 and the variance 11.

What is not proved. With model noise, the members must be perturbed in the forecast, and then the result is exact only in expectation or as N→∞N \to \infty; this is not shown here. For a nonlinear model or a nonlinear HH the update is a linear regression on the ensemble and is a heuristic. With inflation, the forecast moments of time tt are changed by ρ\rho, but the stored ensembles are not, so their cross covariances with the forecast no longer match the joint moments; inflation is also a heuristic.

Termination. The loop of line L1 runs TT times. The window holds at most L+1L + 1 ensembles. The matrix (N−1)I+Y⊤R−1Y(N - 1)I + Y^\top R^{-1}Y has all eigenvalues at least N−1>0N - 1 > 0, so the weights exist. The Jacobi method has a fixed upper limit on its sweeps, and the solve with RR needs RR positive definite. The algorithm returns at line L8. ■\blacksquare

Complexity

The weights of line L5 cost Θ(p3+p2N)\Theta(p^3 + p^2N) for the solve with RR, Θ(N2p)\Theta(N^2p) for Y⊤R−1YY^\top R^{-1}Y and Θ(N3)\Theta(N^3) for the eigendecomposition. Line L6 costs Θ(N2n)\Theta(N^2n) for each of the at most L+1L + 1 stored times. So TT steps cost Θ(T(p3+p2N+N3+N2n(L+1)))\Theta(T(p^3 + p^2N + N^3 + N^2n(L + 1))) plus NTNT model runs and NTNT calls of HH. The extra space is the window of L+1L + 1 ensembles, Θ(Nn(L+1))\Theta(Nn(L + 1)), plus Θ(N2+p(p+N))\Theta(N^2 + p(p + N)) for the weights. The model runs are the same as for the filter, so the smoother costs little more than the filter when LL is small.

Properties

  • No extra model runs. The past states are updated with the weights of the filter, so the smoother needs no backward model and no adjoint.
  • Filter included. With L=0L = 0 the algorithm is the ETKF. The last time is always the same in the filter and the smoother.
  • Exact for linear models. Without model noise and for a linear HH, the moments are those of the Gaussian smoothing distribution.
  • Model relation kept. For a linear model the smoothed members of two times in the window differ by the model, member by member.
  • Deterministic. With the square root weights the result does not depend on random draws. With perturbed observations, the same smoother applies the matrix X5X_5 of the EnKF.

Variants and improvements

  • Perturbed observations. Evensen (2003) writes the EnKF analysis as Ea=EfX5E^a = E^fX_5 for an N×NN \times N matrix X5X_5, and the smoother multiplies the stored ensembles by the same X5X_5.
  • Fixed interval. Take L≥TL \ge T to keep all times. The memory then grows with TT.
  • Local weights. With the LETKF, each grid point has its own weights, and the smoother applies them to the past values at the same grid point.
  • Ensemble smoother. The ensemble smoother updates the whole trajectory once with all the data, without the sequential filter. Evensen and van Leeuwen (2000) found the sequential EnKS more accurate with a nonlinear model.
  • Iterative smoothers. For strongly nonlinear models the update can be repeated, which is related to ensemble Kalman inversion and to 4D-Var.

When to use it

Use the EnKS when an estimate of past states is needed, for example for a reanalysis or to estimate initial conditions and parameters, and when an ensemble filter already runs. The extra cost is small. Choose the lag from the time over which the errors stay correlated: beyond that, longer lags only add sampling noise. For linear Gaussian models of small size the Rauch-Tung-Striebel smoother gives the exact answer directly.

Pitfalls

  • Too long a lag (line L7). With a nonlinear model and few members the sample cross covariances between distant times are mostly noise. Updating states with them can make the estimate worse. The lag must be tuned.
  • Using the smoothed ensemble for the next forecast (line L2). The forecast must start from the filtered ensemble at the current time, which is also the smoothed one at that time. Older smoothed states are not used again for forecasts.
  • Stale weights (line L6). All stored ensembles must use the weights of the same analysis. Recomputing weights from a past ensemble does not work, because the predicted observations belong to the current time.
  • Inflation of the past (line L2). Inflation changes only the current forecast. Inflating the stored ensembles as well makes their spread grow at every analysis in the window, with no model step to justify it.
  • Localization in time. Covariance localization in space does not remove spurious correlations in time. A shorter lag does this.

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

"""Fixed-lag ensemble Kalman smoother (EnKS) with a square root analysis.

Notation of Ide, Courtier, Ghil and Lorenc (1997). The ensemble has N members
in R^n, the observations at time t have the error covariance R, and h is the
observation operator.

At each observation time the analysis is written as a linear combination of
the forecast members: x^a_i = xbar + X (wbar + W_i), with the weights of the
ensemble transform Kalman filter. The smoother applies the same weights to
the stored ensembles of the last L times (Evensen and van Leeuwen 2000;
Evensen 2003 writes this as E^a = E^f X5). With L = 0 it is the filter.

Cost of one analysis: O(N^2 p + p^3 + N^3) for the weights and O(N^2 n) for
each stored time, so O(N^2 (p + n (L + 1)) + p^3 + N^3) in all.
"""

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."""
    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 transform_weights(ens, yo, h, R):
    """Return (wbar, W): the ETKF weights of the forecast ensemble for the observations yo."""
    N = len(ens)
    hx = [list(h(x)) for x in ens]  # @line L4
    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)]  # p by N
    C = scimat.transpose(scimat.solve(R, Y))  # @line L5
    A = scimat.add(scimat.scale(N - 1, scimat.eye(N)), scimat.matmul(C, Y))
    lam, Q = sym_eig(A)
    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)]
    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, [yo[k] - ybar[k] for k in range(p)]))
    return wbar, W


def apply_weights(ens, wbar, W):
    """Return the members sbar + S (wbar + W_i) of the ensemble ens (any state, any time)."""
    N, n = len(ens), len(ens[0])
    sbar = [sum(s[j] for s in ens) / N for j in range(n)]
    S = [[s[j] - sbar[j] for j in range(n)] for s in ens]
    out = []
    for i in range(N):
        c = [wbar[m] + W[m][i] for m in range(N)]
        out.append([sbar[j] + sum(c[m] * S[m][j] for m in range(N)) for j in range(n)])
    return out


def inflate(ens, rho):
    """Return the ensemble with its perturbations multiplied by sqrt(rho)."""
    N, n = len(ens), len(ens[0])
    m = [sum(x[j] for x in ens) / N for j in range(n)]
    f = math.sqrt(rho)
    return [[m[j] + f * (x[j] - m[j]) for j in range(n)] for x in ens]


def enks(ens0, model, h, R, obs, lag, rho=1.0):
    """Run the fixed-lag EnKS from the ensemble ens0 at time 0.

    obs[t - 1] is the observation vector at time t (t = 1..T) or None.
    rho multiplies the covariance of each forecast before its analysis.
    Return (filt, smooth): lists of the ensembles at the times 0..T. filt[t]
    has used the data up to time t, smooth[t] the data up to time t + lag.
    """
    filt = [[list(x) for x in ens0]]
    smooth = [[list(x) for x in ens0]]
    window = [0] if lag >= 1 else []  # times whose ensembles the next analysis still updates
    for t in range(1, len(obs) + 1):  # @line L1
        ens = [list(model(x)) for x in filt[-1]]  # @line L2
        if rho != 1.0:
            ens = inflate(ens, rho)
        smooth.append(ens)
        window.append(t)
        if obs[t - 1] is not None:  # @line L3
            wbar, W = transform_weights(ens, obs[t - 1], h, R)
            for s in window:  # @line L6
                smooth[s] = apply_weights(smooth[s], wbar, W)
        filt.append(smooth[t])
        while window and window[0] < t - lag + 1:  # @line L7
            window.pop(0)
    return filt, smooth  # @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_smoother.py 149 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/ensemble-kalman-smoother/. The authors are listed in prov/G9PNFT.jsonl.

import math
import random

import scimat
from ensemble_kalman_smoother import apply_weights, enks, ensemble_moments, transform_weights


def exact_ensemble(m0, P0, N, rng):
    """N members whose sample mean is m0 and sample covariance is P0 exactly."""
    n = len(m0)
    rows = []
    for _ in range(n):
        v = [rng.gauss(0, 1) for _ in range(N)]
        for u in [[1.0 / math.sqrt(N)] * N] + rows:
            c = scimat.dot(u, v)
            v = [a - c * b for a, b in zip(v, u)]
        nv = scimat.norm2(v)
        rows.append([a / nv for a in v])
    L = scimat.cholesky(P0)
    Z = [[math.sqrt(N - 1) * a for a in row] for row in rows]
    return [[m0[j] + sum(L[j][k] * Z[k][i] for k in range(n)) for j in range(n)] for i in range(N)]


def batch_posterior(m0, P0, A, H, R, obs, s, last):
    """Exact mean and covariance of x_s given y_1..y_last, for x_t = A^t x_0."""
    n = len(m0)
    powers = [scimat.eye(n)]
    for _ in range(max(s, last)):
        powers.append(scimat.matmul(A, powers[-1]))
    G, y, blocks = [], [], []
    for t in range(1, last + 1):
        if obs[t - 1] is None:
            continue
        G.extend(scimat.matmul(H, powers[t]))
        y.extend(obs[t - 1])
        blocks.append(R)
    m, P = list(m0), [list(r) for r in P0]
    if G:
        q = len(y)
        Rb = [[0.0] * q for _ in range(q)]
        off = 0
        for B in blocks:
            for a in range(len(B)):
                for b in range(len(B)):
                    Rb[off + a][off + b] = B[a][b]
            off += len(B)
        PGt = scimat.matmul(P0, scimat.transpose(G))
        S = scimat.add(scimat.matmul(G, PGt), Rb)
        K = scimat.transpose(scimat.solve(S, scimat.transpose(PGt)))
        m = scimat.add(m0, scimat.matvec(K, scimat.sub(y, scimat.matvec(G, m0))))
        P = scimat.sub(P0, scimat.matmul(K, scimat.transpose(PGt)))
    As = powers[s]
    return scimat.matvec(As, m), scimat.matmul(scimat.matmul(As, P), scimat.transpose(As))


def check(ens, m, P, tol=1e-8):
    em, eP = ensemble_moments(ens)
    for a in range(len(m)):
        assert abs(em[a] - m[a]) < tol * (1 + abs(m[a]))
        for b in range(len(m)):
            assert abs(eP[a][b] - P[a][b]) < tol * (1 + abs(P[a][b]))


def test_scalar_check_value():
    s = 1 / math.sqrt(2.0)
    filt, smooth = enks([[-s], [s]], lambda x: x, lambda x: x, [[1.0]], [[1.0]], lag=1)
    for ens in (smooth[0], filt[1], smooth[1]):
        m, P = ensemble_moments(ens)
        assert abs(m[0] - 0.5) < 1e-12 and abs(P[0][0] - 0.5) < 1e-12
    m, P = ensemble_moments(filt[0])
    assert abs(m[0]) < 1e-12 and abs(P[0][0] - 1.0) < 1e-12


def test_page_example():
    filt, smooth = enks([[-1.0], [1.0]], lambda x: [2 * x[0]], lambda x: x, [[8.0]], [[4.0]], lag=1)
    r = 1 / math.sqrt(2.0)
    assert abs(smooth[1][0][0] - (2 - 2 * r)) < 1e-12 and abs(smooth[1][1][0] - (2 + 2 * r)) < 1e-12
    assert abs(smooth[0][0][0] - (1 - r)) < 1e-12 and abs(smooth[0][1][0] - (1 + r)) < 1e-12
    m, P = ensemble_moments(smooth[0])
    assert abs(m[0] - 1.0) < 1e-12 and abs(P[0][0] - 1.0) < 1e-12


def linear_setup(seed, n=3, p=2, T=6, N=6):
    rng = random.Random(seed)
    A = [[rng.uniform(-0.8, 0.8) + (1.0 if i == j else 0.0) for j in range(n)] for i 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.5, scimat.eye(p)))
    m0 = [rng.gauss(0, 1) for _ in range(n)]
    B = [[rng.uniform(-1, 1) for _ in range(n)] for _ in range(n)]
    P0 = scimat.add(scimat.matmul(B, scimat.transpose(B)), scimat.scale(0.2, scimat.eye(n)))
    obs = [None if t == 2 else [rng.gauss(0, 2) for _ in range(p)] for t in range(T)]
    ens0 = exact_ensemble(m0, P0, N, rng)
    return A, H, R, m0, P0, obs, ens0


def test_fixed_interval_matches_exact_smoother():
    for seed in range(3):
        A, H, R, m0, P0, obs, ens0 = linear_setup(seed)
        T = len(obs)
        filt, smooth = enks(ens0, lambda x: scimat.matvec(A, x), lambda x: scimat.matvec(H, x), R, obs, lag=T)
        for s in range(T + 1):
            m, P = batch_posterior(m0, P0, A, H, R, obs, s, T)
            check(smooth[s], m, P)
            m, P = batch_posterior(m0, P0, A, H, R, obs, s, s)
            check(filt[s], m, P)


def test_fixed_lag_uses_data_up_to_t_plus_lag():
    A, H, R, m0, P0, obs, ens0 = linear_setup(7)
    T = len(obs)
    for lag in (1, 2):
        _, smooth = enks(ens0, lambda x: scimat.matvec(A, x), lambda x: scimat.matvec(H, x), R, obs, lag=lag)
        for s in range(T + 1):
            m, P = batch_posterior(m0, P0, A, H, R, obs, s, min(s + lag, T))
            check(smooth[s], m, P)


def test_lag_zero_is_the_filter_and_last_time_agrees():
    A, H, R, m0, P0, obs, ens0 = linear_setup(8)
    model, h = (lambda x: scimat.matvec(A, x)), (lambda x: scimat.matvec(H, x))
    filt, smooth = enks(ens0, model, h, R, obs, lag=0)
    assert all(a == b for a, b in zip(filt, smooth))
    filt2, smooth2 = enks(ens0, model, h, R, obs, lag=3)
    assert smooth2[-1] == filt2[-1] == filt[-1]


def test_smoothed_members_keep_the_linear_model_relation():
    A, H, R, m0, P0, obs, ens0 = linear_setup(9)
    T = len(obs)
    _, smooth = enks(ens0, lambda x: scimat.matvec(A, x), lambda x: scimat.matvec(H, x), R, obs, lag=T)
    for t in range(T):
        for a, b in zip(smooth[t], smooth[t + 1]):
            ax = scimat.matvec(A, a)
            assert all(abs(u - v) < 1e-9 for u, v in zip(ax, b))


def test_weights_are_shared_and_keep_the_mean_of_a_constant():
    rng = random.Random(10)
    ens = [[rng.gauss(0, 1) for _ in range(3)] for _ in range(5)]
    wbar, W = transform_weights(ens, [0.5], lambda x: [x[0]], [[0.4]])
    assert abs(sum(wbar)) < 1e-12
    for i in range(5):
        assert abs(sum(W[m][i] for m in range(5)) - 1.0) < 1e-12
    const = [[3.0, -1.0] for _ in range(5)]
    assert all(abs(u - v) < 1e-12 for x in apply_weights(const, wbar, W) for u, v in zip(x, [3.0, -1.0]))

History

Evensen and van Leeuwen introduced the ensemble Kalman smoother in 2000 and showed with a nonlinear model that the sequential smoother improves on the ensemble smoother, which uses all the data at once. In 2003 Evensen wrote the EnKF analysis as a combination of the forecast members, which makes the smoother a matter of applying the same matrix at all stored times. Cosme and coauthors gave the linear Gaussian solutions of the fixed interval and fixed lag problems in 2012.

References

  1. G. Evensen and P. J. van Leeuwen, An ensemble Kalman smoother for nonlinear dynamics, Monthly Weather Review 128(6) (2000) 1852-1867, the sequential smoother that updates past states with ensemble cross covariances in time
  2. G. Evensen, The ensemble Kalman filter: theoretical formulation and practical implementation, Ocean Dynamics 53(4) (2003) 343-367, the analysis as a combination of the forecast members, E^a = E^f X5, and its use for the smoother
  3. E. Cosme, J. Verron, P. Brasseur, J. Blum and D. Auroux, Smoothing problems in a Bayesian framework and their linear Gaussian solutions, Monthly Weather Review 140(2) (2012) 683-695, the fixed interval and fixed lag smoothing problems and their linear Gaussian solutions
  4. 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 weights in ensemble space and the symmetric square root used here
  5. 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.

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