Algorithm Search⌘K

Algorithmresearch

Four-dimensional ensemble-variational assimilation

Also called 4DEnVar.

Replaces the tangent linear and adjoint models of 4D-Var by ensemble trajectories over the window, so no adjoint code is needed.

Time
Θ(N K c + n^3 + p^3 + m (K N n^2 + p n)) worst
Space
Θ(N K n + n^2 + p^2) extra
Where
K = the number of time steps in the window; N = the ensemble size; c = the cost of one model step; m = the number of conjugate gradient steps, at most p + 1; n = the state dimension; p = the number of observations in the window
Properties
deterministicnot needs adjoint
Origin
Chengsi Liu, Qingnong Xiao, Bin Wang, Mark Buehner, 2008

Four-dimensional ensemble-variational assimilation (4DEnVar) fits a model state to all observations of a time window, like 4D-Var, but it needs no tangent linear and no adjoint model. An ensemble of NN forecasts is run forward over the window with the full model. At each time kk the scaled perturbations xi′(k)x'_i(k) of the members about their mean describe how an error at the start of the window has grown by time kk. The increment at time kk is

δxk=∑i=1Nxi′(k)∘(ULαi),\delta x_k = \sum_{i=1}^N x'_i(k) \circ (U_L\alpha_i),

with the same control α=(α1,…,αN)\alpha = (\alpha_1, \ldots, \alpha_N) at all times and a localization matrix L=ULUL⊤L = U_LU_L^\top. The control is found by minimizing a quadratic cost with the conjugate gradient method. This is the alpha control variable of hybrid ensemble-variational assimilation, applied over the window. The implied covariance between the increments at times kk and ll is L∘(Xk′Xl′⊤)L \circ (X'_kX'^\top_l), and for a linear model without localization and an ensemble with X0′X0′⊤=BX'_0X'^\top_0 = B the analysis is exactly 4D-Var.

In plain words

4D-Var finds the start of a forecast that best fits all measurements in a time window. To do this it needs special extra code that runs the model backward, and this code is hard to write and to keep correct. 4DEnVar replaces this code with a set of ordinary forecasts that start from slightly different states. The way these forecasts spread apart over the window shows how a change at the start moves and grows. The method then looks for the best mix of these spreads to fit the measurements. It uses only the normal forecast model, run once for each member of the set, and the runs can all go at the same time.

The problem

Input. A background state xbx^b at the start of the window, a model xk=Mk(xk−1)x_k = \mathcal M_k(x_{k-1}) for k=1,…,Kk = 1, \ldots, K, an ensemble of start states x1(0),…,xN(0)x_1(0), \ldots, x_N(0), a localization matrix LL, and observations yk=Hkxk+ϵky_k = H_kx_k + \epsilon_k with ϵk∼N(0,Rk)\epsilon_k \sim N(0, R_k) at the times k∈T⊆{1,…,K}k \in T \subseteq \{1, \ldots, K\}, with linear HkH_k. Notation of Ide, Courtier, Ghil and Lorenc (1997).

Output. The analysis xka=xkb+δxkx^a_k = x^b_k + \delta x_k at the start, at the end and at the observation times, where xkbx^b_k is the background trajectory, δxk\delta x_k is as above and α\alpha minimizes

J(α)=12∣α∣2+∑k∈T12(dk−Hkδxk)⊤Rk−1(dk−Hkδxk),dk=yk−Hkxkb,J(\alpha) = \tfrac12|\alpha|^2 + \sum_{k \in T}\tfrac12(d_k - H_k\delta x_k)^\top R_k^{-1}(d_k - H_k\delta x_k), \qquad d_k = y_k - H_kx^b_k,

with xi′(k)=(xi(k)−xˉ(k))/N−1x'_i(k) = (x_i(k) - \bar x(k))/\sqrt{N - 1} and ∘\circ the entrywise product.

The algorithm

  1. FOUR-D-ENVAR(x^b, {x_i(0)}, L, {(H_k, y_k, R_k)}, M, K)
  2. 1x^b_k <- run the model from x^b for k = 0..K
  3. 2x_i(k) <- run the model from x_i(0) for i = 1..N ▷ forward only
  4. 3x'_i(k) <- (x_i(k) - mean_k) / sqrt(N - 1) ; U_L <- square root of L
  5. 4d_k <- y_k - H_k x^b_k for every k in T
  6. 5U_k alpha = sum_i x'_i(k) o (U_L alpha_i)
  7. 6b <- sum_k U_k^T H_k^T R_k^-1 d_k
  8. 7A alpha = alpha + sum_k U_k^T H_k^T R_k^-1 H_k U_k alpha
  9. 8alpha <- solve A alpha = b by conjugate gradients
  10. 9x^a_k <- x^b_k + U_k alpha for each k
  11. 10return {x^a_k}

The transpose Uk⊤U_k^\top maps a vector gg to (UL⊤(x1′(k)∘g),…,UL⊤(xN′(k)∘g))(U_L^\top(x'_1(k) \circ g), \ldots, U_L^\top(x'_N(k) \circ g)). In 4D-Var the same products need the tangent linear model forward and the adjoint model backward at every iteration. Here the time dimension is carried by the stored perturbations xi′(k)x'_i(k), so an iteration costs only products with ULU_L and with the observation operators. In large systems ULU_L is a spectral or recursive filter, and only the perturbations at the observation times are stored.

