Algorithmadvanced
Weak-constraint 4D-Var
Allows model error terms at each time in the window, penalized by their covariance, so the analysis need not follow the model exactly.
- Time
- Θ(K n^3 + k (K c + m (K s + K n^2 + n p))) worst
- Space
- Θ(K n^2) extra
- Where
- K = the number of model steps in the window; c = the cost of one full model step; k = the number of outer loops; m = the number of conjugate gradient steps per outer loop; n = the state dimension; p = the total number of observations; s = the cost of one tangent linear or adjoint step
- Model
- Real RAM
- Properties
- deterministic
- Evidence
- Proof sketchCode in 1 languages
- Origin
- Yannick Trémolet, 2006
Weak-constraint 4D-Var removes the assumption of 4D-Var that the model is perfect. It adds a model error term to every step of the window, , and minimizes a cost over the initial state and all the model errors together, with a penalty for each step. The analysis can then leave the model trajectory where the observations ask for it, by an amount that the model error covariance controls. For a linear model and Gaussian errors the minimizer is the mean of the Rauch-Tung-Striebel smoother with process noise , so weak-constraint 4D-Var is the variational form of the full Kalman smoother. As all tend to zero it becomes strong-constraint 4D-Var.
In plain words
Ordinary 4D-Var trusts the weather model completely: the answer must be an exact run of the model, and only the start state can change. But every model has errors. Weak-constraint 4D-Var lets the answer move away from the model at each time step by a small push. Each push costs something, and pushes that the model is known to need are cheap, while others are expensive. The method finds the start state and all the pushes that together give the best balance between the background, the model and the measurements. The price is a much larger search, because there is now one unknown state for every time step instead of one in total.
The problem
Input. A background with error covariance , model steps with their tangent linear and adjoint models, model error covariances for , and observations with operators and error covariances at the times of the window . Notation of Ide, Courtier, Ghil and Lorenc (1997).
Output. The control that minimizes
with , and the trajectory of that control. This is the model error forcing form. Trémolet (2006) also describes the state form, with the states as the control, and a form in which a constant bias is the control.
The algorithm
WEAK-4DVAR(x^b, B, {Q_k}, {y_k, H_k, R_k}, M, M', M'^T)- 1
x_0 <- x^b ; eta_k <- 0 for k = 1..K - 2
for outer <- 1 to max_outer do - 3
x_k <- M_k(x_(k-1)) + eta_k for k = 1..K - 4
d_k <- y_k - H_k x_k for k in T - 5
mu_k <- sensitivity to x_k from one adjoint run forced by -H_k^T R_k^-1 d_k g <- (B^-1 (x_0 - x^b) + mu_0, Q_1^-1 eta_1 + mu_1, ..., Q_K^-1 eta_K + mu_K)- 6
A v = D v + G^T H^T R^-1 H G v ▷ one tangent linear run and one adjoint run - 7
dz <- solve A dz = -g by conjugate gradients - 8
(x_0, eta) <- (x_0, eta) + dz - 9
if |dz| <= tol (1 + |z|) then break - 10
return x_0, ..., x_K
Line L5 is the same backward sweep as in 4D-Var, but the gradient now has a part for every step: the sensitivity to the state at time is also the sensitivity to the model error , because adds to directly. In line L6, maps an increment to the trajectory increments , and is the block diagonal matrix of and the . Each outer loop is a Gauss-Newton step, as in incremental 4D-Var, with a control times larger.
Example
One step. Take (), , , and one observation with . The cost is
Both partial derivatives are zero when , so and . The misfit of 2 between background and observation is shared equally between the initial state and the model error, because . As a check, the prior variance of is , so the Kalman filter gives . With strong constraint () the cost is , with the minimizer : the analysis at time 1 is pulled less towards the observation, because the prior variance of is only .
A model with a missing forcing. In a twin test with the Lorenz-63 model, 40 forward Euler steps with , the truth has a forcing of per step on the third component that the model does not have. All three components are observed every 4 steps with error standard deviation 0.2, and . Over six seeds the mean error of the analysis at the end of the window is 0.20 for weak-constraint 4D-Var with and 0.73 for strong constraint, with 6 to 8 and 8 to 9 outer loops (a measurement). The strong-constraint analysis must fit the drift of the truth with the initial state alone, and the error grows towards the end of the window.
Correctness
The proof shows that the backward sweep gives the exact gradient over and every , that the inner matrix is symmetric positive definite, and that each outer loop is a Gauss-Newton step (a theorem). For a linear model one outer loop gives the minimizer, and the prior times the likelihood of the control is proportional to , so the trajectory of the minimizer is at every time, the Rauch-Tung-Striebel smoother mean with model error (a theorem). The tests check this to against a separate Kalman filter and smoother on random problems, the gradient against finite differences on Lorenz-63, the approach to strong constraint as , and the stationarity of the nonlinear result.
Proof: Weak-constraint 4D-Var has the exact adjoint gradient, and for a linear model its minimizer is the Kalman smoother with model errorfull
Setting. The window has the time levels . The model steps are differentiable with Jacobians , and the trajectory of the control is . , all and all are symmetric positive definite, and is the set of times with observations . The cost is
Lemma 1 (gradient). Let for and otherwise, and let , (the values the backward sweep of line L5 stores after the forcing at each time). Then
Proof. is the gradient of the observation term with respect to , with all later states seen as functions of and the later : the term at time gives , and the terms after act on only through , which gives by the chain rule. A change of changes by the same amount and nothing before time , so the observation term has the gradient with respect to . The same holds for with . The background and model error terms add and .
Lemma 2 (the inner problem). Let be the linear map from an increment to the trajectory increments, , and let . Line L6 applies
which is symmetric positive definite, and line L7 gives the unique minimizer of with the model linearized along the current trajectory.
Proof. The forward loop inside apply_a computes , the forcing applies , and the backward sweep with Lemma 1 applied to these forcings computes of the result, so apply_a is . for . With the linearized model the cost is a quadratic in with Hessian and gradient at , where by Lemma 1, so its minimizer is .
So each outer loop is a Gauss-Newton step for over the control , and when .
Theorem 3 (linear model). Let . Then the first outer loop, with an exact inner solve, returns the unique minimizer of . If , and are independent, the trajectory of the minimizer is for every , the mean of the Rauch-Tung-Striebel smoother with model error covariance , and is the Kalman filter mean at time .
Proof. For a linear model the linearization is exact, so the first outer loop minimizes itself, and is strictly convex by Lemma 2. The map from to the trajectory is linear and invertible (), and the prior density of times the likelihood of is proportional to . So the posterior of is Gaussian with mean , and since each is a linear function of , is the trajectory of . The Rauch-Tung-Striebel smoother computes for this linear Gaussian model, and the Kalman filter computes .
Strong-constraint limit. As every , the penalty forces , and the minimizer tends to the strong-constraint 4D-Var minimizer. In the linear case this is continuity of in ; the tests check it with times a positive definite matrix.
Termination. The conjugate gradient method of line L7 stops after at most steps, and the outer loop runs at most max_outer times.
Summary. The backward sweep gives the exact gradient over the initial state and all model errors. Each outer loop is a Gauss-Newton step with a strictly convex inner problem. For a linear model one outer loop gives the minimizer, whose trajectory is the Kalman smoother mean with model error . The tests check this to against a separate Kalman filter and smoother, and the gradient against finite differences.
Complexity
The control has entries instead of . An outer loop costs one full model run, , and each conjugate gradient step one tangent linear and one adjoint run, , plus solves with the factors of and the , with dense covariances, and the observation terms, . With outer loops of inner steps the time is , where is the Cholesky factorization of and every . The memory is for the dense factors of the ; with a single for all steps, or with an operator for , it is the of the trajectory and the control. The inner problem is also harder to precondition than in strong constraint, so is larger in practice.
Properties
- Kalman smoother with model error. For a linear model and Gaussian errors, the minimizer is the smoother mean with process noise (a theorem). Strong-constraint 4D-Var is the case .
- Continuous in . As the minimizer tends to the strong-constraint minimizer (a theorem for the linear case; the tests check it with times a positive definite matrix).
- The window can be longer. Strong-constraint 4D-Var needs a window short enough that the model is nearly perfect over it; the model error terms relax this.
- The answer depends on . A that is too large lets the analysis follow the observation noise, and a that is too small gives strong constraint back. is harder to estimate than (a heuristic that Trémolet 2007 discusses).
- Parallel in time. In the state form the model runs over the subwindows are independent, so they can run in parallel.
Variants and improvements
- State form. Use the states at the start of each subwindow as the control, and penalize the jumps between the model run from one and the next. This is the form that allows parallel subwindows (Trémolet 2006).
- Bias form. Use one constant model error for the whole window, with a small control. It suits systematic model errors.
- Representer method. Solve the linear problem exactly in observation space, with one unknown per observation, using representer functions. This is the representer method of Bennett, the dual of this algorithm.
- Ensemble estimates of . Estimate the model error covariance from differences between model versions or from ensemble statistics, as ensemble Kalman smoothers do with inflation.
When to use it
Use weak-constraint 4D-Var when the model error over the window is not small next to the background error: long windows, models with known systematic errors, and ocean and atmospheric chemistry problems with weakly known forcing. If the model is good over a short window, strong-constraint 4D-Var is cheaper and has fewer parameters to tune. If no model error covariance can be estimated, start with the bias form.
Pitfalls
- A gradient that ignores the model error (line L5). The gradient over is , with the adjoint variable after the forcing at time . Taking it before the forcing at time drops the observation at that time.
- A badly chosen . The answer depends strongly on ; check it with innovation statistics, as in Desroziers diagnostics.
- Poor conditioning (line L7). The inner problem has unknowns and couples them along the window, so the conjugate gradient method needs a preconditioner, such as a control variable transform with and .
- Memory. Storing a dense for every step is not possible for a large model; use one for all steps or an operator form.
- An unobserved error. Model error and initial state error can have the same effect on the observations, and then only and decide how the misfit is split, as in the example.
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
# 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)]
weak_constraint_4d_var.py 182 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/weak-constraint-4d-var/. The authors are listed in prov/2GGXNP.jsonl.
"""Weak-constraint 4D-Var in the model error forcing form.
Notation of Ide, Courtier, Ghil and Lorenc (1997). The window has the time
levels 0..K. The model is not exact: x_k = M_k(x_(k-1)) + eta_k, where the
model error eta_k has the covariance Q_k. The control variable is
z = (x_0, eta_1, ..., eta_K), and the cost is
J(z) = 1/2 (x_0 - x^b)^T B^-1 (x_0 - x^b) + sum_k 1/2 eta_k^T Q_k^-1 eta_k
+ sum_(k in T) 1/2 d_k^T R_k^-1 d_k, d_k = y_k - H_k x_k.
The minimizer is Gauss-Newton: each outer loop linearizes the model along
the current trajectory and solves the quadratic problem for the increment
dz with the conjugate gradient method. Products with the Gauss-Newton
Hessian cost one tangent linear run and one adjoint run. For a linear model
one outer loop gives the exact minimizer, which is the Kalman smoother
estimate with model error covariance Q.
The model is given by three functions:
step(k, x) M_k(x) for x = x_(k-1), without the model error
tangent(k, x, dx) M_k'(x) dx
adjoint(k, x, lam) M_k'(x)^T lam
Q is a list with Q[k] the covariance of eta_k for k = 1..K (Q[0] is not used).
"""
import scimat
def trajectory(x0, eta, step, K):
"""Return [x_0, ..., x_K] with x_k = M_k(x_(k-1)) + eta_k."""
xs = [list(x0)]
for k in range(1, K + 1):
xs.append(scimat.add(step(k, xs[-1]), eta[k]))
return xs
def cost(x0, eta, xb, B, Q, obs, step, K):
"""Return J(x_0, eta)."""
xs = trajectory(x0, eta, step, K)
e = scimat.sub(x0, xb)
J = 0.5 * scimat.dot(e, scimat.solve(B, e))
for k in range(1, K + 1):
J += 0.5 * scimat.dot(eta[k], scimat.solve(Q[k], eta[k]))
for k, (H, y, R) in obs.items():
d = scimat.sub(y, scimat.matvec(H, xs[k]))
J += 0.5 * scimat.dot(d, scimat.solve(R, d))
return J
def _backward(xs, forcing, adjoint, K, n):
"""Return [mu_0, ..., mu_K]: mu_k is the sensitivity to x_k after the forcing at time k."""
mu = [None] * (K + 1)
lam = [0.0] * n
for k in range(K, -1, -1):
if k in forcing:
lam = scimat.add(lam, forcing[k])
mu[k] = lam
if k > 0:
lam = adjoint(k, xs[k - 1], lam)
return mu
def gradient(x0, eta, xb, B, Q, obs, step, adjoint, K):
"""Return (grad over x_0, [None, grad over eta_1, ..., grad over eta_K])."""
n = len(x0)
xs = trajectory(x0, eta, step, K)
forcing = {}
for k, (H, y, R) in obs.items():
d = scimat.sub(y, scimat.matvec(H, xs[k]))
forcing[k] = [-v for v in scimat.matvec(scimat.transpose(H), scimat.solve(R, d))]
mu = _backward(xs, forcing, adjoint, K, n)
g0 = scimat.add(scimat.solve(B, scimat.sub(x0, xb)), mu[0])
geta = [None] + [scimat.add(scimat.solve(Q[k], eta[k]), mu[k]) for k in range(1, K + 1)]
return g0, geta
def conjugate_gradient(apply_a, b, tol=1e-14, max_iter=None):
"""Solve A z = b for symmetric positive definite A given as a function."""
n = len(b)
if max_iter is None:
max_iter = 2 * n
z = [0.0] * n
r = [float(v) for v in b]
q = list(r)
rr = scimat.dot(r, r)
stop = (tol * scimat.norm2(b)) ** 2
for _ in range(max_iter):
if rr <= stop:
break
aq = apply_a(q)
alpha = rr / scimat.dot(q, aq)
z = [zi + alpha * qi for zi, qi in zip(z, q)]
r = [ri - alpha * ai for ri, ai in zip(r, aq)]
rr_new = scimat.dot(r, r)
q = [ri + (rr_new / rr) * qi for ri, qi in zip(r, q)]
rr = rr_new
return z
def _split(v, n, K):
return v[:n], [None] + [v[n * k : n * (k + 1)] for k in range(1, K + 1)]
def _join(v0, w, K):
out = list(v0)
for k in range(1, K + 1):
out.extend(w[k])
return out
def weak_4dvar(xb, B, Q, obs, step, tangent, adjoint, K, max_outer=30, tol=1e-12):
"""Return (trajectory, x_0, eta, number of outer loops) for weak-constraint 4D-Var."""
n = len(xb)
LB = scimat.cholesky(B)
LQ = [None] + [scimat.cholesky(Q[k]) for k in range(1, K + 1)]
ob = {k: (H, scimat.transpose(H), y, scimat.cholesky(R)) for k, (H, y, R) in obs.items()}
x0 = [float(v) for v in xb] # @line L1
eta = [None] + [[0.0] * n for _ in range(K)]
outer = 0
for outer in range(1, max_outer + 1): # @line L2
xs = trajectory(x0, eta, step, K) # @line L3
d = {k: scimat.sub(y, scimat.matvec(H, xs[k])) for k, (H, Ht, y, LR) in ob.items()} # @line L4
forcing = {k: [-v for v in scimat.matvec(Ht, scimat.cholesky_solve(LR, d[k]))] for k, (H, Ht, y, LR) in ob.items()}
mu = _backward(xs, forcing, adjoint, K, n) # @line L5
g = _join(
scimat.add(scimat.cholesky_solve(LB, scimat.sub(x0, xb)), mu[0]),
[None] + [scimat.add(scimat.cholesky_solve(LQ[k], eta[k]), mu[k]) for k in range(1, K + 1)],
K,
)
def apply_a(v): # @line L6
v0, w = _split(v, n, K)
dx = [v0]
for k in range(1, K + 1):
dx.append(scimat.add(tangent(k, xs[k - 1], dx[-1]), w[k]))
f = {k: scimat.matvec(Ht, scimat.cholesky_solve(LR, scimat.matvec(H, dx[k]))) for k, (H, Ht, y, LR) in ob.items()}
m = _backward(xs, f, adjoint, K, n)
out0 = scimat.add(scimat.cholesky_solve(LB, v0), m[0])
outw = [None] + [scimat.add(scimat.cholesky_solve(LQ[k], w[k]), m[k]) for k in range(1, K + 1)]
return _join(out0, outw, K)
dz = conjugate_gradient(apply_a, [-v for v in g]) # @line L7
d0, dw = _split(dz, n, K)
x0 = scimat.add(x0, d0) # @line L8
eta = [None] + [scimat.add(eta[k], dw[k]) for k in range(1, K + 1)]
size = scimat.norm2(x0) + sum(scimat.norm2(eta[k]) for k in range(1, K + 1))
if scimat.norm2(dz) <= tol * (1.0 + size): # @line L9
break
return trajectory(x0, eta, step, K), x0, eta, outer # @line L10
def linear_model(M):
"""Return (step, tangent, adjoint) for the linear model x_k = M x_(k-1)."""
Mt = scimat.transpose(M)
return (
lambda k, x: scimat.matvec(M, x),
lambda k, x, dx: scimat.matvec(M, dx),
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."""
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
test_weak_constraint_4d_var.py 164 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/weak-constraint-4d-var/. The authors are listed in prov/2GGXNP.jsonl.
import random
import scimat
from weak_constraint_4d_var import (
cost,
gradient,
linear_model,
lorenz63,
trajectory,
weak_4dvar,
)
def random_spd(rng, n, shift=0.5):
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] += shift
return S
def kalman_and_rts(xb, B, M, Q, obs, K):
"""Oracle: Kalman filter and Rauch-Tung-Striebel smoother means with model error Q[k]."""
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.add(scimat.matmul(scimat.matmul(M, Pa[-1]), Mt), Q[k])
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 random_problem(rng, n, K, qscale=1.0):
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)
Q = [None] + [scimat.scale(qscale, random_spd(rng, n, 0.2)) for _ in range(K)]
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]])
return M, B, Q, xb, obs
def test_scalar_check_value():
step, tl, adj = linear_model([[1.0]])
xs, x0, eta, _ = weak_4dvar([0.0], [[1.0]], [None], {0: ([[1.0]], [1.0], [[1.0]])}, step, tl, adj, 0)
assert abs(x0[0] - 0.5) < 1e-14
def test_page_example():
# x_1 = x_0 + eta_1, x^b = 0, B = Q = R = 1, y_1 = 3: x_0 = eta_1 = 1 and x_1 = 2.
step, tl, adj = linear_model([[1.0]])
xs, x0, eta, _ = weak_4dvar([0.0], [[1.0]], [None, [[1.0]]], {1: ([[1.0]], [3.0], [[1.0]])}, step, tl, adj, 1)
assert abs(x0[0] - 1.0) < 1e-13 and abs(eta[1][0] - 1.0) < 1e-13 and abs(xs[1][0] - 2.0) < 1e-13
def test_linear_model_equals_kalman_smoother_with_q():
rng = random.Random(61)
for _ in range(40):
n = rng.randint(1, 3)
K = rng.randint(1, 5)
M, B, Q, xb, obs = random_problem(rng, n, K)
step, tl, adj = linear_model(M)
xs, x0, eta, outer = weak_4dvar(xb, B, Q, obs, step, tl, adj, K)
xa, xsm = kalman_and_rts(xb, B, M, Q, obs, K)
for k in range(K + 1):
assert close(xs[k], xsm[k], 1e-8)
assert close(xs[K], xa[K], 1e-8)
assert outer <= 3
def test_small_q_approaches_strong_constraint():
rng = random.Random(62)
n, K = 2, 4
M, B, Q, xb, obs = random_problem(rng, n, K, qscale=1e-9)
step, tl, adj = linear_model(M)
xs, x0, eta, _ = weak_4dvar(xb, B, Q, obs, step, tl, adj, K)
zero = [None] + [[[0.0] * n for _ in range(n)] for _ in range(K)]
_, strong = kalman_and_rts(xb, B, M, zero, obs, K)
for k in range(K + 1):
assert close(xs[k], strong[k], 1e-6)
def test_gradient_matches_finite_differences_lorenz63():
rng = random.Random(63)
step, _, adj = lorenz63()
K = 15
B = [[1.0, 0.2, 0.0], [0.2, 2.0, 0.1], [0.0, 0.1, 1.5]]
Q = [None] + [[[0.1, 0.0, 0.0], [0.0, 0.2, 0.0], [0.0, 0.0, 0.1]] for _ in range(K)]
xb = [1.0, 2.0, 20.0]
H = [[1.0, 0.0, 0.0], [0.0, 0.5, 0.5]]
obs = {k: (H, [rng.uniform(-5, 5), rng.uniform(-5, 5)], [[0.5, 0.0], [0.0, 1.0]]) for k in (0, 5, 10, 15)}
x0 = [v + rng.uniform(-1, 1) for v in xb]
eta = [None] + [[rng.uniform(-0.3, 0.3) for _ in range(3)] for _ in range(K)]
g0, geta = gradient(x0, eta, xb, B, Q, 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(xp, eta, xb, B, Q, obs, step, K) - cost(xm, eta, xb, B, Q, obs, step, K)) / (2 * eps)
assert abs(fd - g0[j]) <= 1e-6 * (1 + abs(fd))
for k in (1, 7, 15):
for j in range(3):
ep = [None] + [list(e) for e in eta[1:]]
em = [None] + [list(e) for e in eta[1:]]
ep[k][j] += eps
em[k][j] -= eps
fd = (cost(x0, ep, xb, B, Q, obs, step, K) - cost(x0, em, xb, B, Q, obs, step, K)) / (2 * eps)
assert abs(fd - geta[k][j]) <= 1e-6 * (1 + abs(fd))
def test_nonlinear_limit_is_stationary_and_weak_beats_strong_with_model_error():
# Twin: the truth has a constant forcing that the model lacks (model error).
step, tl, adj = lorenz63()
K = 40
forcing = [0.0, 0.0, 0.05]
truth0 = trajectory([1.0, 1.0, 1.0], [None] + [[0.0] * 3] * 500, step, 500)[-1]
truth = trajectory(truth0, [None] + [forcing] * K, step, K)
H = [[1.0, 0.0, 0.0], [0.0, 1.0, 0.0], [0.0, 0.0, 1.0]]
R = [[0.04, 0.0, 0.0], [0.0, 0.04, 0.0], [0.0, 0.0, 0.04]]
B = [[1.0, 0.0, 0.0], [0.0, 1.0, 0.0], [0.0, 0.0, 1.0]]
err_weak = err_strong = 0.0
for seed in range(64, 70):
rng = random.Random(seed)
obs = {k: (H, [v + rng.gauss(0, 0.2) for v in truth[k]], R) for k in range(0, K + 1, 4)}
xb = [v + rng.gauss(0, 1.0) for v in truth0]
Qw = [None] + [[[0.01, 0.0, 0.0], [0.0, 0.01, 0.0], [0.0, 0.0, 0.01]] for _ in range(K)]
Qs = [None] + [[[1e-8, 0.0, 0.0], [0.0, 1e-8, 0.0], [0.0, 0.0, 1e-8]] for _ in range(K)]
xw, x0, eta, _ = weak_4dvar(xb, B, Qw, obs, step, tl, adj, K)
g0, geta = gradient(x0, eta, xb, B, Qw, obs, step, adj, K)
assert scimat.norm2(g0) + sum(scimat.norm2(g) for g in geta[1:]) < 1e-7
xstr, _, _, _ = weak_4dvar(xb, B, Qs, obs, step, tl, adj, K)
err_weak += scimat.norm2(scimat.sub(xw[K], truth[K]))
err_strong += scimat.norm2(scimat.sub(xstr[K], truth[K]))
assert err_weak < 0.5 * err_strong
History
Sasaki (1970) distinguished strong and weak constraints in variational analysis, depending on whether the dynamics must hold exactly or only approximately. Bennett developed the weak-constraint problem for ocean models in the 1980s and 1990s and solved it with representers (Bennett 1992 and 2002). Trémolet (2006) compared the forcing, state and bias formulations for the ECMWF 4D-Var system and studied the estimation of model error in 2007.
References
- Y. Sasaki, Some basic formalisms in numerical variational analysis, Monthly Weather Review 98(12) (1970) 875-883, the formalisms with strong and with weak constraint
- Y. Trémolet, Accounting for an imperfect model in 4D-Var, Quarterly Journal of the Royal Meteorological Society 132(621) (2006) 2483-2504, the model error forcing, state and bias formulations of weak-constraint 4D-Var
- Y. Trémolet, Model-error estimation in 4D-Var, Quarterly Journal of the Royal Meteorological Society 133 (2007) 1267-1280, the estimation of model error in the ECMWF system and the specification of Q
- Andrew F. Bennett, Inverse Modeling of the Ocean and Atmosphere, Cambridge University Press, 2002, the weak-constraint least squares problem and its solution by representers
- 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 2GGXNP Edit this page History Report an error Markdown