Algorithm Search⌘K

Algorithmresearch

Ensemble Kalman inversion

Also called EKI.

Solves inverse problems by repeated ensemble Kalman updates in an artificial time, with no derivatives of the forward model.

Time
Θ(K (N p (d + p) + p^3)) worst
Space
Θ(K N d + N p + p^2) extra
Where
K = the number of steps; N = the ensemble size; d = the number of unknowns; p = the number of data
Properties
derivative free
Origin
Marco A. Iglesias, Kody J. H. Law, Andrew M. Stuart, 2013

Ensemble Kalman inversion (EKI) uses the analysis step of the ensemble Kalman filter to solve an inverse problem y=G(u)+ey = G(u) + e. An ensemble of candidate parameters is moved towards the data by repeated Kalman updates with the same data, in an artificial time. Each step calls the forward model GG once for each member and needs no derivative of GG and no adjoint. The members always stay in the span of the initial ensemble. For a linear GG, the square root form with KK steps of size h=1/Kh = 1/K gives the exact Gaussian posterior. For a nonlinear GG the method is a derivative-free optimizer of the data misfit.

In plain words

You want the parameters of a model that make its output match some data. You cannot differentiate the model, but you can run it. Start with a cloud of guesses and run the model for each. Where the guesses differ, compare how their outputs differ. This tells you which way to move each guess to bring its output closer to the data. Move every guess part of the way, run the model again and repeat. The cloud shrinks around the parameters that fit the data. The cloud only moves inside the space spanned by the first guesses, so these must be chosen with care.

The problem

Input. A forward model G:Rd→RpG: \mathbb R^d \to \mathbb R^p that can be evaluated, data y∈Rpy \in \mathbb R^p with a noise covariance Γ\Gamma (symmetric positive definite), an initial ensemble u1,…,uN∈Rdu_1, \ldots, u_N \in \mathbb R^d drawn from a prior, a step size h>0h > 0 and a number of steps KK. The notation follows Ide, Courtier, Ghil and Lorenc (1997), with the unknown uu in place of the state xx and GG in place of HH. 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. The ensembles after each step. For a linear GG, a Gaussian prior whose mean and covariance the initial ensemble matches exactly, and Kh=1Kh = 1, the square root form ends with the mean and the covariance of the posterior of the Bayesian inverse problem. In the other cases the ensemble mean is an estimate of uu and the spread a rough measure of its uncertainty.

The algorithm

uˉ\bar u and gˉ\bar g are the ensemble means of the uiu_i and the gig_i, and CugC^{ug} and CggC^{gg} the sample covariances with the divisor N−1N - 1.

  1. EKI(u_1..u_N, G, y, Gamma, h, K)
  2. 1for k <- 1 to K do
  3. 2g_i <- G(u_i) for each member
  4. 3compute ubar, gbar, C^ug and C^gg
  5. 4y_i <- y, or y + eta_i with eta_i ~ N(0, Gamma / h) for perturbed data
  6. 5S <- C^gg + Gamma / h; u_i <- u_i + C^ug S^-1 (y_i - g_i) for each member
  7. 6return the ensembles of all steps

Line L5 is the analysis step of the EnKF with the observation error covariance Γ/h\Gamma/h, where GG plays the role of the observation operator. The matrix CugS−1C^{ug}S^{-1} is a Kalman gain built from the ensemble. It replaces the derivative of GG by a linear regression of uu on G(u)G(u) over the members. A small hh makes Γ/h\Gamma/h large, so each step moves the members a short way.

The code has three modes. Mode "perturbed" uses the perturbed targets of line L4. Mode "none" uses yi=yy_i = y for all members. Mode "sqrt" replaces line L5 by the deterministic weights of the ETKF with R=Γ/hR = \Gamma/h.

Example

Take d=p=1d = p = 1, G(u)=uG(u) = u, y=1y = 1, Γ=1\Gamma = 1, two members u=(−1,1)u = (-1, 1) (mean 00, variance 22) and two steps of size h=1/2h = 1/2, so Γ/h=2\Gamma/h = 2.