Example

One variable. Take the model x1=2x0x_1 = 2x_0, K=1K = 1, xb=0x^b = 0 and the two members ∓1/2\mp 1/\sqrt 2. Their perturbations are x1,2′(0)=∓1/2x'_{1,2}(0) = \mp 1/\sqrt 2, so X0′X0′⊤=1=BX'_0X'^\top_0 = 1 = B, and x1,2′(1)=∓2x'_{1,2}(1) = \mp\sqrt 2. One observation y1=2y_1 = 2 with H=R=1H = R = 1 gives d1=2d_1 = 2, C11=4C_{11} = 4, w=2/(4+1)=0.4w = 2/(4 + 1) = 0.4, and

x0a=C01w=2⋅0.4=0.8,x1a=C11w=1.6=2x0a.x^a_0 = C_{01}w = 2 \cdot 0.4 = 0.8, \qquad x^a_1 = C_{11}w = 1.6 = 2x^a_0 .

This is the 4D-Var analysis x0a=1⋅2⋅(4+1)−1⋅2=0.8x^a_0 = 1 \cdot 2 \cdot (4 + 1)^{-1} \cdot 2 = 0.8. The reference code gives 0.80.8 and 1.61.6 to rounding error.

Lorenz-63. A twin run uses the Lorenz-63 equations with forward Euler steps of 0.010.01, a window of K=25K = 25 steps, a background error of standard deviation 1 in each variable, members drawn about the background with the same spread, and all three variables observed at steps 10 and 25 with error variance 0.25. No localization is used. The table gives the mean error norm over 20 cases (a measurement):

start of window end of window
background 1.45 2.10
4DEnVar, N=4N = 4 1.11 0.61
4DEnVar, N=10N = 10 0.94 0.46
4DEnVar, N=40N = 40 0.89 0.47

The error at the end of the window falls to about a quarter of the background error. More members help up to about N=10N = 10; after that the error is limited by the nonlinearity of the model over the window and by the observation errors.

Correctness

The proof shows that UkUl⊤=L∘(Xk′Xl′⊤)U_kU_l^\top = L \circ (X'_kX'^\top_l), and with a push-through identity that the minimizer gives the conditional mean of the increments given all observations of the window, for a Gaussian prior with these covariance blocks (a theorem). For a linear model with LL the matrix of ones and X0′X0′⊤=BX'_0X'^\top_0 = B, the perturbations are Xk′=M(k)X0′X'_k = M^{(k)}X'_0, the blocks are M(k)BM(l)⊤M^{(k)}BM^{(l)\top}, and the analysis is the strong-constraint 4D-Var analysis (a theorem). The tests check the first result to 10−810^{-8} against a direct solve with the stacked covariance, for a linear and a nonlinear model, the second to 10−810^{-8} against the 4D-Var formula with an ensemble built to have X0′X0′⊤=BX'_0X'^\top_0 = B exactly, and the count of (N+1)K(N + 1)K forward model calls.

Proof: 4DEnVar conditions on all observations of the window with the localized four-dimensional ensemble covariancefull

Setting. The window has the time levels 0,…,K0, \ldots, K, and TT is the set of observation times. Lines L1 and L2 give the background trajectory xkbx^b_k and the member trajectories xi(k)x_i(k), i=1,…,Ni = 1, \ldots, N, with N≥2N \ge 2. Let xi′(k)=(xi(k)−xˉ(k))/N−1x'_i(k) = (x_i(k) - \bar x(k))/\sqrt{N - 1}, let Xk′X'_k be the n×Nn \times N matrix with the columns xi′(k)x'_i(k), and let Di(k)=diag(xi′(k))D_i(k) = \mathrm{diag}(x'_i(k)). L=ULUL⊤L = U_LU_L^\top is symmetric positive semidefinite (line L3). For k∈Tk \in T, HkH_k is a pk×np_k \times n matrix, RkR_k is symmetric positive definite and dk=yk−Hkxkbd_k = y_k - H_kx^b_k (line L4). The control is α=(α1,…,αN)∈RNn\alpha = (\alpha_1, \ldots, \alpha_N) \in \mathbb R^{Nn}, and line L5 is the linear map

Ukα=∑i=1NDi(k) ULαi.U_k\alpha = \sum_{i=1}^N D_i(k)\, U_L\alpha_i .

The cost is J(α)=12∣α∣2+∑k∈T12(dk−HkUkα)⊤Rk−1(dk−HkUkα)J(\alpha) = \tfrac12 |\alpha|^2 + \sum_{k \in T} \tfrac12 (d_k - H_kU_k\alpha)^\top R_k^{-1}(d_k - H_kU_k\alpha). Stack the times of TT: U\mathbf U has the block rows UkU_k, H=diag(Hk)\mathbf H = \mathrm{diag}(H_k), R=diag(Rk)\mathbf R = \mathrm{diag}(R_k) and d\mathbf d has the blocks dkd_k. Then J(α)=12∣α∣2+12(d−HUα)⊤R−1(d−HUα)J(\alpha) = \tfrac12|\alpha|^2 + \tfrac12(\mathbf d - \mathbf H\mathbf U\alpha)^\top\mathbf R^{-1}(\mathbf d - \mathbf H\mathbf U\alpha), and p=∑kpkp = \sum_k p_k.

