Algorithm Search⌘K

Techniqueadvanced

Desroziers diagnostics

Estimates observation and background error covariances from statistics of innovations and analysis residuals in observation space.

Desroziers diagnostics estimate the error covariances of an assimilation system from the output of the system itself. From many analyses, collect three vectors in observation space: the innovation dbo=y−Hxbd^o_b = y - Hx^b, the analysis increment dba=Hxa−Hxbd^a_b = Hx^a - Hx^b, and the analysis residual dao=y−Hxad^o_a = y - Hx^a. If the analysis uses the right error covariances, the sample means of their products estimate the observation error covariance RR, the background error covariance in observation space HBH⊤HBH^\top, and the analysis error covariance HAH⊤HAH^\top (Desroziers, Berre, Chapnik and Poli 2005). If the assumed covariances are wrong, the estimates differ from the assumed ones, which is a test of consistency, and they can be fed back into the analysis to tune it. The tuning converges to the truth only under conditions that must be checked: a wrong background error covariance gives a wrong RR (Ménard 2016).

In plain words

An assimilation system needs to know how large the errors of the measurements and of the forecast are, but nobody can measure these errors directly, because the true state is not known. This method finds them from numbers that the system already produces. For each measurement it compares three things: the measurement, the forecast and the final analysis. It then averages products of their differences over many cases. If the error sizes that the system assumes are right, these averages give back the measurement errors and the forecast errors. If they are wrong, the averages show it, and the system can correct its assumptions and try again.

When it applies

  • A linear or nearly linear analysis xa=xb+K(y−Hxb)x^a = x^b + K(y - Hx^b) with the gain K~=B~H⊤(HB~H⊤+R~)−1\tilde K = \tilde B H^\top (H\tilde BH^\top + \tilde R)^{-1} of assumed covariances B~\tilde B and R~\tilde R, as in optimal interpolation, 3D-Var, 4D-Var or an ensemble Kalman filter.
  • Many analyses are available, over time or over a set of similar observations, so that sample means converge. The errors must be statistically the same over the sample.
  • Background and observation errors are not correlated with each other, and both have mean zero.
  • The quantities of interest are in observation space: variances of a channel of a satellite instrument, inter-channel correlations, or correlations between nearby observations.

The template

Let S=HBH⊤+RS = HBH^\top + R be the true covariance of the innovation, S~=HB~H⊤+R~\tilde S = H\tilde BH^\top + \tilde R the one the analysis assumes, and G=HB~H⊤S~−1G = H\tilde BH^\top \tilde S^{-1}, so dba=Gdbod^a_b = Gd^o_b and dao=(I−G)dbo=R~S~−1dbod^o_a = (I - G)d^o_b = \tilde R\tilde S^{-1}d^o_b. Then, exactly,

E[daodbo⊤]=R~S~−1S,E[dbadbo⊤]=HB~H⊤S~−1S,E[dbadao⊤]=HB~H⊤S~−1SS~−1R~,E[dbodbo⊤]=S.E[d^o_a d^{o\top}_b] = \tilde R\tilde S^{-1}S, \qquad E[d^a_b d^{o\top}_b] = H\tilde BH^\top \tilde S^{-1}S, \qquad E[d^a_b d^{o\top}_a] = H\tilde BH^\top \tilde S^{-1}S\tilde S^{-1}\tilde R, \qquad E[d^o_b d^{o\top}_b] = S .

If B~=B\tilde B = B and R~=R\tilde R = R, then S~=S\tilde S = S and the four right sides are RR, HBH⊤HBH^\top, HAH⊤HAH^\top and HBH⊤+RHBH^\top + R, where A=(I−KH)BA = (I - KH)B is the analysis error covariance; the third one follows from HAH⊤=HBH⊤−HBH⊤S−1HBH⊤=HBH⊤S−1RHAH^\top = HBH^\top - HBH^\top S^{-1}HBH^\top = HBH^\top S^{-1}R.

  1. DESROZIERS({d^o_b}, H B~ H^T, R~)
  2. 1G <- H B~ H^T (H B~ H^T + R~)^-1
  3. 2for each analysis t do
  4. 3d^a_b <- G d^o_b ▷ in a real system: H x^a - H x^b
  5. 4d^o_a <- d^o_b - d^a_b ▷ y - H x^a
  6. 5add d^o_a d^o_b^T, d^a_b d^o_b^T, d^a_b d^o_a^T, d^o_b d^o_b^T to the sums
  7. 6divide the sums by the number of analyses
  8. 7return the estimates of R, H B H^T, H A H^T and H B H^T + R

