Algorithmadvanced
Representer method
Solves weak-constraint variational assimilation exactly in the span of representer functions, one per observation, from adjoint and forward runs.
- Time
- Θ(p K (c + n^2) + p^2 n + p^3) worst
- Space
- Θ(K n + p n + p^2) extra
- Where
- K = the number of model steps in the window; c = the cost of one model or adjoint step; n = the state dimension; p = the number of scalar observations
- Model
- Real RAM
- Properties
- deterministicexact for linear model
- Evidence
- Proof sketchCode in 1 languages
- Origin
- Andrew F. Bennett, Peter C. McIntosh, 1982
The representer method solves the linear weak-constraint 4D-Var problem in observation space. For every scalar observation it computes a representer: the change of the whole trajectory over the window that one unit of influence from that observation causes, found by one run of the adjoint model backward and one forward run of the model forced by the background and model error covariances. The answer is the first guess plus a combination of the representers, and the coefficients solve one symmetric positive definite system , where holds the representers at the observation points and is the innovation. The method replaces a minimization over unknowns by a linear system of size , and for a linear model the result is exact: it is the mean of the Kalman smoother with model error.
In plain words
Each measurement can only change the estimate in one fixed pattern over space and time. The pattern spreads out from the place and time of the measurement, forward along the model and also backward, and its shape comes from what is known about the errors of the start state and of the model. This pattern is the representer. The method computes the pattern of each measurement once. Then the best estimate is the first guess plus a weighted sum of these patterns, and the weights come from a small system of equations with one unknown per measurement. Few measurements and a large model make the method cheap.
The problem
Input. A linear model on the time levels with its adjoint, a background with error covariance , model error covariances , and scalar observations with error covariance . Notation of Ide, Courtier, Ghil and Lorenc (1997).
Output. The trajectory of the minimizer of the weak-constraint cost
The algorithm
REPRESENTER-METHOD(x^b, B, {Q_k}, {h_i, k_i, y_i}, R, M, M^T)- 1
x^f_0 <- x^b ; x^f_k <- M_k x^f_(k-1) ▷ first guess, no model error - 2
for i <- 1 to p do - 3
lambda <- adjoint run backward, forced by h_i at time k_i - 4
r_i(0) <- B lambda_0 ; r_i(k) <- M_k r_i(k-1) + Q_k lambda_k - 5
P_ji <- h_j^T r_i(k_j) for j = 1..p - 6
d_i <- y_i - h_i^T x^f_(k_i) for i = 1..p ▷ innovations - 7
beta <- solve (P + R) beta = d - 8
lambda <- adjoint run backward, forced by beta_i h_i at times k_i - 9
x_0 <- x^b + B lambda_0 ; x_k <- M_k x_(k-1) + Q_k lambda_k - 10
return x_0, ..., x_K
The representer of line L4 is the prior covariance of the trajectory with the observed quantity , so is the prior covariance of the observed quantities. Lines L8 and L9 form with one more pair of sweeps, without storing the representers. The adjoint variable of line L8 is the same as in the Euler-Lagrange equations of : the analysis increment of the initial state is and the estimated model error is .
Example
One step. Take , , and one observation of . The adjoint run gives , and the forward run gives and . So , and , and the estimate is , the same as the result of weak-constraint 4D-Var on that page.
Two observations. Take the scalar model with , , , , and the observations at time 1 and at time 2, each with error variance . The first guess is and the innovations are . The representers are
| (observation at time 1) | |||
| (observation at time 2) |
so
The estimate is . The second coefficient is negative: the first observation alone would pull above 1, and the second observation pulls it back. The reference code gives these values exactly in rational arithmetic.
Correctness
The proof shows by direct expansion of the sweeps that under the prior, so , and that the estimate is , the Gaussian conditional mean, which is also the minimizer of (a theorem). The tests check the estimate and with exact rational arithmetic against a direct conditioning of the stacked trajectory, in floating point against a Kalman filter and smoother with model error to , and they count the model and adjoint runs.
Proof: The representer expansion gives the exact minimizer of the linear weak-constraint costfull
Setting. The window has the time levels , and the model is linear, . Write for , with , and , for . There are scalar observations , with , and , and all are symmetric positive definite. The cost is
where . Give the control the prior and , all independent. Then , so
is the first guess of line L1.
Lemma 1 (a representer is a covariance). Lines L3 and L4 for observation compute for every .
Proof. The backward sweep of line L3 starts from zero, adds at time and applies from time to time . So for and for . The forward sweep of line L4 starts from and sets , so . Only the terms with are not zero, which gives .
Corollary 2. Line L5 gives , so . It is symmetric positive semidefinite, and is positive definite, so line L7 has a unique solution.
Lemma 3 (the combined sweep). Lines L8 and L9 compute .
Proof. The backward sweep is linear in the forcing, so the forcing at the times gives . The forward sweep from is the forward sweep from plus the model run from , which is , and the forward sweep from is linear in , which gives .
Theorem 4. The trajectory returned by line L10 is the trajectory of the unique minimizer of , and for every .
Proof. The map from the control to the trajectory is linear and invertible, and the prior density of times the likelihood of is proportional to . is a strictly convex quadratic, so the posterior of is Gaussian, its mean is the unique minimizer of , and the trajectory of the minimizer is . For jointly Gaussian and , with independent of ,
Here , so of line L6; by Corollary 2; and column of is by Lemma 1. So with , which is by Lemma 3.
Remark (the Euler-Lagrange form). At the minimizer, , and , where is the adjoint of the weighted residuals. This is the form in which Bennett (2002) derives the method, and it follows from Theorem 4: .
Termination. The algorithm runs backward sweeps and forward sweeps of steps, plus the first guess, and one dense solve of size . It always stops.
Summary. Each representer is the prior covariance of the trajectory with one observed quantity, the representer matrix is the prior covariance of the observations, and the representer expansion with the coefficients from is the Gaussian conditional mean, which is the minimizer of the weak-constraint cost. The tests check this with exact rational arithmetic against a direct conditioning of the stacked trajectory, and in floating point against a Kalman filter and smoother with model error.
Complexity
Each representer costs one adjoint run and one forward run, with dense , and filling column of costs . With the dense solve of size and the final pair of sweeps the time is . The memory is one trajectory, the observation vectors and , . So the cost grows with the number of observations, not with the number of unknowns of the primal problem: the method suits a large model with few observations, and is too expensive for the millions of observations of weather prediction unless the system is solved by iterations (see the variants).
Properties
- Exact for linear models. The result is the minimizer of the weak-constraint cost and the Kalman smoother mean with model error (a theorem).
- Dual form. The unknowns are the coefficients in observation space. Strong-constraint 4D-Var has the same dual with , and the optimal interpolation formula is the case .
- A covariance in each column. The representers are prior covariances of the trajectory with the observed quantities, so they show which parts of the window and of the state each observation can correct.
- Statistics for free. is the covariance of the innovations, so has a distribution with degrees of freedom when the error statistics are right, a test of , and (a theorem for Gaussian errors).
- Linear only. For a nonlinear model the method applies to the linearized problem inside outer loops, as in incremental 4D-Var.
Variants and improvements
- Iterative (indirect) solution. Do not form . Solve by the conjugate gradient method, where each product costs one adjoint run forced by and one forward run. The cost is then one pair of runs per iteration instead of one per observation (Bennett 2002).
- Outer loops for nonlinear models. Linearize the model around the current estimate, solve the linear problem with representers, and repeat.
- Strong constraint. With the same algorithm gives the strong-constraint 4D-Var solution in its dual form, which is the physical space form used in some weather systems.
- Representer analysis of an observing network. The eigenvectors of show which combinations of the observations the prior can resolve, a tool for the design of observing systems.
When to use it
Use the representer method for a linear or linearized model when the number of observations is much smaller than the number of unknowns of the weak-constraint problem, as in ocean tide and circulation problems with sparse data, and when the representers themselves are of interest. With many observations, use the iterative form, or solve the primal problem with weak-constraint 4D-Var.
Pitfalls
- An adjoint that is not the transpose (lines L3 and L8). Then is not symmetric and is not a covariance, and the estimate is wrong. Check the adjoint with the dot product test.
- The forward run without model error (line L4). Dropping gives the strong-constraint representers, not the weak-constraint ones.
- Forming when is large (line L5). The cost of pairs of runs and the solve both grow fast; use the iterative form.
- An ill-conditioned (line L7). With small observation errors and nearly redundant observations the system is close to singular, and the solve loses accuracy.
- Two separate first guesses. The innovation of line L6 must come from the same first guess that line L9 starts from, the model run from without model error.
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/representer-method/. The authors are listed in prov/6YYQY7.jsonl.
"""The representer method for weak-constraint variational assimilation.
Notation of Ide, Courtier, Ghil and Lorenc (1997). The window has the time
levels 0..K, the model is linear with model error, x_k = M_k x_(k-1) + eta_k,
and the cost is
J = 1/2 (x_0 - x^b)^T B^-1 (x_0 - x^b) + sum_k 1/2 eta_k^T Q_k^-1 eta_k
+ 1/2 (y - H x)^T R^-1 (y - H x),
where y stacks all the scalar observations y_i = h_i^T x_(k_i) + e_i and R
is their error covariance. The minimizer is the first guess (the model run
from x^b with no model error) plus a combination sum_i beta_i r_i of the
representers r_i, one per observation. The representer r_i is found by one
adjoint run forced by h_i at time k_i and one forward run forced by B and
Q_k times the adjoint variable. The coefficients solve (P + R) beta = d,
with P_ji = h_j^T r_i(k_j) and d the innovation of the first guess.
The model is given by two functions:
step(k, x) M_k x, for x = x_(k-1)
adjoint(k, lam) M_k^T lam
B, Q[k] (k = 1..K, Q[0] is not used), the observation operators and the data
may hold Fraction entries; then every result is exact.
"""
import scimat
def observation_list(obs):
"""Return [(k_i, h_i, y_i)] for obs = {k: (H_k, y_k, R_k)} and the block diagonal R."""
items = []
blocks = []
for k in sorted(obs):
H, y, R = obs[k]
for row, value in zip(H, y):
items.append((k, row, value))
blocks.append(R)
p = len(items)
Rall = scimat.zeros(p)
i = 0
for R in blocks:
for a in range(len(R)):
for b in range(len(R)):
Rall[i + a][i + b] = R[a][b]
i += len(R)
return items, Rall
def backward(forcing, adjoint, K, n):
"""Return [lam_0, ..., lam_K] with lam_k = M_(k+1)^T lam_(k+1) + forcing at time k."""
lam = [None] * (K + 1)
v = [0] * n
for k in range(K, -1, -1):
if k in forcing:
v = scimat.add(v, forcing[k])
lam[k] = v
if k > 0:
v = adjoint(k, v)
return lam
def forward(start, lam, B, Q, step, K):
"""Return [x_0, ..., x_K] with x_0 = start + B lam_0 and x_k = M_k x_(k-1) + Q_k lam_k."""
xs = [scimat.add(start, scimat.matvec(B, lam[0]))]
for k in range(1, K + 1):
xs.append(scimat.add(step(k, xs[-1]), scimat.matvec(Q[k], lam[k])))
return xs
def representer_method(xb, B, Q, obs, step, adjoint, K):
"""Return (estimate [x_0, ..., x_K], beta, representer matrix P)."""
n = len(xb)
items, R = observation_list(obs)
p = len(items)
zero = [0] * n
first = [list(xb)] # @line L1
for k in range(1, K + 1):
first.append(step(k, first[-1]))
P = scimat.zeros(p)
for i, (ki, hi, _) in enumerate(items): # @line L2
lam = backward({ki: list(hi)}, adjoint, K, n) # @line L3
r = forward(zero, lam, B, Q, step, K) # @line L4
for j, (kj, hj, _) in enumerate(items): # @line L5
P[j][i] = scimat.dot(hj, r[kj])
d = [yi - scimat.dot(hi, first[ki]) for ki, hi, yi in items] # @line L6
beta = scimat.solve(scimat.add(P, R), d) # @line L7
forcing = {}
for (ki, hi, _), bi in zip(items, beta): # @line L8
forcing[ki] = scimat.add(forcing.get(ki, zero), scimat.scale(bi, hi))
lam = backward(forcing, adjoint, K, n)
estimate = forward(list(xb), lam, B, Q, step, K) # @line L9
return estimate, beta, P # @line L10
def linear_model(M):
"""Return (step, adjoint) for the linear model x_k = M x_(k-1)."""
Mt = scimat.transpose(M)
return (lambda k, x: scimat.matvec(M, x), lambda k, lam: scimat.matvec(Mt, lam))
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_representer_method.py 190 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/representer-method/. The authors are listed in prov/6YYQY7.jsonl.
import random
from fractions import Fraction
import scimat
from representer_method import linear_model, representer_method
def random_spd(rng, n, shift=0.5):
L = [[rng.uniform(-1, 1) for _ in range(n)] for _ in range(n)]
S = scimat.matmul(L, scimat.transpose(L))
for i in range(n):
S[i][i] += shift
return S
def frac(rng, lo=-3, hi=3, 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 kalman_and_rts(xb, B, M, Q, obs, K):
"""Oracle: Kalman filter and Rauch-Tung-Striebel smoother means with model error Q[k]."""
Mt = scimat.transpose(M)
xf, Pf, xa, Pa = [], [], [], []
x, P = list(xb), B
for k in range(K + 1):
if k > 0:
x = scimat.matvec(M, xa[-1])
P = scimat.add(scimat.matmul(scimat.matmul(M, Pa[-1]), Mt), Q[k])
xf.append(x)
Pf.append(P)
if k in obs:
H, y, R = obs[k]
S = scimat.add(scimat.matmul(scimat.matmul(H, P), scimat.transpose(H)), R)
G = scimat.transpose(scimat.solve(S, scimat.matmul(H, P)))
x = scimat.add(x, scimat.matvec(G, scimat.sub(y, scimat.matvec(H, x))))
P = scimat.sub(P, scimat.matmul(G, scimat.matmul(H, P)))
xa.append(x)
Pa.append(P)
xs = [None] * (K + 1)
xs[K] = xa[K]
for k in range(K - 1, -1, -1):
C = scimat.transpose(scimat.solve(Pf[k + 1], scimat.matmul(M, Pa[k])))
xs[k] = scimat.add(xa[k], scimat.matvec(C, scimat.sub(xs[k + 1], xf[k + 1])))
return xa, xs
def gaussian_conditioning(xb, B, M, Q, obs, K):
"""Brute force: condition the stacked trajectory on all observations at once.
Return (E[x | y] as a list of states, prior covariance of the stacked observations).
"""
n = len(xb)
N = n * (K + 1)
# T maps z = (x_0, eta_1, ..., eta_K) to the stacked trajectory.
T = scimat.zeros(N)
powers = [scimat.eye(n)]
for _ in range(K):
powers.append(scimat.matmul(M, powers[-1]))
for k in range(K + 1):
for j in range(k + 1):
blk = powers[k - j]
for a in range(n):
for b in range(n):
T[k * n + a][j * n + b] = blk[a][b]
C = scimat.zeros(N)
for j in range(K + 1):
cov = B if j == 0 else Q[j]
for a in range(n):
for b in range(n):
C[j * n + a][j * n + b] = cov[a][b]
mean_z = list(xb) + [0] * (n * K)
mean = scimat.matvec(T, mean_z)
cov = scimat.matmul(scimat.matmul(T, C), scimat.transpose(T))
rows, y, blocks = [], [], []
for k in sorted(obs):
H, yk, R = obs[k]
for row, v in zip(H, yk):
full = [0] * N
for a in range(n):
full[k * n + a] = row[a]
rows.append(full)
y.append(v)
blocks.append(R)
p = len(rows)
Rall = scimat.zeros(p)
i = 0
for R in blocks:
for a in range(len(R)):
for b in range(len(R)):
Rall[i + a][i + b] = R[a][b]
i += len(R)
Hs = rows
HC = scimat.matmul(Hs, cov)
S = scimat.matmul(HC, scimat.transpose(Hs))
gain_t = scimat.solve(scimat.add(S, Rall), HC)
post = scimat.add(mean, scimat.matvec(scimat.transpose(gain_t), scimat.sub(y, scimat.matvec(Hs, mean))))
return [post[k * n : (k + 1) * n] for k in range(K + 1)], S
def close(a, b, tol):
return all(abs(u - v) <= tol * (1 + abs(v)) for u, v in zip(a, b))
def test_scalar_check_value():
step, adj = linear_model([[1]])
est, beta, P = representer_method([0], [[1]], [None], {0: ([[1]], [1], [[1]])}, step, adj, 0)
assert est[0][0] == Fraction(1, 2) and P == [[1]]
def test_page_example():
# x_1 = x_0 + eta_1, x^b = 0, B = Q = R = 1, y_1 = 3: r = (1, 2), P = 2, beta = 1, estimate (1, 2).
step, adj = linear_model([[1]])
est, beta, P = representer_method([0], [[1]], [None, [[1]]], {1: ([[1]], [3], [[1]])}, step, adj, 1)
assert P == [[2]] and beta == [1] and est == [[1], [2]]
def test_exact_against_gaussian_conditioning():
rng = random.Random(71)
for _ in range(12):
n = rng.randint(1, 3)
K = rng.randint(0, 3)
M = [[frac(rng, -1, 1) + (1 if i == j else 0) for j in range(n)] for i in range(n)]
B = frac_spd(rng, n)
Q = [None] + [frac_spd(rng, n) for _ in range(K)]
xb = [frac(rng) for _ in range(n)]
obs = {}
for k in range(K + 1):
if rng.random() < 0.7 or k == K:
p = rng.randint(1, 2)
obs[k] = ([[frac(rng, -1, 1) for _ in range(n)] for _ in range(p)], [frac(rng) for _ in range(p)], frac_spd(rng, p))
step, adj = linear_model(M)
est, beta, P = representer_method(xb, B, Q, obs, step, adj, K)
ref, S = gaussian_conditioning(xb, B, M, Q, obs, K)
assert est == ref
assert P == S # the representer matrix is the prior covariance of the observations
def test_equals_kalman_smoother_with_q():
rng = random.Random(72)
for _ in range(30):
n = rng.randint(1, 3)
K = rng.randint(1, 6)
M = [[(1.0 if i == j else 0.0) + 0.3 * rng.uniform(-1, 1) for j in range(n)] for i in range(n)]
B = random_spd(rng, n)
Q = [None] + [random_spd(rng, n, 0.2) for _ in range(K)]
xb = [rng.uniform(-2, 2) for _ in range(n)]
obs = {}
for k in range(K + 1):
if rng.random() < 0.6 or k == K:
p = rng.randint(1, 3)
obs[k] = ([[rng.uniform(-1, 1) for _ in range(n)] for _ in range(p)], [rng.uniform(-2, 2) for _ in range(p)], random_spd(rng, p))
step, adj = linear_model(M)
est, _, _ = representer_method(xb, B, Q, obs, step, adj, K)
xa, xs = kalman_and_rts(xb, B, M, Q, obs, K)
for k in range(K + 1):
assert close(est[k], xs[k], 1e-9)
def test_one_adjoint_and_one_forward_run_per_observation():
rng = random.Random(73)
n, K = 2, 5
M = [[1.0, 0.1], [-0.1, 1.0]]
step0, adj0 = linear_model(M)
calls = {"step": 0, "adjoint": 0}
def step(k, x):
calls["step"] += 1
return step0(k, x)
def adj(k, lam):
calls["adjoint"] += 1
return adj0(k, lam)
obs = {1: ([[1.0, 0.0]], [0.5], [[0.1]]), 3: ([[0.0, 1.0], [1.0, 1.0]], [0.2, -0.4], [[0.1, 0.0], [0.0, 0.2]]), 5: ([[1.0, -1.0]], [1.0], [[0.3]])}
p = 4
Q = [None] + [[[0.05, 0.0], [0.0, 0.05]] for _ in range(K)]
representer_method([rng.uniform(-1, 1) for _ in range(n)], [[1.0, 0.0], [0.0, 1.0]], Q, obs, step, adj, K)
assert calls["adjoint"] == (p + 1) * K
assert calls["step"] == (p + 2) * K
History
Bennett and McIntosh used representers in 1982 to solve a variational inverse problem for open ocean tides, in which the tidal equations hold only as weak constraints. Bennett developed the method into a general tool for ocean inverse problems in his books of 1992 and 2002, with the iterative form that avoids the computation of all representers. Egbert, Bennett and Foreman (1994) applied it to estimate global ocean tides from TOPEX/POSEIDON altimeter data.
References
- Andrew F. Bennett, Inverse Modeling of the Ocean and Atmosphere, Cambridge University Press, 2002, the representer solution of the weak-constraint problem and its indirect solution by iterations
- Andrew F. Bennett, Inverse Methods in Physical Oceanography, Cambridge University Press, 1992, the generalized inverse of a linear model and its representer expansion
- A. F. Bennett and P. C. McIntosh, Open ocean modeling as an inverse problem, tidal theory, Journal of Physical Oceanography 12(10) (1982) 1004-1018, the variational tidal inverse problem
- G. D. Egbert, A. F. Bennett and M. G. G. Foreman, TOPEX/POSEIDON tides estimated using a global inverse model, Journal of Geophysical Research 99(C12) (1994) 24821-24852, a global tidal inverse solution with representers and altimeter data
- 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.
| 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 6YYQY7 Edit this page History Report an error Markdown