Lemma 1 (the implied four-dimensional covariance). For all times kk and ll,

UkUl⊤=L∘(Xk′Xl′⊤)=:Ckl.U_kU_l^\top = L \circ (X'_kX'^\top_l) =: C_{kl} .

Proof. UkU_k has the blocks Di(k)ULD_i(k)U_L, so UkUl⊤=∑iDi(k) ULUL⊤Di(l)=∑iDi(k)LDi(l)U_kU_l^\top = \sum_i D_i(k)\,U_LU_L^\top D_i(l) = \sum_i D_i(k) L D_i(l). The entry (j,m)(j, m) of Di(k)LDi(l)D_i(k)LD_i(l) is xij′(k)Ljmxim′(l)x'_{ij}(k) L_{jm} x'_{im}(l), and the sum over ii is Ljm(Xk′Xl′⊤)jmL_{jm}(X'_kX'^\top_l)_{jm}. □\square

So the same control α\alpha at all times gives increments whose covariance between times kk and ll is the localized sample covariance of the ensemble between those times. The block matrix C=UU⊤\mathbf C = \mathbf U\mathbf U^\top with the blocks CklC_{kl} is positive semidefinite.

Theorem 2. The minimizer α∗\alpha^\ast of JJ is unique, and the analysis of line L9 is

xka=xkb+Ukα∗=xkb+∑l∈TCklHl⊤wl,w=(HCH⊤+R)−1d.x^a_k = x^b_k + U_k\alpha^\ast = x^b_k + \sum_{l \in T} C_{kl} H_l^\top w_l, \qquad w = (\mathbf H\mathbf C\mathbf H^\top + \mathbf R)^{-1}\mathbf d .

This is the conditional mean of the increments at time kk given all observations of the window, for a Gaussian prior with the covariance blocks CklC_{kl}.

Proof. JJ is a quadratic with Hessian A=I+U⊤H⊤R−1HUA = I + \mathbf U^\top\mathbf H^\top\mathbf R^{-1}\mathbf H\mathbf U, which is symmetric positive definite, so α∗=A−1U⊤H⊤R−1d\alpha^\ast = A^{-1}\mathbf U^\top\mathbf H^\top\mathbf R^{-1}\mathbf d is the unique minimizer. Line L6 computes the right side b=U⊤H⊤R−1db = \mathbf U^\top\mathbf H^\top\mathbf R^{-1}\mathbf d, and line L7 applies AA. Expanding both sides gives

(I+U⊤H⊤R−1HU) U⊤H⊤=U⊤H⊤R−1(R+HUU⊤H⊤).(I + \mathbf U^\top\mathbf H^\top\mathbf R^{-1}\mathbf H\mathbf U)\,\mathbf U^\top\mathbf H^\top = \mathbf U^\top\mathbf H^\top\mathbf R^{-1}(\mathbf R + \mathbf H\mathbf U\mathbf U^\top\mathbf H^\top).

Multiply on the left by A−1A^{-1} and on the right by (R+HCH⊤)−1(\mathbf R + \mathbf H\mathbf C\mathbf H^\top)^{-1}: U⊤H⊤(HCH⊤+R)−1=A−1U⊤H⊤R−1\mathbf U^\top\mathbf H^\top(\mathbf H\mathbf C\mathbf H^\top + \mathbf R)^{-1} = A^{-1}\mathbf U^\top\mathbf H^\top\mathbf R^{-1}. So α∗=U⊤H⊤w\alpha^\ast = \mathbf U^\top\mathbf H^\top w and Ukα∗=∑lUkUl⊤Hl⊤wl=∑lCklHl⊤wlU_k\alpha^\ast = \sum_l U_kU_l^\top H_l^\top w_l = \sum_l C_{kl}H_l^\top w_l by Lemma 1. For jointly Gaussian increments δxk\delta x_k with the covariances CklC_{kl} and observations d=H δx+ϵ\mathbf d = \mathbf H\,\delta\mathbf x + \epsilon, ϵ∼N(0,R)\epsilon \sim N(0, \mathbf R), the conditional mean of δxk\delta x_k is Cov(δxk,d) Cov(d)−1d\mathrm{Cov}(\delta x_k, \mathbf d)\,\mathrm{Cov}(\mathbf d)^{-1}\mathbf d, and this is the same expression. □\square

Theorem 3 (equivalence with 4D-Var). Let the model be linear, xk=Mkxk−1x_k = M_kx_{k-1}, with M(k)=Mk⋯M1M^{(k)} = M_k\cdots M_1 and M(0)=IM^{(0)} = I. Let LL be the matrix of ones and let X0′X0′⊤=BX'_0X'^\top_0 = B be positive definite (this needs N≥n+1N \ge n + 1). Then x0ax^a_0 is the minimizer of the strong-constraint 4D-Var cost with background covariance BB, and xka=M(k)x0ax^a_k = M^{(k)}x^a_0 for every kk.