The holes are the analysis that gives xax^a (line L3), the set of analyses over which the means are taken (line L2), and the use of the estimates. In an operational system dbad^a_b and daod^o_a come directly from the analysis and line L1 is not needed. The reference code forms GG to simulate a linear analysis, and also gives the expected values above and the iteration below in exact rational arithmetic.

Consistency check and tuning. Compare each estimate with the assumed covariance. A mismatch shows that B~\tilde B or R~\tilde R is wrong. Tuning replaces R~\tilde R by the symmetric part of the estimate of E[daodbo⊤]E[d^o_a d^{o\top}_b] and runs the analyses again. In expectation this is the fixed point iteration R~j+1=R~jS~j−1S\tilde R_{j+1} = \tilde R_j \tilde S_j^{-1}S.

Worked example. Take one scalar observation with HBH⊤=R=1HBH^\top = R = 1, so S=2S = 2, and an analysis that uses the right HBH⊤HBH^\top but R~0=2\tilde R_0 = 2. Then E[daodbo]=R~0S/S~0=2⋅2/3=4/3E[d^o_a d^o_b] = \tilde R_0 S/\tilde S_0 = 2 \cdot 2/3 = 4/3: smaller than the assumed 2, so the diagnostic says that RR is overestimated. The iteration gives R~=2,4/3,8/7,16/15,…\tilde R = 2, 4/3, 8/7, 16/15, \ldots, that is R~j=2j+1/(2j+1−1)\tilde R_j = 2^{j+1}/(2^{j+1} - 1), which tends to the true value 1, with the error halved at each step. In general, with the right HBH⊤HBH^\top, the scalar map R~↦R~S/(HBH⊤+R~)\tilde R \mapsto \tilde R S/(HBH^\top + \tilde R) has the derivative HBH⊤/SHBH^\top/S at the fixed point RR, so the iteration converges slowly when the background is much less accurate than the observations.

A wrong background. If the analysis assumes HB~H⊤=3/2H\tilde BH^\top = 3/2 instead of 1, the same iteration converges to R~=S−3/2=1/2\tilde R = S - 3/2 = 1/2, not to 1: the iteration only makes the total S~\tilde S match SS. If both R~\tilde R and HB~H⊤H\tilde BH^\top are updated, one step makes S~=S\tilde S = S and keeps the ratio of the first guesses, so the gain does not change and the split between BB and RR is never learned. This agrees with the results of Ménard (2016). The tests check both cases exactly.

A twin measurement. With four observations of a three-variable state, correlated BB and an RR with one correlated pair, 10000 simulated analyses with the right covariances give the estimates of RR to within 0.008 and of HBH⊤HBH^\top to within 0.016 of the truth in every entry (a measurement). With R~=2R\tilde R = 2R the estimate of RR has the diagonal (0.68,0.68,0.74,0.40)(0.68, 0.68, 0.74, 0.40) instead of the true (0.5,0.5,0.5,0.3)(0.5, 0.5, 0.5, 0.3), as the formula R~S~−1S\tilde R\tilde S^{-1}S predicts, and three steps of the iteration bring it to (0.58,0.57,0.58,0.36)(0.58, 0.57, 0.58, 0.36).

Classic examples

  • Satellite radiance errors. Estimates of the error variances and the inter-channel correlations of satellite instruments, which then enter RR in operational systems.
  • Consistency of a 3D-Var or 4D-Var system. The ratio of the estimated to the assumed variances, for each observation type, shows which part of BB or RR is too large or too small.
  • Ensemble systems. In an ensemble Kalman filter the same relations give a check of the ensemble spread, and they underlie some adaptive covariance inflation schemes.
  • The innovation method. The older method of Hollingsworth and Lönnberg (1986) splits the covariance of innovations at pairs of stations, as a function of distance, into a correlated background part and an uncorrelated observation part. Desroziers diagnostics need no such assumption on the spatial structure.

Variations

  • Scalar tuning factors. Estimate only one factor for the variances of each observation type, from the trace of the estimates. This needs fewer samples and is more robust than full matrices.
  • Iterated tuning. Apply the estimates, run the analyses again and repeat. The iteration converges to the truth for RR when BB is right (a theorem in the scalar case shown above), and Ménard (2016) gives the conditions for observation networks.
  • Estimates of correlations. The off-diagonal entries of the estimate of RR give observation error correlations, for example between channels or between nearby observations.
  • Chi-squared checks. The trace relations E[dbo⊤S−1dbo]=pE[d^{o\top}_b S^{-1}d^o_b] = p and their variational forms, such as the expected minimum of the cost, give single number checks of the whole system.

