Algorithm Search⌘K

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
Properties
deterministiclinear in data
Origin
Lev S. Gandin, 1963

Optimal interpolation (OI) computes an analysis xax^a of a gridded field from a background xbx^b (usually a short forecast) and a set of observations yoy^o. For each grid value it adds to the background a weighted sum of the innovations yo−H(xb)y^o - H(x^b) of nearby observations. The weights come from the background error covariance BB and the observation error covariance RR, 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 xb∈Rnx^b \in \mathbb R^n with error covariance BB (n×nn \times n, symmetric positive semidefinite), observations yo∈Rpy^o \in \mathbb R^p with error covariance RR (p×pp \times p, symmetric positive definite), a linear observation operator HH (p×np \times n), and for each grid index ii a selection Si⊆{1,…,p}S_i \subseteq \{1, \ldots, p\} of observations. Here nn is the number of grid values and pp 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, HH is its CC, and xbx^b and BB are its predicted values x^\hat x and PP.

Output. For each ii, the value xia=xib+wi⊤dSix^a_i = x^b_i + w_i^\top d_{S_i}, where d=yo−Hxbd = y^o - H x^b is the innovation and wiw_i minimizes the error variance of xiax^a_i among all such linear updates, and that smallest variance σa,i2\sigma^2_{a,i}.

The algorithm

Write A=HBH⊤+RA = H B H^\top + R, the covariance of the innovation. The entry (HB)k,i(HB)_{k,i} is the covariance between the background error at observation kk and the background error at grid value ii.

  1. OI(x^b, B, y^o, H, R, select)
  2. 1d <- y^o - H x^b ▷ innovations
  3. 2for i <- 1 to n do
  4. 3S <- select(i) ▷ nearby observations
  5. 4A_S <- (H B H^T + R)[S, S]
  6. 5c <- (H B)[S, i]
  7. 6w <- solve A_S w = c
  8. 7x^a_i <- x^b_i + w^T d[S]
  9. 8var_i <- B_ii - w^T c
  10. 9return 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 BiiB_{ii}. Operational schemes often share one selection between all the grid values of a box, so that one factorization of ASA_S serves many values of ii (Lorenc 1981).

Example

Take n=6n = 6 grid points at positions 0,…,50, \ldots, 5, Bij=(1/2)∣i−j∣B_{ij} = (1/2)^{|i - j|} (unit variance, correlation halving with each grid step), two observations at points 1 and 4 with R=14IR = \tfrac14 I, xb=(2,3,4,4,3,2)x^b = (2, 3, 4, 4, 3, 2) and yo=(4,2)y^o = (4, 2). The innovations are d=(1,−1)d = (1, -1). The global analysis uses both observations everywhere. The local analysis uses only the observations within distance 1.51.5 of the grid point. All numbers are exact fractions in the test file, and they are rounded here.

ii xibx^b_i global xiax^a_i global σa,i2\sigma^2_{a,i} local SiS_i local xiax^a_i local σa,i2\sigma^2_{a,i}
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 79/99≈0.8079/99 \approx 0.80 and the far observation the weight 2/992/99. The local analysis at points 2 and 3 uses different observations, so the field jumps from 4.44.4 to 3.63.6 between two points that had the same background, while the global field goes from 4.2224.222 to 3.7783.778. The local variances are never smaller than the global ones, as Corollary 4 of the proof states.

For a smaller check: two points with B=(11/21/21)B = \begin{pmatrix} 1 & 1/2 \\ 1/2 & 1 \end{pmatrix}, xb=(10,12)x^b = (10, 12) and one observation yo=11y^o = 11 of the first point with R=1R = 1. Then d=1d = 1, A=2A = 2, the weights are 1/21/2 and 1/41/4, xa=(10.5,12.25)x^a = (10.5, 12.25), and the variances are 1/21/2 and 7/87/8. 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. ASA_S is positive definite, so line L6 always has a unique solution. The error of xib+w⊤dSx^b_i + w^\top d_S has the variance Bii−2w⊤c+w⊤ASwB_{ii} - 2w^\top c + w^\top A_S w, which line L6 minimizes, and line L8 is the minimum (a theorem when the errors are unbiased, uncorrelated with each other, and BB and RR are their true covariances). Adding observations to SiS_i never increases the variance. With all observations selected, the output is xb+Kdx^b + K d with K=BH⊤(HBH⊤+R)−1K = B H^\top (H B H^\top + R)^{-1}, the variances are the diagonal of (I−KH)B(I - KH)B, and this equals (B−1+H⊤R−1H)−1(B−1xb+H⊤R−1yo)(B^{-1} + H^\top R^{-1} H)^{-1}(B^{-1}x^b + H^\top R^{-1} y^o), the 3D-Var minimizer.

Proof: Optimal interpolation is the best linear unbiased analysis for its data selectionfull

