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
- Model
- Real RAM
- Properties
- derivative free
- Evidence
- Proof sketchCode in 1 languages
- 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 . 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 once for each member and needs no derivative of and no adjoint. The members always stay in the span of the initial ensemble. For a linear , the square root form with steps of size gives the exact Gaussian posterior. For a nonlinear 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 that can be evaluated, data with a noise covariance (symmetric positive definite), an initial ensemble drawn from a prior, a step size and a number of steps . The notation follows Ide, Courtier, Ghil and Lorenc (1997), with the unknown in place of the state and in place of . In the letters of the Kalman filter page, is its , the model is its , the forecast and are its predicted and , and the analysis and are its filtered and .
Output. The ensembles after each step. For a linear , a Gaussian prior whose mean and covariance the initial ensemble matches exactly, and , 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 and the spread a rough measure of its uncertainty.
The algorithm
and are the ensemble means of the and the , and and the sample covariances with the divisor .
EKI(u_1..u_N, G, y, Gamma, h, K)- 1
for k <- 1 to K do - 2
g_i <- G(u_i) for each member - 3
compute ubar, gbar, C^ug and C^gg - 4
y_i <- y, or y + eta_i with eta_i ~ N(0, Gamma / h) for perturbed data - 5
S <- C^gg + Gamma / h; u_i <- u_i + C^ug S^-1 (y_i - g_i) for each member - 6
return the ensembles of all steps
Line L5 is the analysis step of the EnKF with the observation error covariance , where plays the role of the observation operator. The matrix is a Kalman gain built from the ensemble. It replaces the derivative of by a linear regression of on over the members. A small makes 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 for all members. Mode "sqrt" replaces line L5 by the deterministic weights of the ETKF with .
Example
Take , , , , two members (mean , variance ) and two steps of size , so .
In mode "none", the first step has and , so the gain is and each member moves halfway to : the ensemble is with the variance . The second step has the gain , so moves to and stays. The ensemble has the mean and the variance .
The posterior for the prior has the variance and the mean . 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 more spread than the Kalman update (Proposition 4).
For the check value of the page group: with two members , , and one step with , mode "sqrt" gives the mean and the variance , and mode "none" gives the mean and the variance .
A measurement. For the nonlinear model with the data without noise, , and initial members drawn from with seed 3, the misfit of the ensemble mean after steps was:
| mode | |||||
|---|---|---|---|---|---|
| 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 the final mean was within of 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 , where the eigendecomposition dominates. With perturbed data, , , , and four steps of , a prior sample with the mean and the variance ended with the mean and the variance , near the posterior values and .
Correctness
The proof shows that in every mode and for every the members stay in the affine span of the initial ensemble (Lemma 1, the subspace property of Iglesias, Law and Stuart). For a linear , one step of mode "sqrt" conditions the sample Gaussian on the data with the noise (Lemma 2), so steps give the posterior with the likelihood raised to the power , which is the exact posterior when (Theorem 3). Mode "none" has the Kalman mean but a covariance smaller than the Kalman one by (Proposition 4). For small , 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 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 members . The data are , the noise covariance is symmetric positive definite and the step size is . One step of line L1 computes (line L2), the means and , the unscaled perturbation matrices () and (), and the sample covariances and (line L3). With , line L5 sets
where the target of line L4 is (mode "none") or with (mode "perturbed"). Mode "sqrt" uses the ETKF weights with the observation error covariance :
and sets , where is column of . is the vector of ones, so and .
Lemma 1 (subspace property). In every mode and for every , after any number of steps each member lies in the affine space of the initial ensemble. In particular it lies in the linear span of the initial members.
Proof. In modes "none" and "perturbed", with , so a step adds to each member a combination of the current perturbations. In mode "sqrt", the new member is the current mean plus a combination of the current perturbations. Let . Suppose that all current members lie in . Then the current mean lies there, the current perturbations are differences of points of and so lie in , and in all modes the new members lie in again. Induction on the number of steps completes the proof. The point and are both in the span of the initial members.
So the ensemble can never leave a space of dimension at most around the initial mean, whatever is.
Lemma 2 (the square root step is Gaussian conditioning on the sample moments). Let be linear, and let and be the sample mean and covariance before a step of mode "sqrt". After the step the sample mean and covariance are
Proof. This is Lemma 2 of the proof on the page of the ensemble Kalman smoother, with , and : the weights satisfy , so the new mean is and the new perturbations are , and the Woodbury identity turns into the right side.
The right sides are the moments of given when and with . As a function of , the Gaussian density of times is proportional to the density with these moments.
Theorem 3 (tempering is exact in mode "sqrt"). Let , let the prior be , and let the initial ensemble have the sample mean and the sample covariance exactly. After steps of mode "sqrt" with the step , the ensemble has the mean and the covariance of the Gaussian density proportional to
With these are the moments of the posterior of the Bayesian inverse problem , .
Proof. By induction on . For this is the assumption. Suppose that after steps the sample moments are those of the density above, which is Gaussian. By Lemma 2 the next step gives the moments of the Gaussian density proportional to . The exponents add, so this is .
The data is the same at every step. The steps do not use more than once in the Bayesian sense: each step uses the fraction of the likelihood, and the fractions add up to one when .
Proposition 4 (mode "none" underestimates the spread). Let , let and be the sample moments before a step of mode "none", and let . The new sample mean is the Kalman mean , and the new sample covariance is
Proof. Here , so , , and . Each member becomes . The map is affine and the same for all members, so the mean becomes and the covariance . Expand it: . From follows , which gives the second form.
is the Kalman covariance, so mode "none" removes 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 , a step of mode "none" is for fixed members. For a linear this is an Euler step of , a gradient flow of with the ensemble covariance as the preconditioner. Schillings and Stuart (2017) study this limit, and the collapse of the ensemble and the convergence of the misfit for linear . Their results are not proved here.
The check value of the page group: with two members , , , and one step of size , mode "sqrt" gives the mean and the variance (Theorem 3), and mode "none" gives the mean and the variance (Proposition 4).
What is not proved. For a nonlinear the step is a linear regression of on over the ensemble, and the result is not the posterior. Mode "perturbed" gives the posterior only as for a linear , and only in distribution; this is not shown here. Convergence of the misfit for a nonlinear is measured on the page, not proved.
Termination. The loop of line L1 runs a fixed number of times. 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 has all eigenvalues at least , and the Jacobi method has a fixed upper limit on its sweeps. The algorithm returns at line L6.
Complexity
In modes "none" and "perturbed", line L3 costs for and , line L4 costs for the Cholesky factor and the draws, and line L5 costs for the solve with right sides and for the update. steps cost plus runs of , which usually dominate. Mode "sqrt" adds for each step. The code keeps all ensembles, space, plus for one step. Keeping only the last ensemble needs .
Properties
- Derivative free. Only evaluations of are needed, and the runs of one step are independent and can run in parallel.
- Subspace property. The solution is a combination of the initial members. With the method searches a space of dimension only.
- Tempering. steps of size split the likelihood into 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 .
- Collapse. Without perturbations of the data the spread shrinks at every step for a linear , so the ensemble collapses towards one point as the steps go on.
- Invariance. If is replaced by for an invertible matrix and by , the members are replaced by at every step, because the update depends on only through the outputs of the members.
Variants and improvements
- Different step sizes. Steps with also give the exact posterior in mode "sqrt" for a linear , by the same proof. ES-MDA allows unequal factors .
- Continuous time. Letting 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 of moderate size, solve the Gaussian posterior or the Tikhonov problem directly.
Pitfalls
- Full weight at every step (line L5). Using instead of with steps counts the data times, and the spread becomes too small.
- Too few members (line L3). With 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 .
- Reading the spread as uncertainty. For a nonlinear , 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 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.
# 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
- 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
- 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
- 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
- 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.
| Ladder | Level | What the next level needs |
|---|---|---|
| Human proof | H1 sketch |
|
| Lean | L0 no Lean part |
|
| Code (python) | I0 not checked yet |
|
| Visual | V0 none |
|
| Writing | W2 basic |
|
Tag 421ZWN Edit this page History Report an error Markdown