Algorithmintro
Optimal interpolation
Also called statistical interpolation.
Sets each grid value to background plus weights times innovations of nearby observations, with weights from fixed B and R that minimize the error variance.
- Time
- Θ(n s^3) worst
- Space
- Θ(s^2) extra
- Where
- n = the number of grid values; p = the number of observations; s = the largest number of observations selected for one grid value, with covariance entries from a formula
- Model
- Real RAM
- Properties
- deterministiclinear in data
- Evidence
- Proof sketchCode in 1 languages
- Origin
- Lev S. Gandin, 1963
Optimal interpolation (OI) computes an analysis of a gridded field from a background (usually a short forecast) and a set of observations . For each grid value it adds to the background a weighted sum of the innovations of nearby observations. The weights come from the background error covariance and the observation error covariance , which are fixed in advance, and they minimize the error variance of the analysis. If every grid value uses all observations, OI gives exactly the analysis step of the Kalman filter and the minimizer of 3D-Var. The local selection of observations is what made OI cheap enough for operational weather prediction in the 1970s and 1980s, and it is also its main weakness.
In plain words
A weather center has a forecast for every point of a grid and a few hundred measurements scattered between the points. At each measurement it looks at how far the measurement is from the forecast. Then, for each grid point, it takes the forecast and adds a part of the differences at the measurements nearby. A close measurement gets a large part and a far one gets a small part. A measurement that is known to be poor also gets a small part. The parts are not guessed: they come from a statistical model of how forecast errors at two places are related, and they are the ones that make the expected error at that point as small as possible. To save work, each grid point only looks at the measurements that are close to it.
The problem
Input. A background with error covariance (, symmetric positive semidefinite), observations with error covariance (, symmetric positive definite), a linear observation operator (), and for each grid index a selection of observations. Here is the number of grid values and the number of observations. The errors are assumed to have zero mean and to be uncorrelated with each other. 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. For each , the value , where is the innovation and minimizes the error variance of among all such linear updates, and that smallest variance .
The algorithm
Write , the covariance of the innovation. The entry is the covariance between the background error at observation and the background error at grid value .
OI(x^b, B, y^o, H, R, select)- 1
d <- y^o - H x^b ▷ innovations - 2
for i <- 1 to n do - 3
S <- select(i) ▷ nearby observations - 4
A_S <- (H B H^T + R)[S, S] - 5
c <- (H B)[S, i] - 6
w <- solve A_S w = c - 7
x^a_i <- x^b_i + w^T d[S] - 8
var_i <- B_ii - w^T c - 9
return x^a, var
Line L1 computes the observation minus background differences once. Lines L3 to L6 set up and solve a small symmetric positive definite system for each grid value. Line L7 applies the weights, and line L8 gives the expected error variance of the result. If select returns no observation, the analysis keeps the background value and its variance . Operational schemes often share one selection between all the grid values of a box, so that one factorization of serves many values of (Lorenc 1981).
Example
Take grid points at positions , (unit variance, correlation halving with each grid step), two observations at points 1 and 4 with , and . The innovations are . The global analysis uses both observations everywhere. The local analysis uses only the observations within distance of the grid point. All numbers are exact fractions in the test file, and they are rounded here.
| global | global | local | local | local | ||
|---|---|---|---|---|---|---|
| 0 | 2 | 2.389 | 0.800 | {1} | 2.4 | 0.8 |
| 1 | 3 | 3.778 | 0.199 | {1} | 3.8 | 0.2 |
| 2 | 4 | 4.222 | 0.768 | {1} | 4.4 | 0.8 |
| 3 | 4 | 3.778 | 0.768 | {4} | 3.6 | 0.8 |
| 4 | 3 | 2.222 | 0.199 | {4} | 2.2 | 0.2 |
| 5 | 2 | 1.611 | 0.800 | {4} | 1.6 | 0.8 |
At point 1 the global gain gives the observation the weight and the far observation the weight . The local analysis at points 2 and 3 uses different observations, so the field jumps from to between two points that had the same background, while the global field goes from to . The local variances are never smaller than the global ones, as Corollary 4 of the proof states.
For a smaller check: two points with , and one observation of the first point with . Then , , the weights are and , , and the variances are and . The second point is not observed, but it moves because its background error is correlated with the error at the first point.
Correctness
The proof shows four facts. is positive definite, so line L6 always has a unique solution. The error of has the variance , which line L6 minimizes, and line L8 is the minimum (a theorem when the errors are unbiased, uncorrelated with each other, and and are their true covariances). Adding observations to never increases the variance. With all observations selected, the output is with , the variances are the diagonal of , and this equals , the 3D-Var minimizer.
Proof: Optimal interpolation is the best linear unbiased analysis for its data selectionfull
Setting. The state has components and there are observations. The background is and the observations are , with a linear matrix . The errors have zero mean, , and . is symmetric positive semidefinite and is symmetric positive definite. Write and (line L1). For a grid point and a selection (line L3), is the submatrix of line L4 and is the vector of line L5.
Lemma 1 (the systems are solvable). is symmetric positive definite, and so is every principal submatrix with not empty.
Proof. For , . For a principal submatrix, take zero outside .
Termination. Line L2 runs over the grid points once. Each pass does a finite amount of work: the selection of line L3, the copies of lines L4 and L5, and one linear solve of size in line L6, which succeeds by Lemma 1. So the algorithm stops after passes and returns at line L9.
Lemma 2 (error of a linear update). For any weight vector , the estimate has the error , which has zero mean and the variance
Proof. , which gives the error formula and the zero mean. Expand the variance: , because and are uncorrelated, and .
Theorem 3 (optimality for the selection). Among all estimates , the weights of line L6, , give the unique smallest error variance. The value of line L8, , is that smallest variance.
Proof. is a quadratic function of with the Hessian , which is positive definite by Lemma 1. So has exactly one minimizer, where the gradient is zero. At that point , so . Line L7 forms the estimate with this .
Corollary 4 (more observations never hurt). If , the variance of line L8 for is at most the variance for . Both are at most , the value for empty.
Proof. An estimate that uses is an estimate that uses with zero weights on , so the minimum over the larger set is not larger.
An observation outside does not enter lines L4 to L8 for point , so a change in its value does not change .
Theorem 5 (global selection is the Kalman update). If is the set of all observations for every , the output is with , and the variances are the diagonal of . If is also positive definite, then
Proof. With = all, line L6 gives , so because and are symmetric. Line L7 is row of and line L8 is .
For the second form, . Multiply by on the left and by on the right: . Then , so . Finally , and gives the stated form.
The second form is the minimizer of the 3D-Var cost , whose gradient is zero exactly there. So global OI, the Kalman update and 3D-Var give the same analysis for a linear . If the errors are also Gaussian, is the mean of the posterior distribution of and is its covariance.
Summary. The algorithm stops after solves of positive definite systems. For each grid point it returns the linear unbiased estimate of smallest error variance among those that use the selected observations, together with that variance. With all observations selected, it returns the Kalman analysis and the diagonal of .
Complexity
With observations selected for a grid value, line L6 costs , so the loop costs when the covariance entries of lines L4 and L5 come from a formula in time each and touches a bounded number of grid values per observation. Sharing one selection over a box of grid values divides the factorization cost by about . The extra space is for . For comparison, the global solve with all observations costs with a direct method. The reference code forms and as dense matrices for clarity, which costs in addition.
Properties
- Linear in the data. is an affine function of and , and the weights do not depend on the values of the data, only on , , and the selection.
- Optimal only for the model of the errors. The variance of line L8 is the true error variance only if and are the true covariances. With wrong covariances the analysis is still unbiased, but it is no longer the best one, and line L8 is no longer its error variance.
- Exact for observed values in the limit. As with observations at grid points and global selection, the analysis matches the observations and interpolates between them with the shape of .
- Fixed covariances. does not evolve with the flow. Methods that propagate it, such as the Kalman filter and the ensemble Kalman filter, give gains that change from day to day.
- Same equations as kriging. For one variable with selecting point values, the weights of line L6 are those of simple kriging and of the posterior mean of a Gaussian process with a known mean.
Variants and improvements
- Multivariate OI. The state holds several variables, such as height and wind, and couples them, for example with geostrophic balance. One height observation then also changes the wind (Lorenc 1981).
- Box selection. All grid values of a box use the same observations from the box and its neighbours. This shares the work and reduces the jumps between neighbouring values.
- Physical space analysis (PSAS). Solve the global system once, for example with the conjugate gradient method, and set . This removes the selection and gives the global analysis (Kalnay 2003, Section 5.5).
- 3D-Var. Minimize the cost function in state space. For a linear this gives the same analysis, and it also accepts a nonlinear (see 3D-Var).
- Flow dependent weights. Replace the fixed by a sample covariance from an ensemble, with localization, which gives the ensemble Kalman filter.
When to use it
Use OI when the covariances can be modeled by simple formulas, when the observations are direct or nearly direct measurements of the state (so that is an interpolation), and when a cheap analysis with a known error estimate is needed. It is still a good choice for surface fields such as sea surface temperature, snow and soil moisture. For satellite radiances and other observations with a nonlinear , or when a smooth global analysis is needed, use 3D-Var or an ensemble method.
Pitfalls
- Jumps from the selection (line L3). Neighbouring grid values that select different observations get different weights, and the analysis can jump between them, as in the example. Large overlapping selections or boxes reduce the jumps. The size of the selection is a tuned rule of thumb.
- Sign of the innovation (line L1). Writing moves the analysis away from the observations. A test with one observation and shows the error at once: the analysis must be halfway between background and observation.
- Covariance with the wrong grid value (line L5). For an observation between grid points, must be , the covariance between the background interpolated to the observation and the value at . Using at the nearest grid point gives the wrong weights.
- Correlated observation errors (line L4). Taking diagonal when the errors of nearby observations are correlated, as for dense satellite data, gives too much weight to clusters of observations. Thinning the data or modeling the correlation in fixes this.
- Trusting the variance (line L8). The variance only reflects the model of and . Check it against the statistics of the innovations, for example with Desroziers diagnostics.
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/optimal-interpolation/. The authors are listed in prov/BG2VYK.jsonl.
"""Optimal interpolation (OI) with local data selection.
Notation of Ide, Courtier, Ghil and Lorenc (1997): background x^b in R^n,
observations y^o in R^p, a linear observation operator H (p by n), the
background error covariance B (n by n) and the observation error covariance
R (p by p). The innovation is d = y^o - H x^b.
For each grid point i, OI picks a set S_i of observations, solves the small
system (H B H^T + R)[S_i, S_i] w = (H B)[S_i, i] and sets
x^a_i = x^b_i + w^T d[S_i]. With S_i = all observations for every i, the
result is x^b + K d with the Kalman gain K = B H^T (H B H^T + R)^-1.
Matrices are lists of rows, as in scimat. With Fraction data the result is
exact. Cost: forming H B H^T and H B is O(p n^2) for a dense H; each point
then costs O(s^3) for s = |S_i|, so the analysis costs O(n s^3) after that.
"""
import math
import scimat
def oi_analysis(xb, B, yo, H, R, select=None):
"""Return (xa, var_a): the OI analysis and its error variance at each point.
select(i) returns the list of observation indices used for grid point i;
None means all observations for every point (the global analysis).
var_a[i] = B[i][i] - w^T c is the analysis error variance of point i when
B and R are the true covariances.
"""
n, p = len(xb), len(yo)
Hxb = scimat.matvec(H, xb)
d = [yo[k] - Hxb[k] for k in range(p)] # @line L1
HB = scimat.matmul(H, B) # p by n, column i holds cov(H x, x_i)
A = scimat.add(scimat.matmul(HB, scimat.transpose(H)), R) # H B H^T + R
xa, var_a = [], []
for i in range(n): # @line L2
S = list(range(p)) if select is None else list(select(i)) # @line L3
if not S:
xa.append(xb[i])
var_a.append(B[i][i])
continue
As = [[A[a][b] for b in S] for a in S] # @line L4
c = [HB[a][i] for a in S] # @line L5
w = scimat.solve(As, c) # @line L6
xa.append(xb[i] + sum(w[t] * d[S[t]] for t in range(len(S)))) # @line L7
var_a.append(B[i][i] - sum(w[t] * c[t] for t in range(len(S)))) # @line L8
return xa, var_a # @line L9
def radius_selector(grid_pos, obs_pos, radius, max_obs=None, period=None):
"""Return select(i): the observations within radius of grid point i.
Distances are |grid_pos[i] - obs_pos[k]|, or the distance on a circle of
length period. If max_obs is given, keep only the max_obs nearest ones.
"""
def dist(a, b):
r = abs(a - b)
if period is not None:
r = min(r, period - r)
return r
def select(i):
near = [(dist(grid_pos[i], q), k) for k, q in enumerate(obs_pos) if dist(grid_pos[i], q) <= radius]
near.sort()
if max_obs is not None:
near = near[:max_obs]
return sorted(k for _, k in near)
return select
def ar1_covariance(n, sigma2, rho):
"""Return B with B_ij = sigma2 rho^|i - j|, the covariance of an AR(1) sequence.
B is symmetric positive definite for |rho| < 1 and sigma2 > 0.
"""
return [[sigma2 * rho ** abs(i - j) for j in range(n)] for i in range(n)]
def gaussian_covariance(pos, sigma2, length, period=None):
"""Return B_ij = sigma2 exp(-r_ij^2 / (2 length^2)) for points at pos.
With period, r_ij is the distance on a circle of that length. The Gaussian
correlation on a line is positive definite; on a circle it is positive
definite only when length is small compared with the period.
"""
n = len(pos)
B = scimat.zeros(n)
for i in range(n):
for j in range(n):
r = abs(pos[i] - pos[j])
if period is not None:
r = min(r, period - r)
B[i][j] = sigma2 * math.exp(-r * r / (2.0 * length * length))
return B
def interpolation_operator(obs_pos, n, dx, period=True):
"""Return H (p by n) for linear interpolation from grid points j dx to obs_pos.
On a periodic grid of n points the position is taken modulo n dx.
"""
H = scimat.zeros(len(obs_pos), n)
for k, q in enumerate(obs_pos):
s = q / dx
j = math.floor(s)
a = s - j
if period:
H[k][j % n] += 1 - a
H[k][(j + 1) % n] += a
else:
H[k][j] += 1 - a
if a != 0:
H[k][j + 1] += a
return H
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_optimal_interpolation.py 189 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/optimal-interpolation/. The authors are listed in prov/BG2VYK.jsonl.
import math
import random
from fractions import Fraction as Fr
import scimat
from optimal_interpolation import (
ar1_covariance,
gaussian_covariance,
interpolation_operator,
oi_analysis,
radius_selector,
)
def information_form(xb, B, yo, H, R):
"""Oracle: x^a = (B^-1 + H^T R^-1 H)^-1 (B^-1 x^b + H^T R^-1 y^o) and P^a."""
Bi = scimat.inv(B)
Ri = scimat.inv(R)
Ht = scimat.transpose(H)
A = scimat.add(Bi, scimat.matmul(scimat.matmul(Ht, Ri), H))
rhs = scimat.add(scimat.matvec(Bi, xb), scimat.matvec(scimat.matmul(Ht, Ri), yo))
return scimat.solve(A, rhs), scimat.inv(A)
def random_spd(rng, n, exact):
L = [[Fr(rng.randint(-3, 3), rng.randint(1, 3)) for _ in range(n)] for _ in range(n)]
S = scimat.add(scimat.matmul(L, scimat.transpose(L)), scimat.eye(n))
if exact:
return S
return [[float(v) for v in row] for row in S]
def test_scalar_check_value():
xa, va = oi_analysis([Fr(0)], [[Fr(1)]], [Fr(1)], [[Fr(1)]], [[Fr(1)]])
assert xa == [Fr(1, 2)]
assert va == [Fr(1, 2)]
def test_two_point_spreading():
B = [[Fr(1), Fr(1, 2)], [Fr(1, 2), Fr(1)]]
xa, va = oi_analysis([Fr(10), Fr(12)], B, [Fr(11)], [[1, 0]], [[Fr(1)]])
assert xa == [Fr(21, 2), Fr(49, 4)]
assert va == [Fr(1, 2), Fr(7, 8)]
def page_problem():
n = 6
B = ar1_covariance(n, Fr(1), Fr(1, 2))
H = [[1 if j == q else 0 for j in range(n)] for q in (1, 4)]
R = [[Fr(1, 4), 0], [0, Fr(1, 4)]]
xb = [Fr(v) for v in (2, 3, 4, 4, 3, 2)]
yo = [Fr(4), Fr(2)]
return xb, B, yo, H, R
def test_page_example_global_and_local():
xb, B, yo, H, R = page_problem()
xa, va = oi_analysis(xb, B, yo, H, R)
assert xa == [Fr(43, 18), Fr(34, 9), Fr(38, 9), Fr(34, 9), Fr(20, 9), Fr(29, 18)]
assert va == [Fr(1267, 1584), Fr(79, 396), Fr(76, 99), Fr(76, 99), Fr(79, 396), Fr(1267, 1584)]
sel = radius_selector(list(range(6)), [1, 4], Fr(3, 2))
xl, vl = oi_analysis(xb, B, yo, H, R, sel)
assert xl == [Fr(12, 5), Fr(19, 5), Fr(22, 5), Fr(18, 5), Fr(11, 5), Fr(8, 5)]
assert vl == [Fr(4, 5), Fr(1, 5), Fr(4, 5), Fr(4, 5), Fr(1, 5), Fr(4, 5)]
for i in range(6):
assert vl[i] >= va[i]
def test_global_equals_information_form_exact():
rng = random.Random(11)
for _ in range(40):
n, p = rng.randint(1, 4), rng.randint(1, 3)
B = random_spd(rng, n, True)
R = random_spd(rng, p, True)
H = [[Fr(rng.randint(-2, 2)) for _ in range(n)] for _ in range(p)]
xb = [Fr(rng.randint(-5, 5)) for _ in range(n)]
yo = [Fr(rng.randint(-5, 5)) for _ in range(p)]
xa, va = oi_analysis(xb, B, yo, H, R)
xo, Po = information_form(xb, B, yo, H, R)
assert xa == xo
assert va == [Po[i][i] for i in range(n)]
def test_global_equals_information_form_float_many():
rng = random.Random(12)
for _ in range(500):
n, p = rng.randint(1, 5), rng.randint(1, 4)
B = random_spd(rng, n, False)
R = random_spd(rng, p, False)
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)]
xa, va = oi_analysis(xb, B, yo, H, R)
xo, Po = information_form(xb, B, yo, H, R)
for i in range(n):
assert abs(xa[i] - xo[i]) <= 1e-10 * (1 + abs(xo[i]))
assert abs(va[i] - Po[i][i]) <= 1e-10 * (1 + abs(Po[i][i]))
assert -1e-12 <= va[i] <= B[i][i] + 1e-12
def test_unselected_observations_have_no_effect():
rng = random.Random(13)
n = 12
pos = list(range(n))
obs = [0.5, 2.25, 4.0, 6.75, 9.5, 11.0]
B = gaussian_covariance(pos, 1.0, 1.5)
H = interpolation_operator(obs, n, 1.0, period=False)
R = [[0.25 if i == j else 0.0 for j in range(len(obs))] for i in range(len(obs))]
xb = [rng.uniform(-1, 1) for _ in range(n)]
yo = [rng.uniform(-1, 1) for _ in range(len(obs))]
sel = radius_selector(pos, obs, 2.0)
xa, _ = oi_analysis(xb, B, yo, H, R, sel)
for k in range(len(obs)):
y2 = list(yo)
y2[k] += 10.0
xa2, _ = oi_analysis(xb, B, y2, H, R, sel)
for i in range(n):
if k in sel(i):
assert abs(xa2[i] - xa[i]) > 1e-6
else:
assert xa2[i] == xa[i]
def test_local_equals_global_when_influence_is_local():
# Diagonal B and observations at grid points: each point only feels its own observation.
n = 5
B = [[Fr(i + 1) if i == j else Fr(0) for j in range(n)] for i in range(n)]
obs = [0, 2, 3]
H = [[1 if j == q else 0 for j in range(n)] for q in obs]
R = [[Fr(1, 2) if i == j else 0 for j in range(3)] for i in range(3)]
xb = [Fr(1)] * n
yo = [Fr(3), Fr(-1), Fr(2)]
g = oi_analysis(xb, B, yo, H, R)
loc = oi_analysis(xb, B, yo, H, R, radius_selector(list(range(n)), obs, 0))
assert g == loc
def test_max_obs_limits_selection():
sel = radius_selector([0.0, 5.0], [0.1, 0.2, 0.9, 4.0, 9.0], 10.0, max_obs=2)
assert sel(0) == [0, 1]
assert sel(1) == [3, 4] # distances 1.0 and 4.0 beat 4.1
per = radius_selector([0.0], [9.5, 3.0], 1.0, period=10.0)
assert per(0) == [0]
def test_analysis_variance_by_sampling():
# The error of the analysis has variance var_a when B and R are the true covariances.
rng = random.Random(14)
B = [[1.0, 0.6, 0.2], [0.6, 1.0, 0.6], [0.2, 0.6, 1.0]]
H = [[0.5, 0.5, 0.0], [0.0, 0.0, 1.0]]
R = [[0.5, 0.0], [0.0, 0.25]]
LB = scimat.cholesky(B)
xt = [0.0, 0.0, 0.0]
N = 6000
sq = [0.0, 0.0, 0.0]
va = None
for _ in range(N):
z = [rng.gauss(0, 1) for _ in range(3)]
xb = [sum(LB[i][k] * z[k] for k in range(3)) for i in range(3)]
yo = [0.0 + math.sqrt(R[0][0]) * rng.gauss(0, 1), 0.0 + math.sqrt(R[1][1]) * rng.gauss(0, 1)]
xa, va = oi_analysis(xb, B, yo, H, R)
for i in range(3):
sq[i] += (xa[i] - xt[i]) ** 2
for i in range(3):
est = sq[i] / N
se = va[i] * math.sqrt(2.0 / N)
assert abs(est - va[i]) < 4 * se
def test_interpolation_operator_reproduces_linear_functions():
n, dx = 8, 0.5
obs = [0.0, 0.3, 1.25, 3.5]
H = interpolation_operator(obs, n, dx, period=False)
grid = [2.0 + 3.0 * j * dx for j in range(n)]
vals = scimat.matvec(H, grid)
for q, v in zip(obs, vals):
assert abs(v - (2.0 + 3.0 * q)) < 1e-12
for row in interpolation_operator([3.9, 0.2], n, dx):
assert abs(sum(row) - 1.0) < 1e-12
def test_no_observations_keeps_background():
xb, B, yo, H, R = page_problem()
xa, va = oi_analysis(xb, B, yo, H, R, lambda i: [])
assert xa == xb
assert va == [B[i][i] for i in range(6)]
History
Lev Gandin published the method in 1963 in Leningrad as the optimal interpolation of meteorological fields, using statistical structure functions estimated from data, and the book was translated into English in 1965. Andrew Lorenc's global three-dimensional multivariate scheme of 1981 was the operational analysis at ECMWF. OI was the main analysis method of the large weather centers until variational methods replaced it in the 1990s, starting with the spectral statistical interpolation of Parrish and Derber (1992) at the US National Meteorological Center, which solves the same statistical problem without local selection.
References
- L. S. Gandin, Objective Analysis of Meteorological Fields, 1963 (English translation 1965), optimal interpolation of meteorological fields with statistical structure functions
- A. C. Lorenc, A global three-dimensional multivariate statistical interpolation scheme, Monthly Weather Review 109(4) (1981) 701-721, the operational global multivariate scheme, with data selection in boxes
- Eugenia Kalnay, Atmospheric Modeling, Data Assimilation and Predictability, Cambridge University Press, 2003, Section 5.4 (multivariate statistical data assimilation methods) and Section 5.5 (relation of 3D-Var and PSAS to OI)
- Roger Daley, Atmospheric Data Analysis, Cambridge University Press, 1991, the chapters on statistical interpolation
- 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 BG2VYK Edit this page History Report an error Markdown