Pitfalls

  • The diagnostic is not an estimate when the statistics are wrong. With a wrong B~\tilde B or R~\tilde R, the first estimate is R~S~−1S\tilde R\tilde S^{-1}S, not RR (line L5). Only the fixed point of the iteration, and only with the right BB, is the truth.
  • Two unknowns from one equation. Tuning BB and RR together keeps the gain fixed and cannot find the right split; extra assumptions, such as a known spatial structure of one of them, are needed.
  • The sample must be homogeneous. Means over observations with different error statistics, or over weather situations with very different background errors, mix them.
  • Correlated errors. If background and observation errors are correlated, as for observations used to make the background, the relations do not hold.
  • The estimate of RR is not symmetric. The sample mean of daodbo⊤d^o_a d^{o\top}_b is not exactly symmetric; take its symmetric part before use, and check that it is positive definite.
  • Nonlinear and quality controlled analyses. The relations assume a linear analysis with the optimal gain of the assumed statistics. Variational quality control, nonlinear observation operators and thinning change them.

Code

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.

desroziers_diagnostics.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/desroziers-diagnostics/. The authors are listed in prov/YFJDYK.jsonl.

"""Desroziers diagnostics of the observation and background error covariances.

Notation of Ide, Courtier, Ghil and Lorenc (1997). Everything is in
observation space. For one analysis, with the background x^b, the analysis
x^a and the observations y:

    d^o_b = y - H x^b          innovation (observation minus background)
    d^a_b = H x^a - H x^b      analysis increment in observation space
    d^o_a = y - H x^a          analysis residual (observation minus analysis)

A linear analysis with the assumed covariances Bt (written here as its
observation space form HBtH^T) and Rt has d^a_b = HBtH^T St^-1 d^o_b, with
St = HBtH^T + Rt. If the assumed covariances are the true ones, the sample
means over many analyses estimate

    E[d^o_a d^o_b^T] = R,           E[d^a_b d^o_b^T] = H B H^T,
    E[d^a_b d^o_a^T] = H A H^T,     E[d^o_b d^o_b^T] = H B H^T + R.

For assumed covariances that are not the true ones, the expected values are
given by expected_statistics. All the routines keep Fraction entries exact.
"""

from fractions import Fraction

import scimat


def gain_in_observation_space(hbht, r):
    """Return G = HBH^T (HBH^T + R)^-1, so that d^a_b = G d^o_b."""
    s = scimat.add(hbht, r)
    # G = HBH^T S^-1, and S and HBH^T are symmetric, so G^T = S^-1 HBH^T.
    return scimat.transpose(scimat.solve(s, hbht))


def desroziers(innovations, hbht, r):
    """Return the sample estimates (R, HBH^T, HAH^T, HBH^T + R) from the innovations.

    Each innovation d^o_b goes through the linear analysis with the assumed
    covariances hbht and r to give d^a_b and d^o_a.
    """
    p = len(r)
    g = gain_in_observation_space(hbht, r)  # @line L1
    sums = {key: scimat.zeros(p) for key in ("oa_ob", "ab_ob", "ab_oa", "ob_ob")}
    for d_ob in innovations:  # @line L2
        d_ab = scimat.matvec(g, d_ob)  # @line L3
        d_oa = scimat.sub(d_ob, d_ab)  # @line L4
        sums["oa_ob"] = scimat.add(sums["oa_ob"], scimat.outer(d_oa, d_ob))  # @line L5
        sums["ab_ob"] = scimat.add(sums["ab_ob"], scimat.outer(d_ab, d_ob))
        sums["ab_oa"] = scimat.add(sums["ab_oa"], scimat.outer(d_ab, d_oa))
        sums["ob_ob"] = scimat.add(sums["ob_ob"], scimat.outer(d_ob, d_ob))
    w = Fraction(1, len(innovations))  # a Fraction times a float is a float
    est = {key: scimat.scale(w, s) for key, s in sums.items()}  # @line L6
    return est["oa_ob"], est["ab_ob"], est["ab_oa"], est["ob_ob"]  # @line L7