In mode "none", the first step has Cug=Cgg=2C^{ug} = C^{gg} = 2 and S=4S = 4, so the gain is 1/21/2 and each member moves halfway to 11: the ensemble is (0,1)(0, 1) with the variance 1/21/2. The second step has the gain (1/2)/(1/2+2)=1/5(1/2)/(1/2 + 2) = 1/5, so 00 moves to 1/51/5 and 11 stays. The ensemble (1/5,1)(1/5, 1) has the mean 3/53/5 and the variance 0.320.32.

The posterior for the prior N(0,2)N(0, 2) has the variance (1/2+1)−1=2/3(1/2 + 1)^{-1} = 2/3 and the mean 2/32/3. Mode "sqrt" gives exactly these values after the two steps (Theorem 3 of the proof). Mode "none" gives a smaller mean and a much smaller variance: at each step it removes K(Γ/h)K⊤K(\Gamma/h)K^\top more spread than the Kalman update (Proposition 4).

For the check value of the page group: with two members ∓1/2\mp 1/\sqrt 2, y=1y = 1, Γ=1\Gamma = 1 and one step with h=1h = 1, mode "sqrt" gives the mean 1/21/2 and the variance 1/21/2, and mode "none" gives the mean 1/21/2 and the variance 1/41/4.

A measurement. For the nonlinear model G(u)=(u1+u22/2, e0.3u1−u2)G(u) = (u_1 + u_2^2/2,\ e^{0.3u_1} - u_2) with the data y=G(0.7,−0.4)y = G(0.7, -0.4) without noise, Γ=0.01I\Gamma = 0.01I, h=1h = 1 and initial members drawn from N(0,I)N(0, I) with seed 3, the misfit ∣G(uˉ)−y∣|G(\bar u) - y| of the ensemble mean after kk steps was:

mode NN k=0k = 0 k=1k = 1 k=5k = 5 k=40k = 40
none 5 1.25 0.160 0.0702 0.0275
none 20 1.06 0.513 0.0149 0.0063
perturbed 5 1.25 0.165 0.0830 0.0134
perturbed 20 1.06 0.525 0.0357 0.0070
sqrt 5 1.25 0.160 0.0369 0.0049
sqrt 20 1.06 0.513 0.0076 0.0011

With N=20N = 20 the final mean was within 0.0070.007 of (0.7,−0.4)(0.7, -0.4) in all three modes. The misfit falls quickly at first and then slowly, because the spread, and with it the step, shrinks. The 40 steps took 2 to 3 ms in modes "none" and "perturbed" and 300 ms in mode "sqrt" with N=20N = 20, where the N×NN \times N eigendecomposition dominates. With perturbed data, N=4000N = 4000, G(u)=uG(u) = u, y=1y = 1, Γ=1\Gamma = 1 and four steps of h=1/4h = 1/4, a prior sample with the mean 0.0060.006 and the variance 0.9810.981 ended with the mean 0.4890.489 and the variance 0.4830.483, near the posterior values 0.50.5 and 0.50.5.

Correctness

The proof shows that in every mode and for every GG the members stay in the affine span of the initial ensemble (Lemma 1, the subspace property of Iglesias, Law and Stuart). For a linear GG, one step of mode "sqrt" conditions the sample Gaussian on the data with the noise Γ/h\Gamma/h (Lemma 2), so kk steps give the posterior with the likelihood raised to the power khkh, which is the exact posterior when kh=1kh = 1 (Theorem 3). Mode "none" has the Kalman mean but a covariance smaller than the Kalman one by K(Γ/h)K⊤K(\Gamma/h)K^\top (Proposition 4). For small hh, mode "none" is an Euler step of a gradient flow of the misfit preconditioned by the ensemble covariance, which Schillings and Stuart (2017) analyse. For a nonlinear GG the result is not the posterior, and convergence is measured, not proved.

Proof: Ensemble Kalman inversion stays in the span of the initial ensemble, and its square root form gives the exact posterior for a linear forward modelfull

Setting. The ensemble has N≥2N \ge 2 members u1,…,uN∈Rdu_1, \ldots, u_N \in \mathbb R^d. The data are y∈Rpy \in \mathbb R^p, the noise covariance Γ\Gamma is symmetric positive definite and the step size is h>0h > 0. One step of line L1 computes gi=G(ui)g_i = G(u_i) (line L2), the means uˉ\bar u and gˉ\bar g, the unscaled perturbation matrices UU (d×Nd \times N) and YY (p×Np \times N), and the sample covariances Cug=UY⊤/(N−1)C^{ug} = UY^\top/(N - 1) and Cgg=YY⊤/(N−1)C^{gg} = YY^\top/(N - 1) (line L3). With S=Cgg+Γ/hS = C^{gg} + \Gamma/h, line L5 sets