Proof. The model is linear, so xi(k)=M(k)xi(0)x_i(k) = M^{(k)}x_i(0), xˉ(k)=M(k)xˉ(0)\bar x(k) = M^{(k)}\bar x(0) and Xk′=M(k)X0′X'_k = M^{(k)}X'_0. With LL the matrix of ones, Ckl=M(k)BM(l)⊤C_{kl} = M^{(k)}BM^{(l)\top}. Let GG have the block rows HkM(k)H_kM^{(k)}, k∈Tk \in T. Then HCH⊤=GBG⊤\mathbf H\mathbf C\mathbf H^\top = GBG^\top, d=y−Gxb\mathbf d = \mathbf y - Gx^b and, by Theorem 2,

x0a=xb+BG⊤(GBG⊤+R)−1(y−Gxb).x^a_0 = x^b + BG^\top(GBG^\top + \mathbf R)^{-1}(\mathbf y - Gx^b).

The 4D-Var cost 12(x0−xb)⊤B−1(x0−xb)+12(y−Gx0)⊤R−1(y−Gx0)\tfrac12(x_0 - x^b)^\top B^{-1}(x_0 - x^b) + \tfrac12(\mathbf y - Gx_0)^\top\mathbf R^{-1}(\mathbf y - Gx_0) is a quadratic in x0x_0, and its minimizer xb+(B−1+G⊤R−1G)−1G⊤R−1(y−Gxb)x^b + (B^{-1} + G^\top\mathbf R^{-1}G)^{-1}G^\top\mathbf R^{-1}(\mathbf y - Gx^b) is the same vector by the Sherman-Morrison-Woodbury identity (B−1+G⊤R−1G)−1G⊤R−1=BG⊤(GBG⊤+R)−1(B^{-1} + G^\top\mathbf R^{-1}G)^{-1}G^\top\mathbf R^{-1} = BG^\top(GBG^\top + \mathbf R)^{-1}. Finally Ckl=M(k)C0lC_{kl} = M^{(k)}C_{0l} and xkb=M(k)xbx^b_k = M^{(k)}x^b, so xka=M(k)x0ax^a_k = M^{(k)}x^a_0. □\square

For a nonlinear model, the member trajectories replace the tangent linear model: Xk′X'_k is a finite difference estimate of M(k)M^{(k)} applied to X0′X'_0, and the analysis xkax^a_k is not in general a model trajectory.

Termination. A−I=U⊤H⊤R−1HUA - I = \mathbf U^\top\mathbf H^\top\mathbf R^{-1}\mathbf H\mathbf U has rank at most pp, so AA has at most p+1p + 1 distinct eigenvalues, and the conjugate gradient method of line L8 reaches α∗\alpha^\ast in at most p+1p + 1 steps in exact arithmetic. The code also stops after at most 2Nn2Nn steps. The model runs only forward, KK steps for the background and KK steps for each member, so line L1 and line L2 call it (N+1)K(N + 1)K times and the minimization does not call it at all.

Summary. 4DEnVar gives the analysis of all observations of the window with the localized four-dimensional covariance L∘(Xk′Xl′⊤)L \circ (X'_kX'^\top_l) (Theorem 2), and for a linear model without localization and an ensemble with X0′X0′⊤=BX'_0X'^\top_0 = B it is strong-constraint 4D-Var (Theorem 3). The tests check Theorem 2 to 10−810^{-8} against a direct solve with the stacked covariance for a linear and a nonlinear model, Theorem 3 to 10−810^{-8} against the 4D-Var formula, and the count of (N+1)K(N + 1)K model calls. ■\blacksquare

Complexity

The model runs cost Θ(NKc)\Theta(NKc) for N+1N + 1 forward runs of KK steps, and they are independent, so they can run in parallel. The control has NnNn entries. With a dense ULU_L, one product with AA costs Θ(KNn2+pn)\Theta(KNn^2 + pn), the Cholesky factorizations of LL and of the RkR_k cost Θ(n3+p3)\Theta(n^3 + p^3) once, and m≤p+1m \le p + 1 conjugate gradient steps give the time Θ(NKc+n3+p3+m(KNn2+pn))\Theta(NKc + n^3 + p^3 + m(KNn^2 + pn)). The stored perturbations take Θ(NKn)\Theta(NKn) memory, or Θ(N∣T∣n)\Theta(N|T|n) if only the observation times are kept. In 4D-Var each iteration needs one tangent linear and one adjoint run over the window, so 4DEnVar trades mm such pairs of runs for NN forward runs that run at the same time.