def expected_statistics(hbht_true, r_true, hbht, r):
    """Return the exact expected values of the four sample estimates of desroziers.

    The innovations have the true covariance S = HBH^T + R, and the analysis
    uses the assumed hbht and r. With St = hbht + r:
        E[d^o_a d^o_b^T] = r St^-1 S
        E[d^a_b d^o_b^T] = hbht St^-1 S
        E[d^a_b d^o_a^T] = hbht St^-1 S St^-1 r
        E[d^o_b d^o_b^T] = S
    """
    s = scimat.add(hbht_true, r_true)
    st = scimat.add(hbht, r)
    st_inv_s = scimat.solve(st, s)
    oa_ob = scimat.matmul(r, st_inv_s)
    ab_ob = scimat.matmul(hbht, st_inv_s)
    ab_oa = scimat.matmul(ab_ob, scimat.solve(st, r))
    return oa_ob, ab_ob, ab_oa, s


def symmetric_part(a):
    """Return (a + a^T) / 2."""
    at = scimat.transpose(a)
    return [[(x + y) / 2 for x, y in zip(ra, rb)] for ra, rb in zip(a, at)]


def tune(hbht_true, r_true, hbht, r, steps, tune_b=False):
    """Iterate r <- E[d^o_a d^o_b^T] (and hbht <- E[d^a_b d^o_b^T] if tune_b) with exact expectations.

    Return the list of (hbht, r) pairs, starting with the given ones.
    """
    out = [(hbht, r)]
    for _ in range(steps):
        oa_ob, ab_ob, _, _ = expected_statistics(hbht_true, r_true, hbht, r)
        new_r = symmetric_part(oa_ob)
        if tune_b:
            hbht = symmetric_part(ab_ob)
        r = new_r
        out.append((hbht, r))
    return out
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_desroziers_diagnostics.py 108 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/desroziers-diagnostics/. The authors are listed in prov/YFJDYK.jsonl.

import random
from fractions import Fraction

import scimat
from desroziers_diagnostics import desroziers, expected_statistics, tune


def frac(rng, lo=-2, hi=2, den=4):
    return Fraction(rng.randint(lo * den, hi * den), den)