ui←ui+CugS−1(yi−gi),u_i \leftarrow u_i + C^{ug}S^{-1}(y_i - g_i),

where the target yiy_i of line L4 is yy (mode "none") or y+ηiy + \eta_i with ηi∼N(0,Γ/h)\eta_i \sim N(0, \Gamma/h) (mode "perturbed"). Mode "sqrt" uses the ETKF weights with the observation error covariance Γ/h\Gamma/h:

P~=((N−1)I+Y⊤(Γ/h)−1Y)−1,wˉ=P~Y⊤(Γ/h)−1(y−gˉ),W=N−1 P~1/2,\tilde P = \bigl((N - 1)I + Y^\top(\Gamma/h)^{-1}Y\bigr)^{-1}, \quad \bar w = \tilde PY^\top(\Gamma/h)^{-1}(y - \bar g), \quad W = \sqrt{N - 1}\,\tilde P^{1/2},

and sets ui←uˉ+U(wˉ+Wi)u_i \leftarrow \bar u + U(\bar w + W_i), where WiW_i is column ii of WW. 1\mathbf 1 is the vector of NN ones, so U1=0U\mathbf 1 = 0 and Y1=0Y\mathbf 1 = 0.

Lemma 1 (subspace property). In every mode and for every GG, after any number of steps each member lies in the affine space uˉ0+span⁡U0\bar u^0 + \operatorname{span} U^0 of the initial ensemble. In particular it lies in the linear span of the initial members.

Proof. In modes "none" and "perturbed", CugS−1(yi−gi)=UciC^{ug}S^{-1}(y_i - g_i) = U c_i with ci=Y⊤S−1(yi−gi)/(N−1)c_i = Y^\top S^{-1}(y_i - g_i)/(N - 1), so a step adds to each member a combination of the current perturbations. In mode "sqrt", the new member uˉ+U(wˉ+Wi)\bar u + U(\bar w + W_i) is the current mean plus a combination of the current perturbations. Let V=span⁡U0V = \operatorname{span} U^0. Suppose that all current members lie in uˉ0+V\bar u^0 + V. Then the current mean lies there, the current perturbations are differences of points of uˉ0+V\bar u^0 + V and so lie in VV, and in all modes the new members lie in uˉ0+V\bar u^0 + V again. Induction on the number of steps completes the proof. The point uˉ0=1N∑juj0\bar u^0 = \tfrac1N\sum_j u^0_j and VV are both in the span of the initial members. □\square

So the ensemble can never leave a space of dimension at most N−1N - 1 around the initial mean, whatever GG is.

Lemma 2 (the square root step is Gaussian conditioning on the sample moments). Let G(u)=AuG(u) = Au be linear, and let mm and PP be the sample mean and covariance before a step of mode "sqrt". After the step the sample mean and covariance are

m+PA⊤(APA⊤+Γ/h)−1(y−Am),P−PA⊤(APA⊤+Γ/h)−1AP.m + PA^\top(APA^\top + \Gamma/h)^{-1}(y - Am), \qquad P - PA^\top(APA^\top + \Gamma/h)^{-1}AP.

Proof. This is Lemma 2 of the proof on the page of the ensemble Kalman smoother, with s=x=us = x = u, H=AH = A and R=Γ/hR = \Gamma/h: the weights satisfy W1=1W\mathbf 1 = \mathbf 1, so the new mean is uˉ+Uwˉ\bar u + U\bar w and the new perturbations are UWUW, and the Woodbury identity turns UP~U⊤U\tilde PU^\top into the right side. □\square

The right sides are the moments of uu given yy when u∼N(m,P)u \sim N(m, P) and y=Au+ey = Au + e with e∼N(0,Γ/h)e \sim N(0, \Gamma/h). As a function of uu, the Gaussian density of N(m,P)N(m, P) times exp⁡(−h2∣Γ−1/2(y−Au)∣2)\exp\bigl(-\tfrac h2|\Gamma^{-1/2}(y - Au)|^2\bigr) is proportional to the density with these moments.