Setting. The state has nn components and there are pp observations. The background is xb=xt+εbx^b = x^t + \varepsilon^b and the observations are yo=Hxt+εoy^o = H x^t + \varepsilon^o, with a linear p×np \times n matrix HH. The errors have zero mean, cov(εb)=B\mathrm{cov}(\varepsilon^b) = B, cov(εo)=R\mathrm{cov}(\varepsilon^o) = R and cov(εb,εo)=0\mathrm{cov}(\varepsilon^b, \varepsilon^o) = 0. BB is symmetric positive semidefinite and RR is symmetric positive definite. Write A=HBH⊤+RA = H B H^\top + R and d=yo−Hxbd = y^o - H x^b (line L1). For a grid point ii and a selection S=SiS = S_i (line L3), ASA_S is the submatrix of line L4 and c=(HB)S,ic = (H B)_{S,i} is the vector of line L5.

Lemma 1 (the systems are solvable). AA is symmetric positive definite, and so is every principal submatrix ASA_S with SS not empty.

Proof. For z≠0z \ne 0, z⊤Az=(H⊤z)⊤B(H⊤z)+z⊤Rz≥z⊤Rz>0z^\top A z = (H^\top z)^\top B (H^\top z) + z^\top R z \ge z^\top R z > 0. For a principal submatrix, take zz zero outside SS. □\square

Termination. Line L2 runs over the nn 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 ∣S∣|S| in line L6, which succeeds by Lemma 1. So the algorithm stops after nn passes and returns at line L9.

Lemma 2 (error of a linear update). For any weight vector w∈R∣S∣w \in \mathbb R^{|S|}, the estimate x^i=xib+w⊤dS\hat x_i = x^b_i + w^\top d_S has the error x^i−xit=εib+w⊤(εo−Hεb)S\hat x_i - x^t_i = \varepsilon^b_i + w^\top(\varepsilon^o - H\varepsilon^b)_S, which has zero mean and the variance

V(w)=Bii−2w⊤c+w⊤ASw.V(w) = B_{ii} - 2 w^\top c + w^\top A_S w.

Proof. d=Hxt+εo−H(xt+εb)=εo−Hεbd = H x^t + \varepsilon^o - H(x^t + \varepsilon^b) = \varepsilon^o - H\varepsilon^b, which gives the error formula and the zero mean. Expand the variance: var(εib)=Bii\mathrm{var}(\varepsilon^b_i) = B_{ii}, cov(εib,(εo−Hεb)S)=−(HB)S,i=−c\mathrm{cov}(\varepsilon^b_i, (\varepsilon^o - H\varepsilon^b)_S) = -(HB)_{S,i} = -c because εb\varepsilon^b and εo\varepsilon^o are uncorrelated, and cov((εo−Hεb)S)=(R+HBH⊤)SS=AS\mathrm{cov}((\varepsilon^o - H\varepsilon^b)_S) = (R + H B H^\top)_{SS} = A_S. □\square

Theorem 3 (optimality for the selection). Among all estimates xib+w⊤dSx^b_i + w^\top d_S, the weights of line L6, ASw=cA_S w = c, give the unique smallest error variance. The value of line L8, Bii−w⊤cB_{ii} - w^\top c, is that smallest variance.

Proof. VV is a quadratic function of ww with the Hessian 2AS2A_S, which is positive definite by Lemma 1. So VV has exactly one minimizer, where the gradient 2ASw−2c2A_S w - 2c is zero. At that point w⊤ASw=w⊤cw^\top A_S w = w^\top c, so V(w)=Bii−w⊤cV(w) = B_{ii} - w^\top c. Line L7 forms the estimate with this ww. □\square

Corollary 4 (more observations never hurt). If S⊆S′S \subseteq S', the variance of line L8 for S′S' is at most the variance for SS. Both are at most BiiB_{ii}, the value for SS empty.

Proof. An estimate that uses SS is an estimate that uses S′S' with zero weights on S′∖SS' \setminus S, so the minimum over the larger set is not larger. □\square

An observation outside SiS_i does not enter lines L4 to L8 for point ii, so a change in its value does not change xiax^a_i.

Theorem 5 (global selection is the Kalman update). If SiS_i is the set of all observations for every ii, the output is xa=xb+Kdx^a = x^b + K d with K=BH⊤A−1K = B H^\top A^{-1}, and the variances are the diagonal of Pa=(I−KH)BP^a = (I - K H) B. If BB is also positive definite, then

xa=P (B−1xb+H⊤R−1yo),Pa=P,P=(B−1+H⊤R−1H)−1.x^a = P\,(B^{-1} x^b + H^\top R^{-1} y^o), \qquad P^a = P, \qquad P = (B^{-1} + H^\top R^{-1} H)^{-1}.

