Algorithmcore
Three-dimensional variational assimilation
Also called 3D-Var.
Finds the analysis by minimizing the distance to the background weighted by B^-1 plus the distance to the observations weighted by R^-1, at one time.
- Time
- Θ(n^3 + p^3 + k m (n^2 + n p + p^2)) worst
- Space
- Θ(n^2 + n p + p^2) extra
- Where
- k = the number of outer loops; m = the number of conjugate gradient steps per outer loop; n = the state dimension; p = the number of observations
- Model
- Real RAM
- Properties
- deterministic
- Evidence
- Proof sketchCode in 1 languages
- Origin
- Andrew C. Lorenc, David F. Parrish, John C. Derber, 1986
Three-dimensional variational assimilation (3D-Var) computes the analysis as the minimizer of a cost function with two terms: the distance from the background , weighted by the inverse of the background error covariance , and the distance from the observations , weighted by the inverse of the observation error covariance . All observations of a time window are treated as valid at one time, hence "three-dimensional". For a linear observation operator the minimizer is the same analysis as global optimal interpolation and the analysis step of the Kalman filter, but 3D-Var uses all observations at once without local selection, accepts a nonlinear operator such as a radiative transfer model for satellite radiances, and needs only products with , and , never the inverse of a large matrix. If the errors are Gaussian, is the negative logarithm of the posterior density, so is the maximum a posteriori estimate.
In plain words
A weather center has a forecast and a large set of new measurements. It looks for the state of the atmosphere that agrees as well as possible with both. Each disagreement is counted with a weight: a large departure from the forecast costs much where the forecast is known to be good, and a large departure from a measurement costs much where the measurement is known to be good. The total cost is a single number, and the method searches for the state with the smallest total. It does this in steps. In each step it replaces the curved link between the state and the measured quantities by a straight one, solves that easier problem, and moves to its solution. For measurements that depend on the state in a straight way, one step is enough.
The problem
Input. A background with error covariance , observations with error covariance (both symmetric positive definite), and an observation operator with Jacobian . Here is the state dimension and the number of observations. This is the notation of Ide, Courtier, Ghil and Lorenc (1997). In the letters of the Kalman filter page, is its , and and are its predicted values and .
Output. A minimizer, or for a nonlinear a stationary point, of
The gradient is . For a linear the minimizer is with .
The algorithm
The reference code uses the incremental form: an outer loop of Gauss-Newton steps, each of which minimizes the cost with linearized at the current point, and an inner conjugate gradient solve.
3DVAR(x^b, B, y^o, h, H(.), R)- 1
x <- x^b - 2
for outer <- 1 to max_outer do - 3
d <- y^o - h(x) ▷ departures from the current point - 4
H <- H(x) ▷ Jacobian of h at x - 5
A <- B^-1 + H^T R^-1 H ▷ Gauss-Newton Hessian, as a function - 6
g <- B^-1 (x - x^b) - H^T R^-1 d ▷ gradient of J at x - 7
dx <- solve A dx = -g by conjugate gradients - 8
x <- x + dx - 9
if |dx| <= tol (1 + |x|) then break - 10
return x
Line L5 never forms : conjugate gradients only need the product , which is one solve with , one product with , one solve with and one product with . Line L6 is the gradient of (Lemma 1 of the proof). The code applies and through Cholesky factors. Operational codes do not apply at all. They minimize over a control variable with and , which turns the background term into and makes the inner problem much better conditioned.
Example
One scalar observation. With , , , , and , line L6 gives , line L5 gives , so , and the analysis error variance is .
Wind speed. The state is a wind with the background , so the background speed is 5. One instrument measures the speed only, , with and . This is nonlinear.
With the minimum lies on the ray through , at the speed , so . Along that ray is linear, and the first outer loop lands on exactly.
With the background is less certain than , so the analysis changes more. The outer iterates, from the reference code, are:
| outer loop | speed | distance to | |||
|---|---|---|---|---|---|
| 0 | 3.000000 | 4.000000 | 5.000000 | 0.500000000 | 8.4e-1 |
| 1 | 3.153061 | 4.816327 | 5.756631 | 0.124626817 | 2.1e-2 |
| 2 | 3.134954 | 4.824572 | 5.753645 | 0.124441540 | 1.3e-3 |
| 3 | 3.134090 | 4.825439 | 5.753901 | 0.124441010 | 8.0e-5 |
| 4 | 3.134038 | 4.825493 | 5.753918 | 0.124441008 | 4.9e-6 |
| 5 | 3.134035 | 4.825496 | 5.753920 | 0.124441008 | 3.0e-7 |
The distance shrinks by a factor of about 0.06 per outer loop (a measurement). This is linear, not quadratic, convergence: the final speed 5.754 does not match the observation 6, and is curved, so the Gauss-Newton Hessian of line L5 misses a term of the true Hessian. A grid search over the square in the tests confirms that the limit is the global minimum.
Correctness
The proof shows that is symmetric positive definite, so line L7 has a unique solution, and that line L8 moves to the exact minimizer of the cost with linearized at . For a linear this is the cost itself, so the first outer loop returns , the Kalman and optimal interpolation analysis, and is the analysis error covariance (a theorem). For a nonlinear each increment is a descent direction, and the loop stops with a zero increment only at a stationary point of . It need not be the global minimum, and convergence from a poor background is not guaranteed.
Proof: 3D-Var gives the Kalman analysis for a linear operator, and its outer loop stops only at stationary pointsfull
Setting. () and () are symmetric positive definite, , , and is differentiable with the Jacobian . The cost is
In one outer loop at the point , line L3 gives , line L4 gives , line L5 defines , and line L6 gives .
Lemma 1 (gradient). , the vector of line L6.
Proof. The first term of has the gradient because is symmetric. For the second term, the chain rule gives .
Lemma 2 (the inner problem). is symmetric positive definite, and (line L7) is the unique minimizer of the quadratic
which is with replaced by its linearization .
Proof. for . The gradient of with respect to is , and its Hessian is . So is strictly convex and its only stationary point is .
The conjugate gradient method of line L7 solves . In exact arithmetic it finds the solution in at most steps for a symmetric positive definite (Hestenes and Stiefel 1952). In floating point the code stops when the residual is small or after steps.
Termination. Line L7 does at most conjugate gradient steps, and the loop of line L2 runs at most max_outer times. Line L9 can stop it earlier. So the algorithm always returns at line L10.
Theorem 3 (linear operator). Let with a fixed matrix . Then has the unique minimizer
and the first outer loop, started at (line L1) with an exact inner solve, returns . The second outer loop gives , so line L9 stops.
Proof. For a linear the linearization is exact, so and is strictly convex by Lemma 2. At , with , so line L8 gives , the minimizer of by Lemma 2. The identity shows that the two forms of are equal. At the minimizer , so the next inner solve gives .
So for a linear , 3D-Var, global optimal interpolation and the analysis step of the Kalman filter give the same . The covariance is the analysis error covariance (see the proof on the optimal interpolation page). If the errors are Gaussian, is the negative logarithm of the posterior density of up to a constant, so is the maximum a posteriori estimate, which for a linear is also the posterior mean.
Theorem 4 (nonlinear operator). For any differentiable :
- If , the increment of line L7 is a descent direction: .
- The increment is zero exactly when . So if line L9 stops with , the returned is a stationary point of .
Proof. (1) because is positive definite. (2) is invertible, so exactly when , and by Lemma 1.
A stationary point of a nonconvex need not be the global minimum, and the full Gauss-Newton step can increase far from a minimum. A line search on along makes each step decrease ; the plain method of the pseudocode uses the full step, which is the usual choice in operational incremental 3D-Var with few outer loops. Near a stationary point with zero residual the convergence is quadratic, and with a nonzero residual it is in general only linear, as the measured example on the page shows.
Summary. The algorithm always stops. Each outer loop exactly minimizes the cost with linearized at the current point. For a linear the first outer loop returns the unique minimizer of , which equals the Kalman and optimal interpolation analysis . For a nonlinear every increment is a descent direction, and the loop stops with a zero increment only at a stationary point of .
Complexity
The reference code factors and once by Cholesky in time. Each conjugate gradient step costs one product , which is with dense matrices, so outer loops of inner steps cost more. Operational systems, with of the order of or more, never store . They apply with as a sequence of transforms (spectral or wavelet transforms, vertical modes, balance operators), each in about time. The tangent linear and its adjoint cost a small multiple of one evaluation of . A few outer loops with some tens of inner steps each are usual (a rule of thumb, not a bound). With the control variable transform the inner Hessian is , whose eigenvalues are at least 1, which bounds the number of inner steps for a given accuracy in terms of the largest eigenvalue only.
Properties
- Same analysis as OI for a linear . The minimizer is (a theorem). The two differ in what they compute: OI solves small systems in observation space for each grid value, and 3D-Var minimizes once over the whole state.
- Global use of observations. Every observation can influence every grid value through , so the analysis has no jumps from data selection.
- Nonlinear and indirect observations. Only , its tangent linear and its adjoint are needed, so radiances, refractivities and other indirect data can be used directly.
- Fixed . The background covariance is the same every day, so the analysis increments do not follow the flow of the day. 4D-Var and hybrid ensemble methods address this.
- Regularized least squares. The cost is a Tikhonov regularization of the observation fit with the background as the prior and as the penalty matrix.
Variants and improvements
- Control variable transform. Minimize over with and (see control variable transform). This is how all operational 3D-Var systems are written.
- Physical space analysis system (PSAS). Solve in observation space and set . For a linear this is the same analysis, and it is cheaper when is much smaller than (Kalnay 2003, Section 5.5).
- First guess at the appropriate time (FGAT). Compute the departures of line L3 with the background at the time of each observation, while the increment stays valid at one time.
- 4D-Var. Add the model as a link between the times of the window, so that the cost compares the model trajectory with the observations at their own times (see 4D-Var and incremental 4D-Var).
- Hybrid 3D-Var. Replace by a weighted sum of the static and a localized ensemble covariance.
When to use it
Use 3D-Var when the observations are many and of many kinds, some with a nonlinear operator, when a smooth global analysis is wanted, and when a good static model of exists. It is the standard choice for regional and limited area systems with short cycles and for systems where a tangent linear and adjoint of the forecast model are not available. If the errors of the day matter, use an ensemble or a four-dimensional method.
Pitfalls
- Inverse of in the code (line L6). Applying directly fails when is huge or nearly singular, and the inner problem is badly conditioned. Use the control variable transform, which needs only.
- Wrong adjoint (line L5 and line L6). If the code for is not the exact transpose of the code for , the conjugate gradient method fails to converge or converges to a wrong point. Check it with the dot product test to rounding error.
- Departures from the wrong point (line L3). In the incremental form, must be computed with the full nonlinear at the current , not at . Computing it once at freezes the outer loop at the first step.
- Too few inner steps (line L7). Stopping conjugate gradients early gives an increment that is not the minimizer of the inner problem. Then one outer loop is no longer exact for a linear , and the analysis depends on the stopping rule.
- Trusting one outer loop for a nonlinear . The first increment can be far from the minimum, and the full step can even increase . Check the cost after line L8, and add outer loops or a line search.
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)]
three_dimensional_variational_assimilation.py 96 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/three-dimensional-variational-assimilation/. The authors are listed in prov/BZ95E9.jsonl.
"""Three-dimensional variational assimilation (3D-Var).
Notation of Ide, Courtier, Ghil and Lorenc (1997): background x^b in R^n
with error covariance B, observations y^o in R^p with error covariance R,
and an observation operator h from R^n to R^p, possibly nonlinear, with
Jacobian H(x). The analysis minimizes
J(x) = 1/2 (x - x^b)^T B^-1 (x - x^b) + 1/2 (y^o - h(x))^T R^-1 (y^o - h(x)).
The minimizer here is incremental Gauss-Newton: each outer loop linearizes h
at the current x and solves the quadratic problem for the increment with the
conjugate gradient method. B^-1 and R^-1 are applied with Cholesky factors
and never formed. For a linear h one outer loop gives the exact minimizer,
which equals the optimal interpolation and Kalman analysis.
"""
import scimat
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.
Stop when |r| <= tol |b|, or after max_iter steps (default 2 len(b)).
"""
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 cost(x, xb, B, yo, h, R):
"""Return J(x)."""
LB, LR = scimat.cholesky(B), scimat.cholesky(R)
e = scimat.sub(x, xb)
r = scimat.sub(yo, h(x))
return 0.5 * scimat.dot(e, scimat.cholesky_solve(LB, e)) + 0.5 * scimat.dot(r, scimat.cholesky_solve(LR, r))
def gradient(x, xb, B, yo, h, jac, R):
"""Return grad J(x) = B^-1 (x - x^b) - H(x)^T R^-1 (y^o - h(x))."""
LB, LR = scimat.cholesky(B), scimat.cholesky(R)
e = scimat.sub(x, xb)
r = scimat.sub(yo, h(x))
Ht = scimat.transpose(jac(x))
return scimat.sub(scimat.cholesky_solve(LB, e), scimat.matvec(Ht, scimat.cholesky_solve(LR, r)))
def var3d(xb, B, yo, h, jac, R, max_outer=30, tol=1e-12):
"""Return (x^a, iterates): the 3D-Var analysis and the list of outer iterates.
h(x) returns the model equivalents of the observations and jac(x) the
p by n Jacobian of h at x. The outer loop stops when the increment is
below tol (1 + |x|) or after max_outer loops.
"""
LB, LR = scimat.cholesky(B), scimat.cholesky(R)
x = [float(v) for v in xb] # @line L1
iterates = [list(x)]
for _ in range(max_outer): # @line L2
d = scimat.sub(yo, h(x)) # @line L3
Hl = jac(x) # @line L4
Ht = scimat.transpose(Hl)
def apply_a(v): # @line L5
return scimat.add(scimat.cholesky_solve(LB, v), scimat.matvec(Ht, scimat.cholesky_solve(LR, scimat.matvec(Hl, v))))
e = scimat.sub(x, xb)
g = scimat.sub(scimat.cholesky_solve(LB, e), scimat.matvec(Ht, scimat.cholesky_solve(LR, d))) # @line L6
dx = conjugate_gradient(apply_a, [-v for v in g]) # @line L7
x = scimat.add(x, dx) # @line L8
iterates.append(list(x))
if scimat.norm2(dx) <= tol * (1.0 + scimat.norm2(x)): # @line L9
break
return x, iterates # @line L10
def linear_operator(H):
"""Return (h, jac) for the linear observation operator given by the matrix H."""
return (lambda x: scimat.matvec(H, x)), (lambda x: H)
test_three_dimensional_variational_assimilation.py 134 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/three-dimensional-variational-assimilation/. The authors are listed in prov/BZ95E9.jsonl.
import math
import random
import scimat
from three_dimensional_variational_assimilation import (
conjugate_gradient,
cost,
gradient,
linear_operator,
var3d,
)
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_analysis(xb, B, yo, H, R):
"""Oracle: x^b + B H^T (H B H^T + R)^-1 (y^o - H x^b), by Gaussian elimination."""
A = scimat.add(scimat.matmul(scimat.matmul(H, B), scimat.transpose(H)), R)
d = scimat.sub(yo, scimat.matvec(H, xb))
z = scimat.solve(A, d)
return scimat.add(xb, scimat.matvec(scimat.matmul(B, scimat.transpose(H)), z))
def speed():
h = lambda x: [math.hypot(x[0], x[1])]
jac = lambda x: [[x[0] / math.hypot(x[0], x[1]), x[1] / math.hypot(x[0], x[1])]]
return h, jac
def test_scalar_check_value():
h, jac = linear_operator([[1.0]])
xa, _ = var3d([0.0], [[1.0]], [1.0], h, jac, [[1.0]])
assert abs(xa[0] - 0.5) < 1e-15
def test_linear_equals_kalman_and_oi_formula():
rng = random.Random(21)
for _ in range(200):
n, p = rng.randint(1, 6), rng.randint(1, 5)
B, R = random_spd(rng, n), random_spd(rng, p)
H = [[rng.uniform(-1, 1) for _ in range(n)] for _ in range(p)]
xb = [rng.uniform(-3, 3) for _ in range(n)]
yo = [rng.uniform(-3, 3) for _ in range(p)]
h, jac = linear_operator(H)
xa, its = var3d(xb, B, yo, h, jac, R)
xk = kalman_analysis(xb, B, yo, H, R)
for a, b in zip(xa, xk):
assert abs(a - b) <= 1e-10 * (1 + abs(b))
# one outer loop is exact for a linear h
for a, b in zip(its[1], xk):
assert abs(a - b) <= 1e-10 * (1 + abs(b))
assert len(its) <= 3
def test_gradient_matches_finite_differences():
rng = random.Random(22)
n, p = 4, 3
def h(x):
return [x[0] * x[1], math.sin(x[2]) + x[3], x[0] ** 2 - x[3]]
def jac(x):
return [[x[1], x[0], 0.0, 0.0], [0.0, 0.0, math.cos(x[2]), 1.0], [2 * x[0], 0.0, 0.0, -1.0]]
B, R = random_spd(rng, n), random_spd(rng, p)
xb = [rng.uniform(-1, 1) for _ in range(n)]
yo = [rng.uniform(-1, 1) for _ in range(p)]
for _ in range(5):
x = [rng.uniform(-1, 1) for _ in range(n)]
g = gradient(x, xb, B, yo, h, jac, R)
eps = 1e-6
for j in range(n):
xp, xm = list(x), list(x)
xp[j] += eps
xm[j] -= eps
fd = (cost(xp, xb, B, yo, h, R) - cost(xm, xb, B, yo, h, R)) / (2 * eps)
assert abs(fd - g[j]) < 1e-6 * (1 + abs(g[j]))
def test_wind_speed_isotropic_exact():
# B = I: the minimum lies on the ray through x^b with speed (5 + 6) / 2.
h, jac = speed()
xa, its = var3d([3.0, 4.0], [[1.0, 0.0], [0.0, 1.0]], [6.0], h, jac, [[1.0]])
assert abs(xa[0] - 3.3) < 1e-12 and abs(xa[1] - 4.4) < 1e-12
def test_wind_speed_anisotropic_converges_to_stationary_point():
h, jac = speed()
B = [[1.0, 0.0], [0.0, 4.0]]
xa, its = var3d([3.0, 4.0], B, [6.0], h, jac, [[1.0]])
g = gradient(xa, [3.0, 4.0], B, [6.0], h, jac, [[1.0]])
assert max(abs(v) for v in g) < 1e-10
assert abs(xa[0] - 3.134034646) < 1e-8 and abs(xa[1] - 4.825496589) < 1e-8
costs = [cost(x, [3.0, 4.0], B, [6.0], h, [[1.0]]) for x in its]
assert all(costs[k + 1] <= costs[k] + 1e-15 for k in range(len(costs) - 1))
# Gauss-Newton converges linearly here: the residual is not zero and h is curved.
e = [scimat.norm2(scimat.sub(x, xa)) for x in its[1:5]]
for k in range(len(e) - 1):
assert 0.01 < e[k + 1] / e[k] < 0.1
# The minimum is a global one: compare with a fine grid search.
best = min(
cost([3.0 + i * 0.01 - 1.0, 4.0 + j * 0.01 - 1.0], [3.0, 4.0], B, [6.0], h, [[1.0]])
for i in range(201)
for j in range(201)
)
assert cost(xa, [3.0, 4.0], B, [6.0], h, [[1.0]]) <= best + 1e-12
def test_conjugate_gradient_against_elimination():
rng = random.Random(23)
for _ in range(100):
n = rng.randint(1, 8)
A = random_spd(rng, n)
b = [rng.uniform(-1, 1) for _ in range(n)]
z = conjugate_gradient(lambda v: scimat.matvec(A, v), b)
zo = scimat.solve(A, b)
for a, c in zip(z, zo):
assert abs(a - c) <= 1e-9 * (1 + abs(c))
def test_no_information_in_observations():
# Huge R: the analysis stays at the background.
h, jac = linear_operator([[1.0, 1.0]])
xa, _ = var3d([1.0, 2.0], [[1.0, 0.3], [0.3, 2.0]], [100.0], h, jac, [[1e12]])
assert abs(xa[0] - 1.0) < 1e-8 and abs(xa[1] - 2.0) < 1e-8
History
Sasaki proposed variational objective analysis in the late 1950s, with dynamical constraints imposed through a cost function. Lorenc showed in 1986 that the analysis of optimal interpolation is the minimizer of a cost function derived from Bayes' theorem, which opened the way to a variational method with nonlinear observation operators and without data selection. Parrish and Derber's spectral statistical interpolation, described in 1992, replaced optimal interpolation at the US National Meteorological Center, and ECMWF followed with its own 3D-Var in the mid 1990s, before moving to 4D-Var in 1997. The incremental form with outer and inner loops was proposed for 4D-Var by Courtier, Thepaut and Hollingsworth in 1994, and 3D-Var systems use the same structure.
References
- A. C. Lorenc, Analysis methods for numerical weather prediction, Quarterly Journal of the Royal Meteorological Society 112(474) (1986) 1177-1194, the Bayesian derivation of the variational cost and its equivalence with optimal interpolation
- D. F. Parrish and J. C. Derber, The National Meteorological Center's spectral statistical-interpolation analysis system, Monthly Weather Review 120(8) (1992) 1747-1763, the first operational 3D-Var, with B modeled in spectral space
- Eugenia Kalnay, Atmospheric Modeling, Data Assimilation and Predictability, Cambridge University Press, 2003, Section 5.5 (3D-Var, the physical space analysis scheme, and their relation to OI)
- K. Law, A. Stuart and K. Zygalakis, Data Assimilation, A Mathematical Introduction, Springer, 2015, Section 4.2.1 (3DVAR as a filter) and Section 4.4.2 (the 3DVAR filter for the Lorenz models)
- 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 BZ95E9 Edit this page History Report an error Markdown