Theorem 3 (tempering is exact in mode "sqrt"). Let G(u)=AuG(u) = Au, let the prior be N(m0,P0)N(m_0, P_0), and let the initial ensemble have the sample mean m0m_0 and the sample covariance P0P_0 exactly. After kk steps of mode "sqrt" with the step hh, the ensemble has the mean and the covariance of the Gaussian density proportional to

exp⁡(−12∣P0−1/2(u−m0)∣2−kh2∣Γ−1/2(y−Au)∣2).\exp\Bigl(-\tfrac12|P_0^{-1/2}(u - m_0)|^2 - \tfrac{kh}{2}|\Gamma^{-1/2}(y - Au)|^2\Bigr).

With kh=1kh = 1 these are the moments of the posterior of the Bayesian inverse problem y=Au+ey = Au + e, e∼N(0,Γ)e \sim N(0, \Gamma).

Proof. By induction on kk. For k=0k = 0 this is the assumption. Suppose that after kk steps the sample moments are those of the density πk\pi_k above, which is Gaussian. By Lemma 2 the next step gives the moments of the Gaussian density proportional to πk(u)exp⁡(−h2∣Γ−1/2(y−Au)∣2)\pi_k(u)\exp(-\tfrac h2|\Gamma^{-1/2}(y - Au)|^2). The exponents add, so this is πk+1\pi_{k + 1}. □\square

The data yy is the same at every step. The steps do not use yy more than once in the Bayesian sense: each step uses the fraction hh of the likelihood, and the fractions add up to one when kh=1kh = 1.

Proposition 4 (mode "none" underestimates the spread). Let G(u)=AuG(u) = Au, let mm and PP be the sample moments before a step of mode "none", and let K=PA⊤(APA⊤+Γ/h)−1K = PA^\top(APA^\top + \Gamma/h)^{-1}. The new sample mean is the Kalman mean m+K(y−Am)m + K(y - Am), and the new sample covariance is

(I−KA)P(I−KA)⊤=(I−KA)P−K(Γ/h)K⊤.(I - KA)P(I - KA)^\top = (I - KA)P - K(\Gamma/h)K^\top.

Proof. Here gi=Auig_i = Au_i, so Y=AUY = AU, Cug=PA⊤C^{ug} = PA^\top, S=APA⊤+Γ/hS = APA^\top + \Gamma/h and CugS−1=KC^{ug}S^{-1} = K. Each member becomes ui+K(y−Aui)=(I−KA)ui+Kyu_i + K(y - Au_i) = (I - KA)u_i + Ky. The map is affine and the same for all members, so the mean becomes (I−KA)m+Ky(I - KA)m + Ky and the covariance (I−KA)P(I−KA)⊤(I - KA)P(I - KA)^\top. Expand it: (I−KA)P(I−KA)⊤=(I−KA)P−PA⊤K⊤+KAPA⊤K⊤(I - KA)P(I - KA)^\top = (I - KA)P - PA^\top K^\top + KAPA^\top K^\top. From KS=PA⊤KS = PA^\top follows KAPA⊤K⊤=PA⊤K⊤−K(Γ/h)K⊤KAPA^\top K^\top = PA^\top K^\top - K(\Gamma/h)K^\top, which gives the second form. □\square

(I−KA)P(I - KA)P is the Kalman covariance, so mode "none" removes K(Γ/h)K⊤K(\Gamma/h)K^\top more spread than conditioning would at every step. The perturbations of the targets in mode "perturbed" add this term back in expectation, as on the page of the ensemble Kalman filter.

Remark (small steps). Since S−1=h(hCgg+Γ)−1S^{-1} = h(hC^{gg} + \Gamma)^{-1}, a step of mode "none" is ui←ui+h CugΓ−1(y−G(ui))+O(h2)u_i \leftarrow u_i + h\,C^{ug}\Gamma^{-1}(y - G(u_i)) + O(h^2) for fixed members. For a linear G=AG = A this is an Euler step of u˙i=−C(u)A⊤Γ−1(Aui−y)\dot u_i = -C(u)A^\top\Gamma^{-1}(Au_i - y), a gradient flow of 12∣Γ−1/2(y−Au)∣2\tfrac12|\Gamma^{-1/2}(y - Au)|^2 with the ensemble covariance C(u)C(u) as the preconditioner. Schillings and Stuart (2017) study this limit, and the collapse of the ensemble and the convergence of the misfit for linear GG. Their results are not proved here.