Proof. With SS = all, line L6 gives w=A−1(HB):,iw = A^{-1}(HB)_{:,i}, so w⊤=(BH⊤A−1)i,:=Ki,:w^\top = (B H^\top A^{-1})_{i,:} = K_{i,:} because AA and BB are symmetric. Line L7 is row ii of xb+Kdx^b + K d and line L8 is Bii−(KHB)iiB_{ii} - (K H B)_{ii}.

For the second form, (B−1+H⊤R−1H)BH⊤=H⊤+H⊤R−1HBH⊤=H⊤R−1(R+HBH⊤)=H⊤R−1A(B^{-1} + H^\top R^{-1} H) B H^\top = H^\top + H^\top R^{-1} H B H^\top = H^\top R^{-1}(R + H B H^\top) = H^\top R^{-1} A. Multiply by PP on the left and by A−1A^{-1} on the right: K=PH⊤R−1K = P H^\top R^{-1}. Then P−1(I−KH)B=P−1B−H⊤R−1HB=IP^{-1}(I - K H) B = P^{-1} B - H^\top R^{-1} H B = I, so (I−KH)B=P(I - KH)B = P. Finally xa=xb+PH⊤R−1(yo−Hxb)x^a = x^b + P H^\top R^{-1}(y^o - H x^b), and P−1xb−H⊤R−1Hxb=B−1xbP^{-1}x^b - H^\top R^{-1} H x^b = B^{-1} x^b gives the stated form. □\square

The second form is the minimizer of the 3D-Var cost J(x)=12(x−xb)⊤B−1(x−xb)+12(yo−Hx)⊤R−1(yo−Hx)J(x) = \tfrac12 (x - x^b)^\top B^{-1}(x - x^b) + \tfrac12 (y^o - Hx)^\top R^{-1}(y^o - Hx), whose gradient B−1(x−xb)−H⊤R−1(yo−Hx)B^{-1}(x - x^b) - H^\top R^{-1}(y^o - Hx) is zero exactly there. So global OI, the Kalman update and 3D-Var give the same analysis for a linear HH. If the errors are also Gaussian, xax^a is the mean of the posterior distribution of xtx^t and PaP^a is its covariance.

Summary. The algorithm stops after nn 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 xb+Kdx^b + K d and the diagonal of (I−KH)B(I - KH)B. ■\blacksquare

Complexity

With ss observations selected for a grid value, line L6 costs Θ(s3)\Theta(s^3), so the loop costs Θ(ns3)\Theta(n s^3) when the covariance entries of lines L4 and L5 come from a formula in Θ(1)\Theta(1) time each and HH touches a bounded number of grid values per observation. Sharing one selection over a box of bb grid values divides the factorization cost by about bb. The extra space is Θ(s2)\Theta(s^2) for ASA_S. For comparison, the global solve with all pp observations costs Θ(p3)\Theta(p^3) with a direct method. The reference code forms HBHB and HBH⊤HBH^\top as dense matrices for clarity, which costs Θ(pn2+p2n)\Theta(p n^2 + p^2 n) in addition.

Properties

  • Linear in the data. xax^a is an affine function of xbx^b and yoy^o, and the weights do not depend on the values of the data, only on BB, RR, HH and the selection.
  • Optimal only for the model of the errors. The variance of line L8 is the true error variance only if BB and RR 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 R→0R \to 0 with observations at grid points and global selection, the analysis matches the observations and interpolates between them with the shape of BB.
  • Fixed covariances. BB 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 HH 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 BB 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 Az=dA z = d once, for example with the conjugate gradient method, and set xa=xb+BH⊤zx^a = x^b + B H^\top z. 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 HH this gives the same analysis, and it also accepts a nonlinear HH (see 3D-Var).
  • Flow dependent weights. Replace the fixed BB 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 HH 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 HH, 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 d=Hxb−yod = H x^b - y^o moves the analysis away from the observations. A test with one observation and B=RB = R 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, cc must be (HB)k,i(HB)_{k,i}, the covariance between the background interpolated to the observation and the value at ii. Using BB at the nearest grid point gives the wrong weights.
  • Correlated observation errors (line L4). Taking RR 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 RR fixes this.
  • Trusting the variance (line L8). The variance only reflects the model of BB and RR. 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.

optimal_interpolation.pyI0RawGitHub
# 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

  1. L. S. Gandin, Objective Analysis of Meteorological Fields, 1963 (English translation 1965), optimal interpolation of meteorological fields with statistical structure functions
  2. 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
  3. 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)
  4. Roger Daley, Atmospheric Data Analysis, Cambridge University Press, 1991, the chapters on statistical interpolation
  5. 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.

LadderLevelWhat the next level needs
Human proofH1 sketch
  • a full proof of time.worst
  • a full proof of space.extra
LeanL0 no Lean part
  • name a Lean module in the lean field (07)
Code (python)I0 not checked yet
  • the tests did not run in this build
VisualV0 none
  • add viz/scene.ts or a figure (10)
WritingW2 basic
  • a scene preset for the example