Algorithmcore
Four-dimensional variational assimilation
Also called 4D-Var, strong-constraint 4D-Var.
Finds the initial state whose model trajectory best fits the background and the observations over a time window, with gradients from the adjoint model.
- Time
- Θ(n^3 + I (K c + n^2 + n p)) worst
- Space
- Θ(K n + n^2) extra
- Where
- I = the number of minimizer iterations; K = the number of model steps in the window; c = the cost of one model step; n = the state dimension; p = the total number of observations
- Model
- Real RAM
- Properties
- deterministic
- Evidence
- Proof sketchCode in 1 languages
- Origin
- François Xavier Le Dimet, Olivier Talagrand, Philippe Courtier, 1986
Four-dimensional variational assimilation (4D-Var) finds the initial state of an assimilation window whose model trajectory best fits a background at the start and all the observations made at their own times during the window. The fit is measured by a cost function with the same two terms as in 3D-Var, the departure from the background weighted by and the departures from the observations weighted by , but the observation term is a sum over the window and the model links the times. The model is a strong constraint: the analysis is an exact model trajectory. The gradient of the cost with respect to all components of comes from one forward run of the model and one backward run of its adjoint, and a quasi-Newton or conjugate gradient method minimizes the cost. For a linear model and Gaussian errors the result is the Rauch-Tung-Striebel smoother estimate, and at the end of the window it is the Kalman filter estimate, without ever forming a covariance matrix of the size of the state.
In plain words
A weather center has a forecast for the start of a six or twelve hour period and many measurements taken at different moments during that period. It wants the start state from which the model, run forward, passes as close as possible to all the measurements at their own times, while it stays near the old forecast at the start. Each start state gets a score: how far it is from the old forecast, plus how far its model run is from each measurement. The method runs the model forward to compute the score, then runs a special backward model that tells, for every start value, which way to change it to lower the score. It takes a step in that direction and repeats until the score stops falling.
The problem
Input. A background for time with error covariance ; model steps for , with their adjoint steps ; and for each time of a set , observations with an operator and an error covariance . The total number of observations is . The notation is that of Ide, Courtier, Ghil and Lorenc (1997). In the letters of the Kalman filter page, is its , is its , and and are its predicted mean and covariance at time .
Output. A minimizer, or for a nonlinear model a stationary point, of
The reference code uses linear operators . A nonlinear replaces by and by the adjoint of its Jacobian. The analysis trajectory is , and its last state is the start of the next forecast.
The algorithm
4DVAR(x^b, B, {y_k, H_k, R_k}, M, M'^T)- 1
x_0 <- x^b - 2
for iter <- 1 to max_iter do - 3
run the model from x_0 and store x_1, ..., x_K - 4
J <- 1/2 |x_0 - x^b|^2_(B^-1) + sum_k 1/2 |d_k|^2_(R_k^-1), d_k = y_k - H_k x_k - 5
lambda <- 0 - 6
for k <- K down to 0 do - 7
if k in T then lambda <- lambda - H_k^T R_k^-1 d_k ▷ observation forcing - 8
if k > 0 then lambda <- M_k'(x_(k-1))^T lambda ▷ one adjoint step - 9
g <- B^-1 (x_0 - x^b) + lambda ▷ = grad J(x_0) - 10
if |g| <= tol then break - 11
x_0 <- x_0 + alpha p, p from BFGS, alpha from a line search on J - 12
return x_0
Lines L3 to L9 are one evaluation of the cost and its gradient. The backward loop is the template of the adjoint model page, with the sign of the observation forcing written for departures . Line L11 is a quasi-Newton step. The reference code uses BFGS, started with as the inverse Hessian, which is the inverse Hessian of the background term, and an Armijo backtracking line search; each trial point of the line search costs one more evaluation of lines L3 to L9. Operational systems use limited memory quasi-Newton or conjugate gradient methods inside the incremental form (see incremental 4D-Var), and they minimize over a control variable with instead of applying .
Example
A scalar window. Take (), , , and one observation with . Then
At the code gives , , . Line L7 at gives , line L8 gives , and line L9 gives . The minimizer is , so .
Check with the Kalman filter: the forecast at time 1 has mean and variance , the gain is , and the filter mean is . The smoother gain is , and the smoothed mean at time 0 is .
Lorenz-63 twin experiments. With forward Euler steps of on the Lorenz-63 system, a window of steps, all three variables observed every 8 steps with error standard deviation , , and a background error drawn from , the reference code converges in 9 to 11 BFGS iterations. Over 8 seeds the mean error of falls from 1.55 for the background to 0.41 for the analysis, and the mean error at the end of the window from 1.60 to 0.31 (a measurement).
Correctness
The proof shows by induction over the backward loop that line L9 returns the exact gradient of , so every BFGS direction is a descent direction. For a linear model, linear and Gaussian errors, is, up to a constant, the negative logarithm of the posterior density of given all the observations of the window, so the minimizer is the posterior mean (a theorem). Run forward, it is the smoother mean at every time of the window, and at the last time the Kalman filter mean with the same at the start. The tests check this to against a separate Kalman filter and smoother, check the gradient against finite differences, and check the adjoint with the dot product test to . For a nonlinear model, 4D-Var finds a stationary point, which need not be the global minimum.
Proof: The adjoint sweep gives the gradient of the 4D-Var cost, and for a linear model the minimizer is the Kalman smoother estimatefull
Setting. The window has the time levels . The model steps are differentiable maps with Jacobians , and the trajectory from is . The set holds the times with observations , linear operators and symmetric positive definite error covariances . is symmetric positive definite. The cost is
Write , so , and write for its Jacobian at (chain rule).
Lemma 1 (gradient). The vector of line L9 is .
Proof. By the chain rule,
Let for and otherwise. Let be the value of after line L7 at time . We claim
where the empty product for is the identity. For , line L5 sets and line L7 gives . If the claim holds for , line L8 multiplies by and line L7 at time subtracts , which gives the claim for . At the claim reads , because . Line L9 adds .
So every iterate of line L11 uses the exact gradient. BFGS with the Armijo line search starts from as the inverse Hessian, keeps the inverse Hessian symmetric positive definite (the update is skipped when ), and so every search direction is a descent direction: for . For a strictly convex quadratic the iterates converge to the unique minimizer. For a nonconvex the method stops, by line L10, only near a stationary point.
Theorem 2 (linear model). Let for a fixed invertible matrix . Then is strictly convex and has the unique minimizer
Let , (no model noise) and with independent . Then , and for every . In particular is the Kalman filter mean at time , and is the Rauch-Tung-Striebel smoother mean at time when that smoother runs with .
Proof. With the cost is a quadratic in with the Hessian , and for . Setting the gradient to zero gives the formula.
By Bayes' theorem the posterior density of is proportional to
so the posterior is Gaussian with mean and covariance . Each is a linear function of , so .
The Kalman filter mean at time is , which is because the window ends at . The Rauch-Tung-Striebel smoother gives for the same linear Gaussian model. Both facts are the standard optimality of these recursions for linear Gaussian models (see the pages on the Kalman filter and the Rauch-Tung-Striebel smoother). With the smoother needs the predicted covariances to be invertible, which holds because is invertible.
The tests check Theorem 2 to against a Kalman filter and smoother written separately with Gaussian elimination, and Lemma 1 against central finite differences for Lorenz-63.
Summary. Lines L3 to L9 compute and its exact gradient with one forward run and one backward adjoint run. The minimizer uses descent directions only. For a linear model the cost is strictly convex, and its minimizer is the posterior mean of the initial state; run forward, it is the smoother mean at every time of the window and the Kalman filter mean at the end.
Complexity
One evaluation of and costs one forward run, model steps, plus one adjoint run, whose steps cost a small multiple of a model step each (the cheap gradient principle of reverse mode differentiation). The observation terms cost with dense . The reference code factors and the once and keeps a dense BFGS matrix, so iterations cost , with a few extra cost evaluations when the line search backtracks. The memory is the stored trajectory, , which checkpointing can reduce. For a weather model with near or more, the dense matrix is replaced by limited memory updates in memory, and the work is dominated by the forward and adjoint runs: the cost of 4D-Var is roughly the number of iterations times two or three model runs over the window (a rule of thumb).
Properties
- Flow-dependent increments. The effective covariance of the analysis at time is propagated by the model through the window, so a single observation spreads along the flow of the day even with a static .
- Same result as the smoother for linear models. With a linear model, linear and no model error, 4D-Var and the Kalman smoother give the same estimates (a theorem), but 4D-Var never forms or stores an covariance matrix.
- Strong constraint. The analysis is an exact model trajectory. Model error is ignored, which limits the useful length of the window. Weak-constraint 4D-Var adds model error terms.
- Observations at their own times. Each observation is compared with the model at the time it was taken, which suits satellite and aircraft data spread through the window.
- No analysis covariance. The method returns the estimate only. The analysis error covariance is the inverse Hessian, which is not computed; the next window starts from the static again.
Variants and improvements
- Incremental 4D-Var. Minimize a sequence of quadratic costs for an increment with the tangent linear model, at a lower resolution, inside outer loops with the full model. This is the form of all operational systems (Courtier, Thépaut and Hollingsworth 1994; see incremental 4D-Var).
- Weak-constraint 4D-Var. Add model error terms with covariance to the cost (see weak-constraint 4D-Var). Its dual, observation space form is the representer method.
- 4DEnVar. Replace the tangent linear and adjoint models by an ensemble of trajectories over the window (see four-dimensional ensemble-variational assimilation).
- Hybrid 4D-Var. Replace by a weighted sum of the static covariance and a localized ensemble covariance (see hybrid ensemble-variational assimilation).
- Long windows and quasi-static minimization. For a chaotic model, lengthen the window step by step and start each minimization from the previous solution, which avoids some of the local minima of a long window.
When to use it
Use 4D-Var when the observations are spread in time, when the model is good enough to be a strong constraint over the window, and when a tangent linear and adjoint model can be written and maintained. It gives a dynamically consistent analysis and uses the model to spread information from the observations, which an analysis at one time cannot do. If an adjoint is not available, use an ensemble method or 4DEnVar. If the model error over the window is comparable to the observation error, use the weak-constraint form.
Pitfalls
- A wrong adjoint (line L8). A gradient that is wrong but close makes the minimizer stall or stop at a wrong point. Run the dot product test for each step and for the whole window, and compare the gradient with finite differences.
- The order of forcing and adjoint step (lines L7 and L8). The observation at time must enter before the adjoint step to time . The other order attaches each observation to the wrong time.
- Departures at the wrong state (line L4). The departures must use the trajectory of the current , not of the background.
- A long window in a chaotic model. The cost becomes very rough as the window grows, with many local minima, and the tangent linear approximation behind the incremental form breaks down. Windows of 6 to 12 hours are usual for global weather models.
- Ignoring model error. With a strong constraint, systematic model errors are pushed into , and the analysis can fit the observations by an unrealistic initial state.
- Badly conditioned minimization (line L11). Without a good preconditioner, such as in the BFGS start or the control variable transform, the number of iterations grows with the condition number of the Hessian.
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/four-dimensional-variational-assimilation/. The authors are listed in prov/XB7N6C.jsonl.
"""Strong-constraint four-dimensional variational assimilation (4D-Var).
Notation of Ide, Courtier, Ghil and Lorenc (1997). The window has the time
levels 0, 1, ..., K. The model step k maps x_(k-1) to x_k = M_k(x_(k-1)),
and the model is a perfect constraint, so the initial state x_0 fixes the
whole trajectory. Observations y_k with a linear operator H_k and an error
covariance R_k can be given at any subset of the time levels. The cost is
J(x_0) = 1/2 (x_0 - x^b)^T B^-1 (x_0 - x^b) + sum_k 1/2 d_k^T R_k^-1 d_k,
d_k = y_k - H_k x_k.
The gradient comes from one forward run and one backward run of the
adjoint model. The minimizer is BFGS with a backtracking line search,
started with B as the inverse Hessian, which is the inverse Hessian of the
background term.
A model is given by two functions:
step(k, x) returns x_k = M_k(x) for x = x_(k-1)
adjoint(k, x, lam) returns M_k'(x)^T lam, the adjoint of step k at x
"""
import scimat
def trajectory(x0, step, K):
"""Return [x_0, x_1, ..., x_K] for the model step from x0."""
xs = [list(x0)]
for k in range(1, K + 1):
xs.append(step(k, xs[-1]))
return xs
def cost_and_gradient(x0, xb, LB, obs, step, adjoint, K):
"""Return (J(x0), grad J(x0)).
LB is the Cholesky factor of B, and obs maps a time level k to
(H_k, y_k, LR_k) with LR_k the Cholesky factor of R_k.
"""
xs = trajectory(x0, step, K) # @line L3
e = scimat.sub(x0, xb)
J = 0.5 * scimat.dot(e, scimat.cholesky_solve(LB, e))
forcing = {}
for k, (H, y, LR) in obs.items():
d = scimat.sub(y, scimat.matvec(H, xs[k]))
rd = scimat.cholesky_solve(LR, d)
J += 0.5 * scimat.dot(d, rd) # @line L4
forcing[k] = scimat.matvec(scimat.transpose(H), rd)
lam = [0.0] * len(x0) # @line L5
for k in range(K, -1, -1): # @line L6
if k in forcing:
lam = scimat.sub(lam, forcing[k]) # @line L7
if k > 0:
lam = adjoint(k, xs[k - 1], lam) # @line L8
g = scimat.add(scimat.cholesky_solve(LB, e), lam) # @line L9
return J, g
def _bfgs_update(Hinv, s, y):
"""Return the BFGS update of the inverse Hessian Hinv for the step s and the gradient change y."""
sy = scimat.dot(s, y)
if sy <= 0.0:
return Hinv
rho = 1.0 / sy
hy = scimat.matvec(Hinv, y)
c = rho * rho * scimat.dot(y, hy) + rho
n = len(s)
return [[Hinv[i][j] - rho * (s[i] * hy[j] + hy[i] * s[j]) + c * s[i] * s[j] for j in range(n)] for i in range(n)]
def var4d(xb, B, obs, step, adjoint, K, max_iter=500, tol=1e-12):
"""Return (x_0^a, number of iterations) for strong-constraint 4D-Var.
obs maps a time level k in 0..K to (H_k, y_k, R_k). The iteration stops
when |grad J| <= tol (1 + |grad J(x^b)|) or after max_iter iterations.
"""
LB = scimat.cholesky(B)
ob = {k: (H, y, scimat.cholesky(R)) for k, (H, y, R) in obs.items()}
x = [float(v) for v in xb] # @line L1
J, g = cost_and_gradient(x, xb, LB, ob, step, adjoint, K)
g0 = scimat.norm2(g)
Hinv = [[float(v) for v in row] for row in B]
it = 0
for it in range(max_iter): # @line L2
if scimat.norm2(g) <= tol * (1.0 + g0): # @line L10
break
p = [-v for v in scimat.matvec(Hinv, g)] # @line L11
gp = scimat.dot(g, p)
if gp >= 0.0:
Hinv = [[float(v) for v in row] for row in B]
p = [-v for v in scimat.matvec(Hinv, g)]
gp = scimat.dot(g, p)
a = 1.0
while True:
xn = [xi + a * pi for xi, pi in zip(x, p)]
Jn, gn = cost_and_gradient(xn, xb, LB, ob, step, adjoint, K)
# Armijo test, with a rounding allowance for the last steps
if Jn <= J + 1e-4 * a * gp + 1e-14 * abs(J) or a < 1e-12:
break
a *= 0.5
Hinv = _bfgs_update(Hinv, scimat.sub(xn, x), scimat.sub(gn, g))
x, J, g = xn, Jn, gn
return x, it # @line L12
def linear_model(M):
"""Return (step, adjoint) for the linear model x_k = M x_(k-1) with a fixed matrix M."""
Mt = scimat.transpose(M)
return (lambda k, x: scimat.matvec(M, x)), (lambda k, x, lam: scimat.matvec(Mt, lam))
def lorenz63(dt=0.01, sigma=10.0, rho=28.0, beta=8.0 / 3.0):
"""Return (step, tangent, adjoint) for forward Euler steps of the Lorenz-63 model.
tangent(k, x, dx) is M_k'(x) dx and adjoint(k, x, lam) is M_k'(x)^T lam.
"""
def f(x):
return [sigma * (x[1] - x[0]), x[0] * (rho - x[2]) - x[1], x[0] * x[1] - beta * x[2]]
def jac(x):
return [[-sigma, sigma, 0.0], [rho - x[2], -1.0, -x[0]], [x[1], x[0], -beta]]
def step(k, x):
return [xi + dt * fi for xi, fi in zip(x, f(x))]
def tangent(k, x, dx):
return [di + dt * v for di, v in zip(dx, scimat.matvec(jac(x), dx))]
def adjoint(k, x, lam):
return [li + dt * v for li, v in zip(lam, scimat.matvec(scimat.transpose(jac(x)), lam))]
return step, tangent, adjoint
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_four_dimensional_variational_assimilation.py 162 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/four-dimensional-variational-assimilation/. The authors are listed in prov/XB7N6C.jsonl.
import random
import scimat
from four_dimensional_variational_assimilation import (
cost_and_gradient,
linear_model,
lorenz63,
trajectory,
var4d,
)
def random_spd(rng, n):
L = [[rng.uniform(-1, 1) for _ in range(n)] for _ in range(n)]
S = scimat.matmul(L, scimat.transpose(L))
for i in range(n):
S[i][i] += 0.5
return S
def kalman_and_rts(xb, B, M, obs, K):
"""Oracle: Kalman filter means and Rauch-Tung-Striebel smoother means, with Q = 0.
Gains by Gaussian elimination. Return (filter means, smoother means).
"""
Mt = scimat.transpose(M)
xf, Pf, xa, Pa = [], [], [], []
x, P = list(xb), B
for k in range(K + 1):
if k > 0:
x = scimat.matvec(M, xa[-1])
P = scimat.matmul(scimat.matmul(M, Pa[-1]), Mt)
xf.append(x)
Pf.append(P)
if k in obs:
H, y, R = obs[k]
S = scimat.add(scimat.matmul(scimat.matmul(H, P), scimat.transpose(H)), R)
G = scimat.transpose(scimat.solve(S, scimat.matmul(H, P)))
x = scimat.add(x, scimat.matvec(G, scimat.sub(y, scimat.matvec(H, x))))
P = scimat.sub(P, scimat.matmul(G, scimat.matmul(H, P)))
xa.append(x)
Pa.append(P)
xs = [None] * (K + 1)
xs[K] = xa[K]
for k in range(K - 1, -1, -1):
C = scimat.transpose(scimat.solve(Pf[k + 1], scimat.matmul(M, Pa[k])))
xs[k] = scimat.add(xa[k], scimat.matvec(C, scimat.sub(xs[k + 1], xf[k + 1])))
return xa, xs
def close(a, b, tol):
return all(abs(u - v) <= tol * (1 + abs(v)) for u, v in zip(a, b))
def test_scalar_check_value():
step, adj = linear_model([[1.0]])
xa, _ = var4d([0.0], [[1.0]], {0: ([[1.0]], [1.0], [[1.0]])}, step, adj, 0)
assert abs(xa[0] - 0.5) < 1e-12
def test_page_example():
# x_1 = 2 x_0, x^b = 0, B = 1, y_1 = 2, R = 1: x_0^a = 0.8 and x_1 = 1.6.
step, adj = linear_model([[2.0]])
obs = {1: ([[1.0]], [2.0], [[1.0]])}
J, g = cost_and_gradient([0.0], [0.0], [[1.0]], {1: ([[1.0]], [2.0], [[1.0]])}, step, adj, 1)
assert abs(J - 2.0) < 1e-15 and abs(g[0] + 4.0) < 1e-15
xa, _ = var4d([0.0], [[1.0]], obs, step, adj, 1)
assert abs(xa[0] - 0.8) < 1e-12
assert abs(trajectory(xa, step, 1)[1][0] - 1.6) < 1e-12
def test_linear_model_equals_kalman_smoother():
rng = random.Random(41)
for _ in range(40):
n = rng.randint(1, 4)
K = rng.randint(1, 6)
M = [[(1.0 if i == j else 0.0) + 0.3 * rng.uniform(-1, 1) for j in range(n)] for i in range(n)]
B = random_spd(rng, n)
xb = [rng.uniform(-2, 2) for _ in range(n)]
obs = {}
for k in range(K + 1):
if rng.random() < 0.6:
p = rng.randint(1, 3)
H = [[rng.uniform(-1, 1) for _ in range(n)] for _ in range(p)]
obs[k] = (H, [rng.uniform(-2, 2) for _ in range(p)], random_spd(rng, p))
if not obs:
obs[K] = ([[1.0] + [0.0] * (n - 1)], [1.0], [[1.0]])
step, adj = linear_model(M)
x0, _ = var4d(xb, B, obs, step, adj, K)
xa, xs = kalman_and_rts(xb, B, M, obs, K)
traj = trajectory(x0, step, K)
assert close(x0, xs[0], 1e-8)
assert close(traj[K], xa[K], 1e-8)
for k in range(K + 1):
assert close(traj[k], xs[k], 1e-8)
def test_gradient_matches_finite_differences_lorenz63():
rng = random.Random(42)
step, _, adj = lorenz63()
K = 30
LB = scimat.cholesky([[1.0, 0.2, 0.0], [0.2, 2.0, 0.1], [0.0, 0.1, 1.5]])
xb = [1.0, 2.0, 20.0]
obs = {}
for k in (0, 10, 20, 30):
H = [[1.0, 0.0, 0.0], [0.0, 0.5, 0.5]]
obs[k] = (H, [rng.uniform(-5, 5), rng.uniform(-5, 5)], scimat.cholesky([[0.5, 0.0], [0.0, 1.0]]))
for _ in range(4):
x0 = [xi + rng.uniform(-1, 1) for xi in xb]
J, g = cost_and_gradient(x0, xb, LB, obs, step, adj, K)
eps = 1e-6
for j in range(3):
xp, xm = list(x0), list(x0)
xp[j] += eps
xm[j] -= eps
fd = (cost_and_gradient(xp, xb, LB, obs, step, adj, K)[0] - cost_and_gradient(xm, xb, LB, obs, step, adj, K)[0]) / (2 * eps)
assert abs(fd - g[j]) <= 1e-6 * (1 + abs(g[j]))
def test_dot_product_test_of_the_adjoint():
rng = random.Random(43)
step, tl, adj = lorenz63()
x = [1.0, 2.0, 20.0]
xs = trajectory(x, step, 40)
for _ in range(10):
dx = [rng.uniform(-1, 1) for _ in range(3)]
lam = [rng.uniform(-1, 1) for _ in range(3)]
# the whole window: M' = M_40' ... M_1'
v = dx
for k in range(1, 41):
v = tl(k, xs[k - 1], v)
w = lam
for k in range(40, 0, -1):
w = adj(k, xs[k - 1], w)
lhs, rhs = scimat.dot(v, lam), scimat.dot(dx, w)
assert abs(lhs - rhs) <= 1e-10 * (abs(lhs) + abs(rhs))
def test_lorenz63_twin_reduces_the_error():
# A measurement over 8 twin experiments: the mean error of x_0 falls by more than half.
step, _, adj = lorenz63()
truth0 = trajectory([1.0, 1.0, 1.0], step, 500)[-1]
K = 40
truth = trajectory(truth0, step, K)
H = [[1.0, 0.0, 0.0], [0.0, 1.0, 0.0], [0.0, 0.0, 1.0]]
R = [[0.25, 0.0, 0.0], [0.0, 0.25, 0.0], [0.0, 0.0, 0.25]]
B = [[1.0, 0.0, 0.0], [0.0, 1.0, 0.0], [0.0, 0.0, 1.0]]
eb = ea = 0.0
for seed in range(44, 52):
rng = random.Random(seed)
obs = {k: (H, [v + rng.gauss(0, 0.5) for v in truth[k]], R) for k in range(0, K + 1, 8)}
xb = [v + rng.gauss(0, 1.0) for v in truth0]
x0, _ = var4d(xb, B, obs, step, adj, K)
ob = {k: (h, y, scimat.cholesky(r)) for k, (h, y, r) in obs.items()}
_, g = cost_and_gradient(x0, xb, scimat.cholesky(B), ob, step, adj, K)
assert scimat.norm2(g) < 1e-8
eb += scimat.norm2(scimat.sub(xb, truth0))
ea += scimat.norm2(scimat.sub(x0, truth0))
assert ea < 0.5 * eb
History
Variational methods with a dynamical constraint go back to Sasaki in the late 1950s and 1970. Le Dimet and Talagrand in 1986 posed assimilation over a time window as an optimal control problem and computed the gradient with the adjoint equations, and Talagrand and Courtier in 1987 applied the adjoint of a discrete vorticity model, with numerical results in the companion paper of Courtier and Talagrand. Lewis and Derber had used an adjoint method for the same kind of problem in 1985. The cost of the full method for a weather model was too high until Courtier, Thépaut and Hollingsworth proposed the incremental form in 1994. ECMWF began operational 4D-Var on 25 November 1997 (Rabier et al. 2000), and Météo-France, the UK Met Office, the Japan Meteorological Agency and Environment Canada followed in the next decade.
References
- F.-X. Le Dimet and O. Talagrand, Variational algorithms for analysis and assimilation of meteorological observations, theoretical aspects, Tellus A 38(2) (1986) 97-110, the variational problem over a time window and the adjoint equations for its gradient
- O. Talagrand and P. Courtier, Variational assimilation of meteorological observations with the adjoint vorticity equation. I, Theory, Quarterly Journal of the Royal Meteorological Society 113(478) (1987) 1311-1328, the adjoint of the discrete model and the gradient of the cost
- P. Courtier and O. Talagrand, Variational assimilation of meteorological observations with the adjoint vorticity equation. II, Numerical results, Quarterly Journal of the Royal Meteorological Society 113(478) (1987) 1329-1347, numerical experiments with a barotropic vorticity model
- F. Rabier, H. Järvinen, E. Klinker, J.-F. Mahfouf and A. Simmons, The ECMWF operational implementation of four-dimensional variational assimilation. I, Experimental results with simplified physics, Quarterly Journal of the Royal Meteorological Society 126(564) (2000) 1143-1170, the operational ECMWF 4D-Var and its comparison with 3D-Var
- P. Courtier, J.-N. Thépaut and A. Hollingsworth, A strategy for operational implementation of 4D-Var, using an incremental approach, Quarterly Journal of the Royal Meteorological Society 120(519) (1994) 1367-1387, the incremental form with outer and inner loops
- Eugenia Kalnay, Atmospheric Modeling, Data Assimilation and Predictability, Cambridge University Press, 2003, Section 5.6 (methods with an evolving forecast error covariance, 4D-Var and the Kalman filter)
- K. Ide, P. Courtier, M. Ghil and A. C. Lorenc, Unified notation for data assimilation, operational, sequential and variational, Journal of the Meteorological Society of Japan 75(1B) (1997) 181-189, the notation used here
Where this leads
About this page
The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.
| 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 XB7N6C Edit this page History Report an error Markdown