The check value of the page group: with two members ∓1/2\mp 1/\sqrt 2, G=1G = 1, y=1y = 1, Γ=1\Gamma = 1 and one step of size h=1h = 1, mode "sqrt" gives the mean 1/21/2 and the variance 1/21/2 (Theorem 3), and mode "none" gives the mean 1/21/2 and the variance 1−1/2−1/4=1/41 - 1/2 - 1/4 = 1/4 (Proposition 4).

What is not proved. For a nonlinear GG the step is a linear regression of uu on G(u)G(u) over the ensemble, and the result is not the posterior. Mode "perturbed" gives the posterior only as N→∞N \to \infty for a linear GG, and only in distribution; this is not shown here. Convergence of the misfit for a nonlinear GG is measured on the page, not proved.

Termination. The loop of line L1 runs a fixed number of times. S=Cgg+Γ/hS = C^{gg} + \Gamma/h is the sum of a positive semidefinite and a positive definite matrix, so it is positive definite and the solve of line L5 has a unique solution. In mode "sqrt" the matrix (N−1)I+Y⊤(Γ/h)−1Y(N - 1)I + Y^\top(\Gamma/h)^{-1}Y has all eigenvalues at least N−1>0N - 1 > 0, and the Jacobi method has a fixed upper limit on its sweeps. The algorithm returns at line L6. ■\blacksquare

Complexity

In modes "none" and "perturbed", line L3 costs Θ(N(d+p)p)\Theta(N(d + p)p) for CugC^{ug} and CggC^{gg}, line L4 costs Θ(p3+Np2)\Theta(p^3 + Np^2) for the Cholesky factor and the draws, and line L5 costs Θ(p3+p2N)\Theta(p^3 + p^2N) for the solve with NN right sides and Θ(Ndp)\Theta(Ndp) for the update. KK steps cost Θ(K(Np(d+p)+p3))\Theta(K(Np(d + p) + p^3)) plus KNKN runs of GG, which usually dominate. Mode "sqrt" adds Θ(N2(p+d)+N3)\Theta(N^2(p + d) + N^3) for each step. The code keeps all K+1K + 1 ensembles, Θ(KNd)\Theta(KNd) space, plus Θ(Np+p2)\Theta(Np + p^2) for one step. Keeping only the last ensemble needs Θ(Nd)\Theta(Nd).

Properties

  • Derivative free. Only evaluations of GG are needed, and the NN runs of one step are independent and can run in parallel.
  • Subspace property. The solution is a combination of the initial members. With N−1<dN - 1 < d the method searches a space of dimension N−1N - 1 only.
  • Tempering. KK steps of size h=1/Kh = 1/K split the likelihood into KK equal parts. With perturbed data this is the ensemble smoother with multiple data assimilation (ES-MDA) of Emerick and Reynolds (2013) with all factors equal to KK.
  • Collapse. Without perturbations of the data the spread shrinks at every step for a linear GG, so the ensemble collapses towards one point as the steps go on.
  • Invariance. If uu is replaced by TuTu for an invertible matrix TT and GG by G∘T−1G \circ T^{-1}, the members are replaced by TuiTu_i at every step, because the update depends on GG only through the outputs of the members.

Variants and improvements

  • Different step sizes. Steps h1,…,hKh_1, \ldots, h_K with ∑khk=1\sum_k h_k = 1 also give the exact posterior in mode "sqrt" for a linear GG, by the same proof. ES-MDA allows unequal factors 1/hk1/h_k.
  • Continuous time. Letting h→0h \to 0 gives a system of coupled ordinary differential equations for the members (Schillings and Stuart 2017).
  • Regularization. Adding the prior term to the misfit, or stopping the steps when the misfit reaches the noise level, prevents fitting the noise. The second option is the discrepancy principle of Landweber iteration and similar methods.
  • Localization and inflation. As in the filters, covariance inflation keeps the spread from collapsing too early, and localization changes the gain so that the members can leave the span of the initial ensemble.

When to use it