Properties

  • No adjoint. The model runs only forward, (N+1)K(N + 1)K steps in total, before the minimization starts.
  • Four-dimensional covariance. The covariance between the increments at times kk and ll is L∘(Xk′Xl′⊤)L \circ (X'_kX'^\top_l), so an observation at time kk changes the state at all times of the window (a theorem).
  • Exact 4D-Var in the linear case. For a linear model, LL the matrix of ones and X0′X0′⊤=BX'_0X'^\top_0 = B, the analysis is the strong-constraint 4D-Var analysis (a theorem).
  • Static localization in time. The same LL is applied at all times. If features move far during the window, the localization does not move with them, unlike 4D-Var with a localized BB, whose covariance the tangent linear model carries along.
  • The analysis trajectory is not a model trajectory. For a nonlinear model, xKa=xKb+δxKx^a_K = x^b_K + \delta x_K is in general not M(x0a)\mathcal M(x^a_0).
  • Parallel. The ensemble runs are independent, and the minimization has no sequential model runs.

Variants and improvements

  • Hybrid 4DEnVar. Add a static covariance part, βcUcvc\beta_cU_cv_c, to the increment, as in hybrid ensemble-variational assimilation. The static part has no time evolution in 4DEnVar unless a model propagates it.
  • Hybrid 4D-Var. Keep the tangent linear and adjoint models of incremental 4D-Var and use the hybrid covariance only at the start of the window.
  • Outer loops. Rerun the background and the ensemble from the new analysis to treat stronger nonlinearity, at the cost of more ensemble runs.
  • Ensemble Kalman smoother. The ensemble Kalman smoother uses the same four-dimensional ensemble covariances, but it updates the members by a sequential formula instead of a variational minimization.
  • Weak constraint. Model error can be added as in weak-constraint 4D-Var, with an ensemble estimate of its covariance.

When to use it

Use 4DEnVar when an ensemble is already run and the model has no maintained adjoint, or when the computer is massively parallel and the sequential tangent linear and adjoint runs of 4D-Var are the bottleneck. It is the four-dimensional form of a hybrid system and needs a good ensemble with enough spread. If an adjoint exists and the window has strong nonlinearity or features that move far, 4D-Var with a hybrid covariance can give better results. If no variational system exists, an ensemble Kalman filter or the LETKF is simpler.

Pitfalls

  • No localization (line L5). With NN much smaller than nn, the raw four-dimensional covariance has rank N−1N - 1 and spurious long-range links, also between times. Use covariance localization.
  • Wrong perturbation scaling (line L3). The perturbations must be divided by N−1\sqrt{N - 1}, or the implied covariance is too large or too small.
  • Perturbations about the wrong trajectory (lines L1 to L3). The perturbations are deviations from the ensemble mean at each time, not from the background trajectory. If the mean and the background drift apart, the increments are wrong.
  • Too long a window. The ensemble perturbations grow nonlinearly and the linear relation between δx0\delta x_0 and δxk\delta x_k breaks down. Shorten the window or use outer loops.
  • Ensemble spread that is too small. An under-dispersive ensemble gives too small increments; use covariance inflation.
  • An inexact transpose of UkU_k (lines L6 and L7). Then AA is not symmetric and the conjugate gradient method fails. Check UkU_k and Uk⊤U_k^\top with the dot product test.

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.

four_dimensional_ensemble_variational.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/four-dimensional-ensemble-variational/. The authors are listed in prov/5MYERD.jsonl.

"""Four-dimensional ensemble-variational assimilation (4DEnVar).

Notation of Ide, Courtier, Ghil and Lorenc (1997). The window has the time
levels 0..K. Each ensemble member is run forward over the window with the
full model, and the scaled perturbations x'_i(k) = (x_i(k) - mean_k) /
sqrt(N - 1) at each time replace the tangent linear model of 4D-Var. The
increment at time k is

    dx_k = sum_i x'_i(k) o (U_L alpha_i),    U_L U_L^T = L,

with the same control alpha = (alpha_1, ..., alpha_N) at all times, and the
cost over alpha is

    J = 1/2 |alpha|^2 + sum_(k in T) 1/2 (d_k - H_k dx_k)^T R_k^-1 (d_k - H_k dx_k),

where d_k = y_k - H_k x^b_k is the departure from the background
trajectory. No tangent linear or adjoint model is needed: the model runs
only forward, once for the background and once for each member. The
implied covariance between the increments at times k and l is
L o (X'_k X'_l^T).

The model is a function step(k, x) = M_k(x) for x = x_(k-1). obs maps a
time k to (H_k, y_k, R_k), with a linear observation operator H_k.
"""

import math

import scimat


def run(x0, step, K):
    """Return the trajectory [x_0, ..., x_K] of the model from x0."""
    xs = [list(x0)]
    for k in range(1, K + 1):
        xs.append(step(k, xs[-1]))
    return xs


def _square_root(A):
    """Return a lower triangular U with U U^T = A, with a tiny shift if A is only semidefinite."""
    try:
        return scimat.cholesky(A)
    except ValueError:
        n = len(A)
        eps = 1e-12 * max(1.0, max(abs(A[i][i]) for i in range(n)))
        return scimat.cholesky([[A[i][j] + (eps if i == j else 0.0) for j in range(n)] for i in range(n)])