def frac_spd(rng, n):
    L = [[frac(rng, -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] += Fraction(1, 2)
    return S


def max_abs_diff(a, b):
    return max(abs(x - y) for ra, rb in zip(a, b) for x, y in zip(ra, rb))


def twin(rng, H, B, R, count):
    """Innovations d = H e_b + e_o with e_b ~ N(0, B) and e_o ~ N(0, R)."""
    LB, LR = scimat.cholesky(B), scimat.cholesky(R)
    n, p = len(B), len(R)
    out = []
    for _ in range(count):
        eb = scimat.matvec(LB, [rng.gauss(0, 1) for _ in range(n)])
        eo = scimat.matvec(LR, [rng.gauss(0, 1) for _ in range(p)])
        out.append(scimat.add(scimat.matvec(H, eb), eo))
    return out


H = [[1.0, 0.0, 0.0], [0.0, 1.0, 0.0], [0.0, 0.0, 1.0], [0.5, 0.5, 0.0]]
B = [[1.0, 0.5, 0.2], [0.5, 1.0, 0.5], [0.2, 0.5, 1.0]]
R = [[0.5, 0.0, 0.0, 0.0], [0.0, 0.5, 0.1, 0.0], [0.0, 0.1, 0.5, 0.0], [0.0, 0.0, 0.0, 0.3]]
HBHT = scimat.matmul(scimat.matmul(H, B), scimat.transpose(H))


def test_expected_values_are_exact_with_correct_statistics():
    rng = random.Random(81)
    for _ in range(20):
        n, p = rng.randint(1, 3), rng.randint(1, 4)
        Hm = [[frac(rng) for _ in range(n)] for _ in range(p)]
        Bm, Rm = frac_spd(rng, n), frac_spd(rng, p)
        hbht = scimat.matmul(scimat.matmul(Hm, Bm), scimat.transpose(Hm))
        oa_ob, ab_ob, ab_oa, ob_ob = expected_statistics(hbht, Rm, hbht, Rm)
        # Brute force: the analysis error covariance A = (I - K H) B with K = B H^T S^-1.
        S = scimat.add(hbht, Rm)
        K = scimat.transpose(scimat.solve(S, scimat.matmul(Hm, Bm)))
        A = scimat.sub(Bm, scimat.matmul(K, scimat.matmul(Hm, Bm)))
        hah = scimat.matmul(scimat.matmul(Hm, A), scimat.transpose(Hm))
        assert oa_ob == Rm and ab_ob == hbht and ab_oa == hah and ob_ob == S


def test_sample_estimates_recover_r_and_hbht():
    rng = random.Random(82)
    ds = twin(rng, H, B, R, 10000)
    r, hb, ha, s = desroziers(ds, HBHT, R)
    assert max_abs_diff(r, R) < 0.05
    assert max_abs_diff(hb, HBHT) < 0.05
    assert max_abs_diff(s, scimat.add(HBHT, R)) < 0.08
    _, _, hah, _ = expected_statistics(HBHT, R, HBHT, R)
    assert max_abs_diff(ha, hah) < 0.05


def test_sample_estimates_follow_the_formula_with_wrong_statistics():
    # The analysis uses R twice too large; the estimate converges to Rt St^-1 S, not to R.
    rng = random.Random(83)
    ds = twin(rng, H, B, R, 10000)
    r_wrong = scimat.scale(2.0, R)
    r_est, hb_est, _, _ = desroziers(ds, HBHT, r_wrong)
    oa_ob, ab_ob, _, _ = expected_statistics(HBHT, R, HBHT, r_wrong)
    assert max_abs_diff(r_est, oa_ob) < 0.05 and max_abs_diff(hb_est, ab_ob) < 0.05
    assert max_abs_diff(oa_ob, R) > 0.2


def test_scalar_iteration_with_correct_b():
    # HBH^T = R = 1 and the first guess of R is 2: R_j = 2^(j+1) / (2^(j+1) - 1).
    steps = tune([[1]], [[1]], [[1]], [[Fraction(2)]], 6)
    for j, (_, r) in enumerate(steps):
        assert r[0][0] == Fraction(2 ** (j + 1), 2 ** (j + 1) - 1)


def test_wrong_b_gives_a_wrong_r():
    # Tuning R alone with HBH^T assumed 3/2 instead of 1 converges to R = S - 3/2 = 1/2,
    # with the error multiplied by about 3/4 per step.
    steps = tune([[1]], [[1]], [[1.5]], [[1.0]], 150)
    assert abs(steps[-1][1][0][0] - 0.5) < 1e-12


def test_joint_tuning_keeps_the_ratio_of_the_first_guess():
    # Scalar case: one joint step makes HBH^T + R equal to S and keeps the ratio HBH^T : R.
    steps = tune([[1]], [[1]], [[Fraction(3)]], [[Fraction(1)]], 4, tune_b=True)
    for hb, r in steps[1:]:
        assert hb[0][0] + r[0][0] == 2 and hb[0][0] == 3 * r[0][0]


def test_matrix_iteration_converges_with_correct_b():
    hbht = [[2.0, 1.0], [1.0, 2.0]]
    r_true = [[1.0, 0.0], [0.0, 0.5]]
    steps = tune(hbht, r_true, hbht, [[3.0, 0.0], [0.0, 3.0]], 200)
    assert max_abs_diff(steps[-1][1], r_true) < 1e-9

Exercises

  1. Show that dao=R~S~−1dbod^o_a = \tilde R\tilde S^{-1}d^o_b for a linear analysis with the gain K~=B~H⊤S~−1\tilde K = \tilde BH^\top \tilde S^{-1}.
  2. In the scalar case with the right HBH⊤HBH^\top, show that the iteration R~j+1=R~jS/(HBH⊤+R~j)\tilde R_{j+1} = \tilde R_j S/(HBH^\top + \tilde R_j) has the closed form 1/R~j−1/R=(HBH⊤/S)j(1/R~0−1/R)1/\tilde R_j - 1/R = (HBH^\top/S)^j (1/\tilde R_0 - 1/R), and check it against 2,4/3,8/7,…2, 4/3, 8/7, \ldots.
  3. Show that updating both R~\tilde R and HB~H⊤H\tilde BH^\top in the scalar case keeps their ratio and so does not change the gain.

References

  1. G. Desroziers, L. Berre, B. Chapnik and P. Poli, Diagnosis of observation, background and analysis-error statistics in observation space, Quarterly Journal of the Royal Meteorological Society 131(613) (2005) 3385-3396, the four relations between residual statistics and error covariances, and their iterative use for tuning
  2. R. Ménard, Error covariance estimation methods based on analysis residuals, theoretical foundation and convergence properties derived from simplified observation networks, Quarterly Journal of the Royal Meteorological Society 142(694) (2016) 257-273, the convergence of the iteration, which needs a correct background error covariance, and the unchanged gain when both covariances are estimated
  3. A. Hollingsworth and P. Lönnberg, The statistical structure of short-range forecast errors as determined from radiosonde data. Part I, The wind field, Tellus A 38(2) (1986) 111-136, the split of innovation covariances into a spatially correlated background part and an uncorrelated observation part
  4. 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

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 proofH0 no proof
  • add a proof in proofs/ (06.5)
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)
WritingW3 standard
  • five exercises