Use EKI when the forward model is a black box that is expensive to run, has no adjoint, and can be run many times in parallel, as with the reservoir models of Emerick and Reynolds. With a derivative and a few hundred unknowns, the Gauss-Newton algorithm or 4D-Var usually converge in fewer runs. For a linear GG of moderate size, solve the Gaussian posterior or the Tikhonov problem directly.

Pitfalls

  • Full weight at every step (line L5). Using Γ\Gamma instead of Γ/h\Gamma/h with KK steps counts the data KK times, and the spread becomes too small.
  • Too few members (line L3). With N−1<dN - 1 < d the answer stays in the span of the initial ensemble. If the true parameter has a part outside this span, the method cannot find it.
  • Fitting the noise (line L1). With noisy data, running too many steps in mode "none" drives the misfit below the noise level. Stop at the noise level, or use Kh=1Kh = 1.
  • Reading the spread as uncertainty. For a nonlinear GG, and for mode "none" in any case, the final spread is not the posterior spread.
  • Strong nonlinearity (line L5). The gain is a linear regression over the whole ensemble. If GG is far from linear over the spread of the ensemble, the step can point the wrong way, and smaller steps help.

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

"""Ensemble Kalman inversion (EKI) for y = G(u) + noise, noise ~ N(0, Gamma).

Each step is an ensemble Kalman update with the noise covariance Gamma / h
(Iglesias, Law and Stuart 2013; Schillings and Stuart 2017). With K steps of
size h = 1/K and perturbed data this is the ensemble smoother with multiple
data assimilation of Emerick and Reynolds (2013) with all factors equal to K.
G is called once for each member and step; no derivative of G is used.

mode = "perturbed": each member sees y + eta_j with eta_j ~ N(0, Gamma / h).
mode = "none":      each member sees y itself (the deterministic EKI).
mode = "sqrt":      the mean moves by the Kalman gain and the perturbations
                    by the symmetric ensemble transform; for a linear G this
                    gives exactly the moments of one tempered Bayes step.

Cost of one step: O(N p (d + p) + p^3) plus N calls of G (O(N^3) more for "sqrt").
"""

import math
import random

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 eki_step(ens, G, y, Gamma, h=1.0, mode="perturbed", rng=None):
    """Return the ensemble after one EKI step of size h."""
    N, d, p = len(ens), len(ens[0]), len(y)
    g = [list(G(u)) for u in ens]  # @line L2
    ubar = [sum(u[a] for u in ens) / N for a in range(d)]  # @line L3
    gbar = [sum(v[k] for v in g) / N for k in range(p)]
    U = [[u[a] - ubar[a] for a in range(d)] for u in ens]
    Gp = [[v[k] - gbar[k] for k in range(p)] for v in g]
    Gh = scimat.scale(1.0 / h, Gamma)
    if mode == "sqrt":
        Y = scimat.transpose(Gp)  # p by N
        C = scimat.transpose(scimat.solve(Gh, Y))
        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, scimat.sub(y, gbar)))
        return [[ubar[a] + sum((wbar[m] + W[m][i]) * U[m][a] for m in range(N)) for a in range(d)] for i in range(N)]
    Cug = [[sum(U[i][a] * Gp[i][k] for i in range(N)) / (N - 1) for k in range(p)] for a in range(d)]
    Cgg = [[sum(Gp[i][k] * Gp[i][l] for i in range(N)) / (N - 1) for l in range(p)] for k in range(p)]
    targets = [list(y) for _ in range(N)]  # @line L4
    if mode == "perturbed":
        rng = rng if rng is not None else random.Random(0)
        low = scimat.cholesky(Gh)
        for t in targets:
            z = [rng.gauss(0.0, 1.0) for _ in range(p)]
            for k in range(p):
                t[k] += sum(low[k][l] * z[l] for l in range(k + 1))
    S = scimat.add(Cgg, Gh)  # @line L5
    D = [[targets[i][k] - g[i][k] for i in range(N)] for k in range(p)]
    Z = scimat.solve(S, D)
    return [[ens[i][a] + sum(Cug[a][k] * Z[k][i] for k in range(p)) for a in range(d)] for i in range(N)]


def eki(ens0, G, y, Gamma, h=1.0, steps=1, mode="perturbed", rng=None):
    """Run steps EKI steps from ens0 and return the list of the ensembles, ens0 first."""
    out = [[list(u) for u in ens0]]
    for _ in range(steps):  # @line L1
        out.append(eki_step(out[-1], G, y, Gamma, h, mode, rng))
    return out  # @line L6


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_inversion.py 142 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/ensemble-kalman-inversion/. The authors are listed in prov/421ZWN.jsonl.