def conjugate_gradient(apply_a, b, tol=1e-13, max_iter=None):
    """Solve A w = b for symmetric positive definite A given as a function."""
    n = len(b)
    if max_iter is None:
        max_iter = 2 * n
    w = [0.0] * n
    r = list(b)
    q = list(r)
    rr = scimat.dot(r, r)
    stop = (tol * scimat.norm2(b)) ** 2
    for _ in range(max_iter):
        if rr <= stop:
            break
        aq = apply_a(q)
        alpha = rr / scimat.dot(q, aq)
        w = [wi + alpha * qi for wi, qi in zip(w, q)]
        r = [ri - alpha * ai for ri, ai in zip(r, aq)]
        rr_new = scimat.dot(r, r)
        q = [ri + (rr_new / rr) * qi for ri, qi in zip(r, q)]
        rr = rr_new
    return w


def four_d_envar(xb, members, L, obs, step, K):
    """Return {k: x^a_k} of 4DEnVar with localization matrix L, for k = 0, K and every observation time."""
    n = len(xb)
    N = len(members)
    background = run(xb, step, K)  # @line L1
    trajs = [run(m, step, K) for m in members]  # @line L2
    s = 1.0 / math.sqrt(N - 1)
    xp = {}
    for k in sorted(set(obs) | {0, K}):
        mean = [sum(t[k][j] for t in trajs) / N for j in range(n)]
        xp[k] = [[s * (t[k][j] - mean[j]) for j in range(n)] for t in trajs]
    UL = _square_root(L)  # @line L3
    ULt = scimat.transpose(UL)
    ob = {k: (H, scimat.transpose(H), y, scimat.cholesky(R)) for k, (H, y, R) in obs.items()}
    d = {k: scimat.sub(y, scimat.matvec(H, background[k])) for k, (H, Ht, y, LR) in ob.items()}  # @line L4

    def U(k, a, loc=None):  # @line L5
        if loc is None:
            loc = [scimat.matvec(UL, a[n * i : n * (i + 1)]) for i in range(N)]
        dx = [0.0] * n
        for i in range(N):
            dx = [v + p * q for v, p, q in zip(dx, xp[k][i], loc[i])]
        return dx

    def Ut(k, g):
        out = []
        for i in range(N):
            out.extend(scimat.matvec(ULt, [p * q for p, q in zip(xp[k][i], g)]))
        return out

    b = [0.0] * (N * n)  # @line L6
    for k, (H, Ht, y, LR) in ob.items():
        b = scimat.add(b, Ut(k, scimat.matvec(Ht, scimat.cholesky_solve(LR, d[k]))))

    def apply_a(a):  # @line L7
        loc = [scimat.matvec(UL, a[n * i : n * (i + 1)]) for i in range(N)]
        out = list(a)
        for k, (H, Ht, y, LR) in ob.items():
            g = scimat.matvec(Ht, scimat.cholesky_solve(LR, scimat.matvec(H, U(k, a, loc))))
            out = scimat.add(out, Ut(k, g))
        return out

    a = conjugate_gradient(apply_a, b)  # @line L8
    loc = [scimat.matvec(UL, a[n * i : n * (i + 1)]) for i in range(N)]
    analysis = {}
    for k in xp:  # @line L9
        analysis[k] = scimat.add(background[k], U(k, a, loc))
    return analysis  # @line L10


def linear_model(M):
    """Return step for the linear model x_k = M x_(k-1)."""
    return lambda k, x: scimat.matvec(M, x)


def lorenz63(dt=0.01, sigma=10.0, rho=28.0, beta=8.0 / 3.0):
    """Return step for forward Euler steps of the Lorenz-63 model."""

    def step(k, x):
        f = [sigma * (x[1] - x[0]), x[0] * (rho - x[2]) - x[1], x[0] * x[1] - beta * x[2]]
        return [xi + dt * fi for xi, fi in zip(x, f)]

    return step
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_four_dimensional_ensemble_variational.py 214 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/four-dimensional-ensemble-variational/. The authors are listed in prov/5MYERD.jsonl.

import math
import random

import scimat
from four_dimensional_ensemble_variational import four_d_envar, linear_model, lorenz63, run


def random_matrix(rng, m, n):
    return [[rng.uniform(-1, 1) for _ in range(n)] for _ in range(m)]


def random_spd(rng, n, shift=0.5):
    A = random_matrix(rng, n, n)
    S = scimat.matmul(A, scimat.transpose(A))
    for i in range(n):
        S[i][i] += shift
    return S


def gaussian_localization(n, c):
    return [[math.exp(-((i - j) ** 2) / (2.0 * c * c)) for j in range(n)] for i in range(n)]


def close(a, b, tol):
    return all(abs(u - v) <= tol * (1 + abs(v)) for u, v in zip(a, b))


def exact_ensemble(xb, B):
    """Return N = n + 1 members whose scaled perturbations X' satisfy X' X'^T = B exactly."""
    n = len(xb)
    N = n + 1
    basis = [[1.0] * N] + [[1.0 if j == i else 0.0 for j in range(N)] for i in range(n)]
    rows = []
    for v in basis:
        w = list(v)
        for q in rows:
            c = scimat.dot(w, q)
            w = [a - c * b for a, b in zip(w, q)]
        rows.append(scimat.scale(1.0 / scimat.norm2(w), w))
    W = rows[1:]  # n orthonormal rows, each orthogonal to the ones vector
    UB = scimat.cholesky(B)
    cols = scimat.matmul(UB, W)
    return [[xb[j] + math.sqrt(N - 1) * cols[j][i] for j in range(n)] for i in range(N)]


def strong_4dvar_reference(xb, B, M, obs):
    """x^a_0 = x^b + B G^T (G B G^T + R)^-1 (y - G x^b), with G the stacked H_k M^k."""
    n = len(xb)
    G, y, blocks = [], [], []
    for k in sorted(obs):
        H, yk, R = obs[k]
        Mk = scimat.eye(n)
        for _ in range(k):
            Mk = scimat.matmul(M, Mk)
        G.extend(scimat.matmul(H, Mk))
        y.extend(yk)
        blocks.append(R)
    m = len(y)
    Rbig = scimat.zeros(m, m)
    off = 0
    for R in blocks:
        for i in range(len(R)):
            for j in range(len(R)):
                Rbig[off + i][off + j] = R[i][j]
        off += len(R)
    GB = scimat.matmul(G, B)
    S = scimat.add(scimat.matmul(GB, scimat.transpose(G)), Rbig)
    w = scimat.solve(S, scimat.sub(y, scimat.matvec(G, xb)))
    return scimat.add(xb, scimat.matvec(scimat.transpose(GB), w))


def localized_reference(xb, members, L, obs, step, K):
    """Brute force: condition on all observations at once with C_kl = L o (X'_k X'_l^T)."""
    n, N = len(xb), len(members)
    background = run(xb, step, K)
    trajs = [run(m, step, K) for m in members]
    times = sorted(set(obs) | {0, K})
    s = 1.0 / math.sqrt(N - 1)
    X = {}
    for k in times:
        mean = [sum(t[k][j] for t in trajs) / N for j in range(n)]
        X[k] = [[s * (t[k][j] - mean[j]) for t in trajs] for j in range(n)]

    def C(k, l):
        P = scimat.matmul(X[k], scimat.transpose(X[l]))
        return [[L[i][j] * P[i][j] for j in range(n)] for i in range(n)]

    otimes = sorted(obs)
    sizes = [len(obs[k][1]) for k in otimes]
    m = sum(sizes)
    S = scimat.zeros(m, m)
    d = []
    oi = 0
    for a, k in enumerate(otimes):
        Hk, yk, Rk = obs[k]
        d.extend(scimat.sub(yk, scimat.matvec(Hk, background[k])))
        oj = 0
        for b, l in enumerate(otimes):
            Hl = obs[l][0]
            blk = scimat.matmul(scimat.matmul(Hk, C(k, l)), scimat.transpose(Hl))
            for i in range(sizes[a]):
                for j in range(sizes[b]):
                    S[oi + i][oj + j] = blk[i][j] + (Rk[i][j] if a == b else 0.0)
            oj += sizes[b]
        oi += sizes[a]
    w = scimat.solve(S, d)
    out = {}
    for k in times:
        x = list(background[k])
        off = 0
        for l, size in zip(otimes, sizes):
            Hl = obs[l][0]
            g = scimat.matvec(scimat.transpose(Hl), w[off : off + size])
            x = scimat.add(x, scimat.matvec(C(k, l), g))
            off += size
        out[k] = x
    return out


def test_scalar_check_value():
    # x_1 = 2 x_0, B = 1 from the members -1/sqrt(2) and 1/sqrt(2), y_1 = 2 with R = 1: x^a_0 = 0.8.
    r = 1.0 / math.sqrt(2.0)
    obs = {1: ([[1.0]], [2.0], [[1.0]])}
    xa = four_d_envar([0.0], [[-r], [r]], [[1.0]], obs, linear_model([[2.0]]), 1)
    assert abs(xa[0][0] - 0.8) < 1e-12
    assert abs(xa[1][0] - 1.6) < 1e-12


def test_equals_strong_4dvar_for_exact_ensemble():
    # Linear model, no localization and X' X'^T = B: 4DEnVar is 4D-Var with the same B.
    rng = random.Random(11)
    n, K = 4, 3
    M = scimat.add(scimat.eye(n), scimat.scale(0.3, random_matrix(rng, n, n)))
    B = random_spd(rng, n)
    xb = [rng.gauss(0, 1) for _ in range(n)]
    obs = {}
    for k in (1, 3):
        H = random_matrix(rng, 2, n)
        obs[k] = (H, [rng.gauss(0, 1) for _ in range(2)], random_spd(rng, 2, 0.3))
    members = exact_ensemble(xb, B)
    ones = [[1.0] * n for _ in range(n)]
    xa = four_d_envar(xb, members, ones, obs, linear_model(M), K)
    ref0 = strong_4dvar_reference(xb, B, M, obs)
    assert close(xa[0], ref0, 1e-8)
    refK = ref0
    for _ in range(K):
        refK = scimat.matvec(M, refK)
    assert close(xa[K], refK, 1e-8)