import math
import random

import scimat
from ensemble_kalman_inversion import eki, eki_step, ensemble_moments


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 posterior(m0, P0, A, y, Gamma):
    """Exact mean and covariance of u given y = A u + noise, noise ~ N(0, Gamma), u ~ N(m0, P0)."""
    PAt = scimat.matmul(P0, scimat.transpose(A))
    S = scimat.add(scimat.matmul(A, PAt), Gamma)
    K = scimat.transpose(scimat.solve(S, scimat.transpose(PAt)))
    m = scimat.add(m0, scimat.matvec(K, scimat.sub(y, scimat.matvec(A, m0))))
    return m, scimat.sub(P0, scimat.matmul(K, scimat.transpose(PAt)))


def close(ens, m, P, tol=1e-9):
    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 linear_problem(seed, d=3, p=2):
    rng = random.Random(seed)
    A = [[rng.uniform(-1, 1) for _ in range(d)] for _ in range(p)]
    L = [[rng.uniform(-1, 1) for _ in range(p)] for _ in range(p)]
    Gamma = scimat.add(scimat.matmul(L, scimat.transpose(L)), scimat.scale(0.3, scimat.eye(p)))
    B = [[rng.uniform(-1, 1) for _ in range(d)] for _ in range(d)]
    P0 = scimat.add(scimat.matmul(B, scimat.transpose(B)), scimat.scale(0.2, scimat.eye(d)))
    m0 = [rng.gauss(0, 1) for _ in range(d)]
    y = [rng.gauss(0, 2) for _ in range(p)]
    return rng, A, Gamma, P0, m0, y


def test_scalar_check_value():
    s = 1 / math.sqrt(2.0)
    ident = lambda u: u
    sq = eki_step([[-s], [s]], ident, [1.0], [[1.0]], mode="sqrt")
    m, P = ensemble_moments(sq)
    assert abs(m[0] - 0.5) < 1e-12 and abs(P[0][0] - 0.5) < 1e-12
    no = eki_step([[-s], [s]], ident, [1.0], [[1.0]], mode="none")
    m, P = ensemble_moments(no)
    assert abs(m[0] - 0.5) < 1e-12 and abs(P[0][0] - 0.25) < 1e-12


def test_page_example():
    ident = lambda u: u
    hist = eki([[-1.0], [1.0]], ident, [1.0], [[1.0]], h=0.5, steps=2, mode="none")
    assert abs(hist[1][0][0]) < 1e-12 and abs(hist[1][1][0] - 1.0) < 1e-12
    assert abs(hist[2][0][0] - 0.2) < 1e-12 and abs(hist[2][1][0] - 1.0) < 1e-12
    m, P = ensemble_moments(hist[2])
    assert abs(m[0] - 0.6) < 1e-12 and abs(P[0][0] - 0.32) < 1e-12
    hist = eki([[-1.0], [1.0]], ident, [1.0], [[1.0]], h=0.5, steps=2, mode="sqrt")
    m, P = ensemble_moments(hist[2])
    assert abs(m[0] - 2 / 3) < 1e-12 and abs(P[0][0] - 2 / 3) < 1e-12


def test_subspace_property():
    rng = random.Random(4)
    d, N = 6, 4
    ens0 = [[rng.gauss(0, 1) for _ in range(d)] for _ in range(N)]
    G = lambda u: [math.sin(u[0]) + u[1] * u[2], u[3] ** 2 - u[4], math.exp(0.2 * u[5])]
    for mode in ("perturbed", "none", "sqrt"):
        hist = eki(ens0, G, [0.3, -0.2, 1.1], scimat.scale(0.1, scimat.eye(3)), h=0.25, steps=4, mode=mode, rng=random.Random(5))
        basis = []
        for u in ens0:
            v = list(u)
            for b in basis:
                v = scimat.sub(v, scimat.scale(scimat.dot(v, b), b))
            basis.append(scimat.scale(1 / scimat.norm2(v), v))
        for u in hist[-1]:
            r = list(u)
            for b in basis:
                r = scimat.sub(r, scimat.scale(scimat.dot(r, b), b))
            assert scimat.norm2(r) < 1e-9 * (1 + scimat.norm2(u))