def test_localized_against_stacked_conditioning():
    rng = random.Random(5)
    n, N, K = 5, 3, 2
    M = scimat.add(scimat.eye(n), scimat.scale(0.2, random_matrix(rng, n, n)))
    xb = [rng.gauss(0, 1) for _ in range(n)]
    members = [[x + rng.gauss(0, 1) for x in xb] for _ in range(N)]
    L = gaussian_localization(n, 1.0)
    obs = {}
    for k in (1, 2):
        H = random_matrix(rng, 2, n)
        obs[k] = (H, [rng.gauss(0, 1) for _ in range(2)], random_spd(rng, 2, 0.3))
    for step in (linear_model(M), lorenz_like(n)):
        xa = four_d_envar(xb, members, L, obs, step, K)
        ref = localized_reference(xb, members, L, obs, step, K)
        for k in ref:
            assert close(xa[k], ref[k], 1e-8)


def lorenz_like(n):
    """A small nonlinear map, to show that the formula holds for any member trajectories."""
    return lambda k, x: [x[j] + 0.1 * (x[(j + 1) % n] - x[j - 2]) * x[j - 1] - 0.05 * x[j] for j in range(n)]


def test_model_runs_forward_only():
    calls = [0]
    base = linear_model([[0.9, 0.1], [0.0, 1.1]])

    def step(k, x):
        calls[0] += 1
        return base(k, x)

    rng = random.Random(3)
    N, K = 4, 6
    xb = [0.0, 0.0]
    members = [[rng.gauss(0, 1), rng.gauss(0, 1)] for _ in range(N)]
    obs = {k: ([[1.0, 0.0]], [1.0], [[0.5]]) for k in (2, 4, 6)}
    four_d_envar(xb, members, [[1.0, 0.5], [0.5, 1.0]], obs, step, K)
    assert calls[0] == (N + 1) * K


def test_lorenz63_twin_reduces_error():
    step = lorenz63(0.01)
    K = 25
    obs_times = (10, 25)
    H = scimat.eye(3)
    R = scimat.scale(0.25, scimat.eye(3))
    ones = [[1.0] * 3 for _ in range(3)]
    err_b = err_a = 0.0
    seeds = range(20)
    for seed in seeds:
        rng = random.Random(100 + seed)
        spin = run([1.0, 1.0, 20.0], step, 200 + 37 * seed)[-1]
        truth = run(spin, step, K)
        xb = [v + rng.gauss(0, 1) for v in spin]
        members = [[v + rng.gauss(0, 1) for v in xb] for _ in range(10)]
        obs = {k: (H, [v + rng.gauss(0, 0.5) for v in truth[k]], R) for k in obs_times}
        xa = four_d_envar(xb, members, ones, obs, step, K)
        back = run(xb, step, K)
        err_b += scimat.norm2(scimat.sub(back[K], truth[K])) / len(seeds)
        err_a += scimat.norm2(scimat.sub(xa[K], truth[K])) / len(seeds)
    assert err_a < 0.6 * err_b

History

Lorenc (2003) introduced the alpha control variable, which brings a localized ensemble covariance into a variational system. Liu, Xiao and Wang (2008) formulated an ensemble-based four-dimensional variational scheme in which the increment is a combination of ensemble trajectories, so no tangent linear and adjoint models are needed. Buehner and coworkers (2010) compared an ensemble four-dimensional variational scheme with 4D-Var and the ensemble Kalman filter at Environment Canada. Several operational centers later adopted 4D ensemble-variational systems (Bannister 2017).

References

  1. C. Liu, Q. Xiao and B. Wang, An ensemble-based four-dimensional variational data assimilation scheme. Part I, technical formulation and preliminary test, Monthly Weather Review 136(9) (2008) 3363-3373, the analysis increment as a combination of ensemble trajectories, without tangent linear and adjoint models
  2. M. Buehner, P. L. Houtekamer, C. Charette, H. L. Mitchell and B. He, Intercomparison of variational data assimilation and the ensemble Kalman filter for global deterministic NWP. Part I, description and single-observation experiments, Monthly Weather Review 138(5) (2010) 1550-1566, the ensemble 4D variational scheme with localized four-dimensional ensemble covariances
  3. M. Buehner, P. L. Houtekamer, C. Charette, H. L. Mitchell and B. He, Intercomparison of variational data assimilation and the ensemble Kalman filter for global deterministic NWP. Part II, one-month experiments with real observations, Monthly Weather Review 138(5) (2010) 1567-1586, the comparison with 4D-Var and the EnKF over one month of real observations
  4. A. C. Lorenc, The potential of the ensemble Kalman filter for NWP, a comparison with 4D-Var, Quarterly Journal of the Royal Meteorological Society 129 (2003) 3183-3203, the alpha control variable with localization
  5. R. N. Bannister, A review of operational methods of variational and ensemble-variational data assimilation, Quarterly Journal of the Royal Meteorological Society 143(703) (2017) 607-633, the 4D ensemble-variational systems of the operational centers
  6. 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 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