def test_sqrt_tempering_gives_the_exact_posterior():
    for seed in range(3):
        rng, A, Gamma, P0, m0, y = linear_problem(seed)
        ens0 = exact_ensemble(m0, P0, 6, rng)
        G = lambda u: scimat.matvec(A, u)
        m, P = posterior(m0, P0, A, y, Gamma)
        close(eki(ens0, G, y, Gamma, h=1.0, steps=1, mode="sqrt")[-1], m, P)
        close(eki(ens0, G, y, Gamma, h=0.25, steps=4, mode="sqrt")[-1], m, P)


def test_none_mode_covariance_is_the_kalman_one_minus_K_Gamma_K():
    rng, A, Gamma, P0, m0, y = linear_problem(11)
    h = 0.5
    ens = exact_ensemble(m0, P0, 7, rng)
    out = eki_step(ens, lambda u: scimat.matvec(A, u), y, Gamma, h=h, mode="none")
    Gh = scimat.scale(1 / h, Gamma)
    m, Pk = posterior(m0, P0, A, y, Gh)
    PAt = scimat.matmul(P0, scimat.transpose(A))
    K = scimat.transpose(scimat.solve(scimat.add(scimat.matmul(A, PAt), Gh), scimat.transpose(PAt)))
    P = scimat.sub(Pk, scimat.matmul(scimat.matmul(K, Gh), scimat.transpose(K)))
    close(out, m, P)


def test_perturbed_mode_with_many_members_is_near_the_posterior():
    rng = random.Random(12)
    N = 4000
    ens0 = [[rng.gauss(0, 1)] for _ in range(N)]
    hist = eki(ens0, lambda u: u, [1.0], [[1.0]], h=0.25, steps=4, mode="perturbed", rng=rng)
    m, P = ensemble_moments(hist[-1])
    assert abs(m[0] - 0.5) < 0.05 and abs(P[0][0] - 0.5) < 0.05


def test_nonlinear_misfit_decreases_without_derivatives():
    G = lambda u: [u[0] + u[1] ** 2 / 2, math.exp(0.3 * u[0]) - u[1]]
    y = G([0.7, -0.4])
    rng = random.Random(3)
    ens0 = [[rng.gauss(0, 1), rng.gauss(0, 1)] for _ in range(20)]
    hist = eki(ens0, G, y, scimat.scale(0.01, scimat.eye(2)), h=1.0, steps=40, mode="none")
    misfit = [scimat.norm2(scimat.sub(G(ensemble_moments(e)[0]), y)) for e in hist]
    spread = [sum(ensemble_moments(e)[1][a][a] for a in range(2)) for e in hist]
    assert misfit[0] > 1.0 and misfit[-1] < 0.01
    assert all(b < a for a, b in zip(spread, spread[1:]))
    m = ensemble_moments(hist[-1])[0]
    assert abs(m[0] - 0.7) < 0.02 and abs(m[1] + 0.4) < 0.02

History

Iglesias, Law and Stuart proposed in 2013 to use the ensemble Kalman update as a general method for inverse problems, iterated with the same data, and noted that the members stay in the span of the initial ensemble. In the same year Emerick and Reynolds published the ensemble smoother with multiple data assimilation for reservoir models, which assimilates the same data several times with an inflated error covariance. Schillings and Stuart derived the continuous time limit in 2017 and analysed it for linear forward models.

References

  1. M. A. Iglesias, K. J. H. Law and A. M. Stuart, Ensemble Kalman methods for inverse problems, Inverse Problems 29(4) (2013) 045001, the iterative ensemble Kalman method for inverse problems and the property that the members stay in the span of the initial ensemble
  2. C. Schillings and A. M. Stuart, Analysis of the ensemble Kalman filter for inverse problems, SIAM Journal on Numerical Analysis 55(3) (2017) 1264-1290, the continuous time limit, its gradient flow structure and the results for linear forward models
  3. A. A. Emerick and A. C. Reynolds, Ensemble smoother with multiple data assimilation, Computers & Geosciences 55 (2013) 3-15, the same data assimilated several times with the error covariance multiplied by factors whose inverses add up to one
  4. 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 of the data assimilation pages

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