Algorithm Search⌘K

Algorithmadvanced

Ensemble adjustment Kalman filter

Also called EAKF.

Adjusts the ensemble members by a linear map so the analysis ensemble has exactly the Kalman posterior mean and covariance of the sample prior.

Time
Θ(p N (n + p)) worst
Space
Θ(N (n + p)) extra
Where
N = the ensemble size; n = the size of the state; p = the number of observations
Properties
deterministicnot perturbed observations
Origin
Jeffrey L. Anderson, 2001

The ensemble adjustment Kalman filter (EAKF) of Anderson (2001) is an ensemble Kalman filter without perturbed observations. It moves the ensemble mean with the Kalman gain and maps each forecast perturbation to an analysis perturbation with one linear map, the adjustment matrix AA. The map is chosen so that the analysis ensemble has exactly the Kalman mean and covariance for the sample covariance of the forecast. In practice the filter is used in the serial two step form of Anderson (2003): for each scalar observation it first adjusts the ensemble of the predicted observation, and then it carries the increments to the state by linear regression. It is one of the ensemble square root filters, and for a linear HH the serial form gives the same members as the serial EnSRF.

In plain words

Look at one observed number. Each member predicts a value for it, so the members give a small cloud of predicted values. The filter first moves this cloud to where Bayes' rule says it should be: it shifts the centre towards the data and shrinks the cloud about the new centre by a fixed factor. It does not add noise, and the order of the members stays the same. Then each member changes every other value by the amount that a straight line fit from the observed value predicts. A value that varies together with the observed one moves a lot, and a value with no relation to it does not move.

The problem

Input. A forecast ensemble x1,…,xN∈Rnx_1, \ldots, x_N \in \mathbb R^n, observations yo∈Rpy^o \in \mathbb R^p with an observation operator HH, and the error variances rkr_k of independent observation errors (a diagonal RR) for the serial form, or a full error covariance RR and a linear HH for the joint form. The serial form takes optional localization weights. The notation is that of Ide, Courtier, Ghil and Lorenc (1997). In the letters of the Kalman filter page, HH is its CC, the model MM is its AA, the forecast xfx^f and PfP^f are its predicted m−m^- and P−P^-, and the analysis xax^a and PaP^a are its filtered mm and PP. The adjustment matrix AA of this page is not the model.

Output. An analysis ensemble with mean xˉ+K(yo−Hxˉ)\bar x + K(y^o - H\bar x) and sample covariance (I−KH)Pf(I - KH)P^f, where PfP^f is the sample covariance of the forecast and K=PfH⊤(HPfH⊤+R)−1K = P^f H^\top(HP^fH^\top + R)^{-1} (for a linear HH and no localization).

The algorithm

The serial form keeps an ensemble of predicted observations yiy_i next to the state ensemble and processes one scalar observation at a time.

  1. EAKF-SERIAL(x_1..x_N, y^o, H, r)
  2. 1y_i <- H(x_i) for each member i ▷ the only use of H
  3. 2for k <- 1 to p do
  4. 3ybar <- mean of y_ik; s <- sample variance of y_ik
  5. 4s^a <- 1 / (1/s + 1/r_k); y^a <- s^a (ybar/s + y^o_k/r_k)
  6. 5Δy_i <- y^a + sqrt(s^a/s) (y_ik - ybar) - y_ik ▷ adjust in observation space
  7. 6b_x <- cov(x, y_k) / s; x_i <- x_i + b_x Δy_i ▷ regression onto the state
  8. 7b_y <- cov(y, y_k) / s; y_i <- y_i + b_y Δy_i ▷ and onto the other observations
  9. 8return x_1..x_N

Line L4 is the posterior of a scalar Gaussian prior N(yˉ,s)N(\bar y, s) after an observation with error variance rkr_k. Line L5 moves the predicted values so that they have exactly this mean and variance, by a shift and a shrink about the mean. Lines L6 and L7 compute the regression coefficients from the values before the update. With localization, bxb_x and byb_y are multiplied entry by entry by the weights of observation kk. An observation with s=0s = 0 carries no information about the ensemble and is skipped.

The joint form of Anderson (2001) treats all observations together for a linear HH and any positive definite RR.

  1. EAKF-JOINT(x_1..x_N, y^o, H, R)
  2. J1 xbar, X <- mean and perturbations of x_i; P <- X X^T / (N - 1)
  3. J2 P = F D F^T with the positive eigenvalues only; G <- D^(1/2)
  4. J3 M <- G F^T H^T R^-1 H F G = U Λ U^T
  5. J4 A <- F G U (I + Λ)^(-1/2) U^T G^-1 F^T ▷ the adjustment matrix
  6. J5 x^a <- xbar + P H^T (H P H^T + R)^-1 (y^o - H xbar)
  7. J6 return x^a_i <- x^a + A X_i for each member i

Line J2 keeps only the positive eigenvalues of PP, so that GG can be inverted. This matters because PP has rank at most N−1N - 1, which is usually smaller than nn.

Example

Take three members with two values each, x1=(0,1)x_1 = (0, 1), x2=(1,3)x_2 = (1, 3) and x3=(2,2)x_3 = (2, 2). The first value is observed, yo=2y^o = 2 with r=1/3r = 1/3. The predicted values are (0,1,2)(0, 1, 2), so yˉ=1\bar y = 1 and s=1s = 1. Line L4 gives sa=1/4s^a = 1/4 and ya=14(1+6)=7/4y^a = \tfrac14(1 + 6) = 7/4, and the shrink factor is 1/4=1/2\sqrt{1/4} = 1/2. Line L5 moves the predicted values to (5/4,7/4,9/4)(5/4, 7/4, 9/4), so the increments are Δy=(5/4,3/4,1/4)\Delta y = (5/4, 3/4, 1/4).

The second value (1,3,2)(1, 3, 2) has the covariance 1/21/2 with the first value, so bx=(1,1/2)b_x = (1, 1/2). The analysis members are (5/4,13/8)(5/4, 13/8), (7/4,27/8)(7/4, 27/8) and (9/4,17/8)(9/4, 17/8). The second value has the mean 19/819/8 and the variance 13/1613/16. The Kalman update with the sample covariance gives the gain K=(3/4,3/8)K = (3/4, 3/8), the same mean 2+3/8=19/82 + 3/8 = 19/8 and the same variance 1−38⋅12=13/161 - \tfrac38\cdot\tfrac12 = 13/16.

For the check value of the page group: with two members ∓1/2\mp 1/\sqrt 2, yo=1y^o = 1 and r=1r = 1, both forms return the mean 1/21/2 and the variance 1/21/2 to rounding.

A measurement. On the Lorenz-96 model with n=40n = 40, F=8F = 8, RK4 with step 0.050.05, every other variable observed every 0.050.05 time units with R=IR = I, N=20N = 20, multiplicative inflation ρ=1.02\rho = 1.02 of the forecast covariance and a Gaspari-Cohn weight with half-width 44 grid units on bxb_x and byb_y, the serial EAKF had the mean analysis RMSE 0.3730.373 over cycles 501 to 1500 (one seed). In every cycle its members differed from those of the serial EnSRF, run from the same forecast, by at most 1.3⋅10−141.3 \cdot 10^{-14}. This is Lemma 2 of the proof, which also holds with localization.

Correctness

The proof shows that line L5 gives the predicted values the Gaussian posterior mean and variance (Lemma 1). The regression of lines L6 and L7 then makes exactly the update xi+Kd−αK(Yk)ix_i + Kd - \alpha K (Y_k)_i of the serial EnSRF, with α=1/(1+r/(s+r))\alpha = 1/(1 + \sqrt{r/(s + r)}) (Lemma 2). So for a linear HH and a diagonal RR the serial EAKF has the Kalman mean and covariance (Theorem 3). For the joint form, APA⊤=(I−KH)PAPA^\top = (I - KH)P by the Woodbury identity (Lemma 4), so the members of line J6 have the Kalman mean and covariance for any positive definite RR (Theorem 5). For one scalar observation the two forms give the same members (Corollary 6). These are theorems. As N→∞N \to \infty for a linear Gaussian model the filter converges to the Kalman filter (Kwiatkowski and Mandel 2015). With localization or a nonlinear HH the update is a heuristic.

Proof: The EAKF gives exactly the Kalman analysis mean and covariance of the sample priorfull

Setting. There are N≥2N \ge 2 forecast members x1,…,xN∈Rnx_1, \ldots, x_N \in \mathbb R^n with mean xˉ\bar x, unscaled perturbations XX (n×Nn \times N, column ii is xi−xˉx_i - \bar x) and sample covariance P=XX⊤/(N−1)P = XX^\top/(N - 1). The observations are yo∈Rpy^o \in \mathbb R^p with a linear operator HH (rows hkh_k) and an error covariance RR. The serial form needs R=diag(rk)R = \mathrm{diag}(r_k) with rk>0r_k > 0; the joint form needs RR symmetric positive definite. There is no localization until the last remark. The Kalman values are K=PH⊤(HPH⊤+R)−1K = PH^\top(HPH^\top + R)^{-1}, xˉa=xˉ+K(yo−Hxˉ)\bar x^a = \bar x + K(y^o - H\bar x) and Pa=(I−KH)PP^a = (I - KH)P.

Lemma 1 (the step in observation space). Fix one observation kk with r=rkr = r_k, and let viv_i be the predicted values of line L1 with mean yˉ\bar y and sample variance s>0s > 0 (line L3). Lines L4 and L5 give new values vi+Δyiv_i + \Delta y_i with mean ya=yˉ+ss+r(yko−yˉ)y^a = \bar y + \frac{s}{s + r}(y^o_k - \bar y) and sample variance sa=srs+rs^a = \frac{sr}{s + r}.

Proof. Line L4 sets sa=(1/s+1/r)−1=sr/(s+r)s^a = (1/s + 1/r)^{-1} = sr/(s + r) and ya=sa(yˉ/s+yko/r)y^a = s^a(\bar y/s + y^o_k/r). Since sa/s+sa/r=1s^a/s + s^a/r = 1, this is ya=yˉ+(sa/r)(yko−yˉ)y^a = \bar y + (s^a/r)(y^o_k - \bar y) with sa/r=s/(s+r)s^a/r = s/(s + r). Line L5 sets vi+Δyi=ya+f(vi−yˉ)v_i + \Delta y_i = y^a + f(v_i - \bar y) with f=sa/sf = \sqrt{s^a/s}. The deviations from yay^a are ff times the old deviations, which sum to zero, so the mean is yay^a and the variance is f2s=saf^2 s = s^a. □\square

These are the mean and the variance of the posterior of a scalar Gaussian prior N(yˉ,s)N(\bar y, s) after one observation with error variance rr. Note that f=r/(s+r)f = \sqrt{r/(s + r)}, which is the number qq of the EnSRF proof.

Lemma 2 (the serial EAKF step is the serial EnSRF step). Let Yk=hkXY_k = h_k X be the perturbations of observation kk and suppose the predicted observations are HH applied to the members. With K=Phk⊤/(s+r)K = Ph_k^\top/(s + r), d=yko−hkxˉd = y^o_k - h_k\bar x, q=r/(s+r)q = \sqrt{r/(s + r)} and α=1/(1+q)\alpha = 1/(1 + q), lines L6 and L7 change member ii to

xi+Kd−αK (Yk)i,x_i + K d - \alpha K\, (Y_k)_i,

and change the predicted observations by HH times the same increments.

Proof. Line L6 sets bx=XYk⊤/((N−1)s)=Phk⊤/sb_x = X Y_k^\top/((N - 1)s) = Ph_k^\top/s, the regression coefficients of the state on observation kk. By Lemma 1, Δyi=(ya−yˉ)+(q−1)(Yk)i=ss+rd+(q−1)(Yk)i\Delta y_i = (y^a - \bar y) + (q - 1)(Y_k)_i = \frac{s}{s + r} d + (q - 1)(Y_k)_i. So bxΔyi=Kd+q−1sPhk⊤(Yk)ib_x \Delta y_i = K d + \frac{q - 1}{s} P h_k^\top (Y_k)_i. Now s=(s+r)(1−q2)s = (s + r)(1 - q^2), so

q−1s=−1−q(s+r)(1−q)(1+q)=−1(s+r)(1+q),\frac{q - 1}{s} = -\frac{1 - q}{(s + r)(1 - q)(1 + q)} = -\frac{1}{(s + r)(1 + q)},

and the second term is −αK(Yk)i-\alpha K (Y_k)_i. Line L7 uses by=YYk⊤/((N−1)s)b_y = YY_k^\top/((N - 1)s) with Y=HXY = HX, which is HbxH b_x, so the predicted observations change by HbxΔyiH b_x \Delta y_i. Both coefficients use the values before the update, as the lines of the code do. □\square

Theorem 3 (serial form). With a linear HH, a diagonal RR and no localization, the serial EAKF returns the same members as the serial EnSRF, so its output has the mean xˉa\bar x^a and the sample covariance PaP^a. If s=0s = 0 for an observation, the code skips it, which is the Kalman update with K=0K = 0.

Proof. By Lemma 2 each pass of the loop of line L2 makes the EnSRF update of lines L8 and L9 of the EnSRF, and keeps the predicted observations equal to HH applied to the members. Theorem 3 of the EnSRF proof says that the serial EnSRF ends with the Kalman mean and covariance. If s=0s = 0, then Yk=0Y_k = 0, so hkPhk⊤=0h_k P h_k^\top = 0, Phk⊤=0Ph_k^\top = 0 (PP is positive semidefinite) and K=0K = 0. □\square

Lemma 4 (the adjustment matrix). Let P=FDF⊤P = F D F^\top where FF (n×mn \times m) has orthonormal columns and D=diag(d1,…,dm)D = \mathrm{diag}(d_1, \ldots, d_m) holds the positive eigenvalues (line J2). Put G=D1/2G = D^{1/2}, Z=FGZ = FG, B=HZB = HZ and M=B⊤R−1B=UΛU⊤M = B^\top R^{-1} B = U\Lambda U^\top (line J3), and

A=Z U(I+Λ)−1/2U⊤ G−1F⊤(line J4).A = Z\, U (I + \Lambda)^{-1/2} U^\top\, G^{-1} F^\top \quad\text{(line J4)}.

Then APA⊤=PaA P A^\top = P^a.

Proof. P=ZZ⊤P = ZZ^\top and F⊤F=IF^\top F = I, so G−1F⊤PFG−1=G−1DG−1=IG^{-1}F^\top P F G^{-1} = G^{-1} D G^{-1} = I. With C=U(I+Λ)−1/2U⊤C = U(I + \Lambda)^{-1/2}U^\top, which is symmetric, APA⊤=ZCCZ⊤=ZU(I+Λ)−1U⊤Z⊤=Z(I+M)−1Z⊤APA^\top = Z C C Z^\top = Z U (I + \Lambda)^{-1} U^\top Z^\top = Z (I + M)^{-1} Z^\top. On the other side,

Pa=ZZ⊤−ZB⊤(BB⊤+R)−1BZ⊤=Z(I−B⊤(BB⊤+R)−1B)Z⊤,P^a = ZZ^\top - Z B^\top (BB^\top + R)^{-1} B Z^\top = Z\bigl(I - B^\top (BB^\top + R)^{-1} B\bigr) Z^\top,

and the Woodbury identity gives I−B⊤(BB⊤+R)−1B=(I+B⊤R−1B)−1=(I+M)−1I - B^\top(BB^\top + R)^{-1}B = (I + B^\top R^{-1} B)^{-1} = (I + M)^{-1}. □\square

GG is invertible because only positive eigenvalues are kept. Anderson (2001, Appendix A) gives this matrix with singular value decompositions, and Grooms (2020) discusses the case where PP is singular, which is the usual case with N≤nN \le n.

Theorem 5 (joint form). For a linear HH and a symmetric positive definite RR, the members xia=xˉa+A(xi−xˉ)x^a_i = \bar x^a + A(x_i - \bar x) of line J6 have the mean xˉa\bar x^a and the sample covariance PaP^a.

Proof. Line J5 computes xˉa=xˉ+PH⊤z\bar x^a = \bar x + PH^\top z with (HPH⊤+R)z=yo−Hxˉ(HPH^\top + R) z = y^o - H\bar x, which is the Kalman mean. The new perturbations are AXAX. Their columns sum to AA times the sum of the columns of XX, which is zero, so the mean is xˉa\bar x^a. Their sample covariance is AXX⊤A⊤/(N−1)=APA⊤=PaAXX^\top A^\top/(N - 1) = APA^\top = P^a by Lemma 4. □\square

Corollary 6 (one scalar observation). If p=1p = 1, the joint form gives the same members as the serial form.

Proof. With H=hH = h (one row) and R=rR = r, B=hZB = hZ is one row, and M=B⊤B/rM = B^\top B/r has the single positive eigenvalue BB⊤/r=hPh⊤/r=s/rBB^\top/r = hPh^\top/r = s/r with the unit eigenvector u=B⊤/∥B∥u = B^\top/\|B\| (if s=0s = 0, then M=0M = 0, A=FF⊤A = FF^\top and AX=XAX = X, which is the skipped update). So C=I+(q−1)uu⊤C = I + (q - 1)uu^\top with q=(1+s/r)−1/2=r/(s+r)q = (1 + s/r)^{-1/2} = \sqrt{r/(s + r)}, and

A=ZG−1F⊤+(q−1)ZB⊤BG−1F⊤s=FF⊤+q−1sPh⊤hFF⊤,A = ZG^{-1}F^\top + (q - 1)\frac{Z B^\top B G^{-1}F^\top}{s} = FF^\top + \frac{q - 1}{s} P h^\top h FF^\top,

because ZB⊤=ZZ⊤h⊤=Ph⊤ZB^\top = ZZ^\top h^\top = Ph^\top and BG−1F⊤=hFF⊤BG^{-1}F^\top = hFF^\top. The columns of XX lie in the range of PP, which is the range of FF, so FF⊤X=XFF^\top X = X and AX=X+q−1sPh⊤hX=X−αKhXAX = X + \frac{q - 1}{s} Ph^\top hX = X - \alpha K hX by the identity in the proof of Lemma 2. The mean is the Kalman mean in both forms, so the members agree. □\square

For more than one observation the joint and the serial members differ in general. The covariance of the analysis fixes the perturbations only up to an orthogonal transform in ensemble space (Tippett et al. 2003), and the two forms make different choices.

With N=2N = 2, x=(−1/2,1/2)x = (-1/\sqrt 2, 1/\sqrt 2), h=1h = 1, r=1r = 1 and yo=1y^o = 1, s=1s = 1, sa=1/2s^a = 1/2 and ya=1/2y^a = 1/2, so both forms return the mean 1/21/2 and the variance 1/21/2.

With localization. If the weights multiply bxb_x and byb_y entry by entry, the proof of Lemma 2 still shows that the serial EAKF makes the same step as the serial EnSRF with the same weights on its gain. The step is then no longer an exact Kalman update, as the EnSRF proof explains, and its use is a heuristic.

A nonlinear HH. The serial form evaluates hh only at line L1 and then updates the predicted observations by regression. The theorems above do not cover this case. Anderson (2003) describes it as a least squares fit of each state value on each observed value.

Termination. The serial form makes pp passes of a finite number of sums over NN members. It skips an observation with s=0s = 0, so line L4 divides only by s>0s > 0 and r>0r > 0, and line L6 by (N−1)s>0(N - 1)s > 0. The joint form calls the Jacobi method twice with a fixed upper limit on the number of sweeps, and solves two linear systems with RR and HPH⊤+RHPH^\top + R, which are positive definite. Both forms return. ■\blacksquare

Complexity

Each pass of the serial loop costs Θ(N(n+p))\Theta(N(n + p)) for lines L6 and L7 and Θ(N)\Theta(N) for the rest, so the analysis costs Θ(pN(n+p))\Theta(pN(n + p)) plus NN applications of HH. With localization only the values with a nonzero weight need work. The extra space is the observation ensemble and the copy of the state ensemble, Θ(N(n+p))\Theta(N(n + p)). The joint form needs the n×nn \times n matrix PP and two eigendecompositions, about Θ(n3+n2(N+p)+p3)\Theta(n^3 + n^2(N + p) + p^3) time and Θ(n2+p2)\Theta(n^2 + p^2) space. It is useful for checks and small problems, not for large models.

Properties

  • No perturbed observations. The update is deterministic, so it adds no sampling noise from random observations.
  • Exact second moments. For a linear HH and no localization, the analysis mean and covariance are the Kalman values for the sample covariance. The serial form needs a diagonal RR for this.
  • Order of the members is kept. Line L5 shifts and shrinks the predicted values without reordering them, so each analysis member stays close to its forecast member.
  • Same members as the serial EnSRF. For a linear HH the two serial filters are the same algorithm written in two ways, also with localization of the gain.
  • A square root filter. The EAKF, the ETKF and the EnSRF give the same mean and covariance. Their members differ by an orthogonal transform in ensemble space (Tippett et al. 2003).
  • Low rank. The analysis stays in the span of the forecast perturbations.

Variants and improvements

  • Other adjustments in observation space. Line L5 can be replaced by any rule that gives the predicted values new values from a scalar posterior. Anderson (2003) uses this freedom: the perturbed observation EnKF is the same two step scheme with a random update in line L5.
  • Localization. Multiply bxb_x and byb_y by a Gaspari-Cohn weight of the distance between the observation and each value. This is covariance localization of the gain.
  • Inflation. The filter is usually run with covariance inflation of the forecast ensemble, as in the measurement above.
  • Joint transform in ensemble space. The ETKF computes an N×NN \times N transform instead of the n×nn \times n matrix AA, which is much cheaper when N≪nN \ll n. The LETKF does this for each grid point.

When to use it

Use the serial EAKF when the observation errors are independent, when the observation operators are nonlinear or complex and should be run only once for each member, and when localization by distance is needed. Its update of the predicted observations makes it easy to add new kinds of observations. For problems with very many observations on a parallel computer the serial loop is a bottleneck, and the LETKF is easier to run in parallel. Use the joint form only for small problems or to check other code.

Pitfalls

  • Forgetting to update the predicted observations (line L7). Without line L7, each later observation uses a prior that does not include the earlier ones, and their information is counted twice.
  • Using updated values in the regression (lines L6 and L7). The coefficients must use the predicted values before line L5 is applied. Using the adjusted values gives the wrong increments.
  • Inverting a singular PP (line J2). With N≤nN \le n the forecast covariance is singular. Keep only the positive eigenvalues, or G−1G^{-1} does not exist.
  • Correlated errors in the serial form. The serial form needs a diagonal RR. For correlated errors, first transform the observations with a square root of RR, or use the joint form.
  • Spread collapse. As with every ensemble filter with few members, the filter underestimates its error. Without inflation or localization it can stop using the data.

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.

ensemble_adjustment_kalman_filter.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/ensemble-adjustment-kalman-filter/. The authors are listed in prov/NP9ZCK.jsonl.

"""Ensemble adjustment Kalman filter (EAKF) of Anderson (2001, 2003).

Notation of Ide, Courtier, Ghil and Lorenc (1997). The forecast ensemble has
N members in R^n; the observations y^o have error variances r_k.

eakf_serial is the two step form of Anderson (2003) used in practice: for
each scalar observation, adjust the ensemble of the predicted observation so
that it has the Gaussian posterior mean and variance, then regress the
increments onto every state value and every other predicted observation.

eakf_joint is the matrix form of Anderson (2001, Appendix A): with
P = F D F^T (the nonzero eigenvalues only), G = D^(1/2) and
G F^T H^T R^-1 H F G = U Lam U^T, the adjustment matrix
A = F G U (I + Lam)^(-1/2) U^T G^-1 F^T maps each forecast perturbation to
an analysis perturbation, and A P A^T is the Kalman analysis covariance.

Costs: eakf_serial O(p N (n + p)); eakf_joint O(n^3 + n^2 (N + p) + p^3) with
a fixed number of Jacobi sweeps.
"""

import math

import scimat


def eakf_serial(ens, yo, h, r_var, loc_state=None, loc_obs=None):
    """Return the analysis ensemble of the serial EAKF (a list of N members).

    h(x) is evaluated once per member. loc_state[k][j] and loc_obs[k][l] are
    optional weights that multiply the regression coefficients.
    """
    N, n, p = len(ens), len(ens[0]), len(yo)
    x = [list(m) for m in ens]
    y = [list(h(m)) for m in ens]  # @line L1
    for k in range(p):  # @line L2
        yk = [y[i][k] for i in range(N)]
        ybar = sum(yk) / N  # @line L3
        s = sum((v - ybar) ** 2 for v in yk) / (N - 1)
        if s == 0.0:
            continue
        sa = 1.0 / (1.0 / s + 1.0 / r_var[k])  # @line L4
        ya = sa * (ybar / s + yo[k] / r_var[k])
        f = math.sqrt(sa / s)
        dy = [ya + f * (v - ybar) - v for v in yk]  # @line L5
        xbar = [sum(x[i][j] for i in range(N)) / N for j in range(n)]  # @line L6
        bx = [sum((x[i][j] - xbar[j]) * (yk[i] - ybar) for i in range(N)) / ((N - 1) * s) for j in range(n)]
        if loc_state is not None:
            bx = [b * w for b, w in zip(bx, loc_state[k])]
        ymean = [sum(y[i][l] for i in range(N)) / N for l in range(p)]  # @line L7
        by = [sum((y[i][l] - ymean[l]) * (yk[i] - ybar) for i in range(N)) / ((N - 1) * s) for l in range(p)]
        if loc_obs is not None:
            by = [b * w for b, w in zip(by, loc_obs[k])]
        for i in range(N):
            for j in range(n):
                x[i][j] += bx[j] * dy[i]
            for l in range(p):
                y[i][l] += by[l] * dy[i]
    return x  # @line L8


def sym_eig(a, tol=1e-14, max_sweeps=60):
    """Return (values, V) with a = V diag(values) V^T, by the cyclic Jacobi method."""
    n = len(a)
    a = [[float(v) for v in row] for row in a]
    v = [[1.0 if i == j else 0.0 for j in range(n)] for i in range(n)]
    for _ in range(max_sweeps):
        off = sum(a[p][q] ** 2 for p in range(n) for q in range(p + 1, n))
        diag = sum(a[p][p] ** 2 for p in range(n))
        if off <= tol * tol * diag or off == 0.0:
            break
        for p in range(n - 1):
            for q in range(p + 1, n):
                apq = a[p][q]
                if apq == 0.0:
                    continue
                theta = (a[q][q] - a[p][p]) / (2.0 * apq)
                t = (1.0 if theta >= 0 else -1.0) / (abs(theta) + math.sqrt(theta * theta + 1.0))
                cs = 1.0 / math.sqrt(t * t + 1.0)
                sn = t * cs
                for k in range(n):
                    akp, akq = a[k][p], a[k][q]
                    a[k][p] = cs * akp - sn * akq
                    a[k][q] = sn * akp + cs * akq
                for k in range(n):
                    apk, aqk = a[p][k], a[q][k]
                    a[p][k] = cs * apk - sn * aqk
                    a[q][k] = sn * apk + cs * aqk
                a[p][q] = 0.0
                a[q][p] = 0.0
                for k in range(n):
                    vkp, vkq = v[k][p], v[k][q]
                    v[k][p] = cs * vkp - sn * vkq
                    v[k][q] = sn * vkp + cs * vkq
    return [a[i][i] for i in range(n)], v


def adjustment_matrix(P, H, R, rel_tol=1e-10):
    """Return A = F G U (I + Lam)^(-1/2) U^T G^-1 F^T for the covariance P (n by n)."""
    n = len(P)
    d, V = sym_eig(P)  # @line J2
    top = max(d) if d else 0.0
    keep = [m for m in range(n) if d[m] > rel_tol * top]
    F = [[V[j][m] for m in keep] for j in range(n)]  # n by r
    g = [math.sqrt(d[m]) for m in keep]
    FG = [[F[j][a] * g[a] for a in range(len(keep))] for j in range(n)]
    B = scimat.matmul(H, FG)  # @line J3
    M = scimat.matmul(scimat.transpose(B), scimat.solve(R, B))
    lam, U = sym_eig(M) if keep else ([], [])
    rr = len(keep)
    core = [[sum(U[a][m] * U[b][m] / math.sqrt(1.0 + lam[m]) for m in range(rr)) for b in range(rr)] for a in range(rr)]
    right = [[F[j][b] / g[b] for b in range(rr)] for j in range(n)]  # F G^-1, so the last factor is right^T
    return scimat.matmul(scimat.matmul(FG, core), scimat.transpose(right))  # @line J4


def eakf_joint(ens, yo, H, R):
    """Return the analysis ensemble of the joint EAKF for a linear H (p by n) and a covariance R."""
    N, n = len(ens), len(ens[0])
    xbar = [sum(x[j] for x in ens) / N for j in range(n)]  # @line J1
    X = [[x[j] - xbar[j] for j in range(n)] for x in ens]
    P = [[sum(X[i][a] * X[i][b] for i in range(N)) / (N - 1) for b in range(n)] for a in range(n)]
    A = adjustment_matrix(P, H, R)
    PHt = scimat.matmul(P, scimat.transpose(H))  # @line J5
    S = scimat.add(scimat.matmul(H, PHt), R)
    z = scimat.solve(S, scimat.sub(yo, scimat.matvec(H, xbar)))
    xa = scimat.add(xbar, scimat.matvec(PHt, z))
    return [scimat.add(xa, scimat.matvec(A, X[i])) for i in range(N)]  # @line J6


def ensemble_moments(ens):
    """Return (mean, P): the ensemble mean and the sample covariance with divisor N - 1."""
    N, n = len(ens), len(ens[0])
    mean = [sum(x[j] for x in ens) / N for j in range(n)]
    P = [[sum((x[a] - mean[a]) * (x[b] - mean[b]) for x in ens) / (N - 1) for b in range(n)] for a in range(n)]
    return mean, P
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_ensemble_adjustment_kalman_filter.py 134 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/ensemble-adjustment-kalman-filter/. The authors are listed in prov/NP9ZCK.jsonl.

import math
import random

import scimat
from ensemble_adjustment_kalman_filter import adjustment_matrix, eakf_joint, eakf_serial, ensemble_moments


def kalman_moments(ens, yo, H, R):
    n = len(ens[0])
    xbar, P = ensemble_moments(ens)
    PHt = scimat.matmul(P, scimat.transpose(H))
    S = scimat.add(scimat.matmul(H, PHt), R)
    K = scimat.transpose(scimat.solve(S, scimat.transpose(PHt)))
    xa = scimat.add(xbar, scimat.matvec(K, scimat.sub(yo, scimat.matvec(H, xbar))))
    Pa = scimat.matmul(scimat.sub(scimat.eye(n), scimat.matmul(K, H)), P)
    return xa, Pa


def close_moments(ens, xa, Pa, tol=1e-9):
    ma, Pe = ensemble_moments(ens)
    for a in range(len(xa)):
        assert abs(ma[a] - xa[a]) < tol * (1 + abs(xa[a]))
        for b in range(len(xa)):
            assert abs(Pe[a][b] - Pa[a][b]) < tol * (1 + abs(Pa[a][b]))


def diag(r):
    return [[r[a] if a == b else 0.0 for b in range(len(r))] for a in range(len(r))]


def test_scalar_check_value():
    s = 1 / math.sqrt(2.0)
    for out in (eakf_serial([[-s], [s]], [1.0], lambda x: [x[0]], [1.0]),
                eakf_joint([[-s], [s]], [1.0], [[1.0]], [[1.0]])):
        mean, P = ensemble_moments(out)
        assert abs(mean[0] - 0.5) < 1e-12
        assert abs(P[0][0] - 0.5) < 1e-12


def test_page_example():
    ens = [[0.0, 1.0], [1.0, 3.0], [2.0, 2.0]]
    out = eakf_serial(ens, [2.0], lambda x: [x[0]], [1 / 3])
    expect = [[5 / 4, 13 / 8], [7 / 4, 27 / 8], [9 / 4, 17 / 8]]
    for a, b in zip(out, expect):
        assert abs(a[0] - b[0]) < 1e-12 and abs(a[1] - b[1]) < 1e-12
    mean, P = ensemble_moments(out)
    assert abs(mean[1] - 19 / 8) < 1e-12
    assert abs(P[1][1] - 13 / 16) < 1e-12


def test_serial_matches_kalman_moments():
    rng = random.Random(41)
    for _ in range(80):
        n, p, N = rng.randint(1, 5), rng.randint(1, 5), rng.randint(2, 8)
        ens = [[rng.gauss(0, 1) for _ in range(n)] for _ in range(N)]
        H = [[rng.uniform(-1, 1) for _ in range(n)] for _ in range(p)]
        r = [rng.uniform(0.1, 2.0) for _ in range(p)]
        yo = [rng.gauss(0, 2) for _ in range(p)]
        out = eakf_serial(ens, yo, lambda x: scimat.matvec(H, x), r)
        xa, Pa = kalman_moments(ens, yo, H, diag(r))
        close_moments(out, xa, Pa)


def test_joint_matches_kalman_moments_with_correlated_R():
    rng = random.Random(42)
    for _ in range(40):
        n, p, N = rng.randint(1, 4), rng.randint(1, 4), rng.randint(2, 8)
        ens = [[rng.gauss(0, 1) for _ in range(n)] for _ in range(N)]
        H = [[rng.uniform(-1, 1) for _ in range(n)] for _ in range(p)]
        L = [[rng.uniform(-1, 1) for _ in range(p)] for _ in range(p)]
        R = scimat.add(scimat.matmul(L, scimat.transpose(L)), scimat.scale(0.3, scimat.eye(p)))
        yo = [rng.gauss(0, 2) for _ in range(p)]
        out = eakf_joint(ens, yo, H, R)
        xa, Pa = kalman_moments(ens, yo, H, R)
        close_moments(out, xa, Pa)


def test_adjustment_matrix_identity():
    # A P A^T equals the Kalman analysis covariance, also when P is singular (N < n + 1).
    rng = random.Random(43)
    n, N, p = 5, 3, 2
    ens = [[rng.gauss(0, 1) for _ in range(n)] for _ in range(N)]
    _, P = ensemble_moments(ens)
    H = [[rng.uniform(-1, 1) for _ in range(n)] for _ in range(p)]
    R = diag([0.5, 2.0])
    A = adjustment_matrix(P, H, R)
    APAt = scimat.matmul(scimat.matmul(A, P), scimat.transpose(A))
    _, Pa = kalman_moments(ens, [0.0, 0.0], H, R)
    for a in range(n):
        for b in range(n):
            assert abs(APAt[a][b] - Pa[a][b]) < 1e-9


def test_one_observation_serial_equals_joint_and_square_root_filter():
    # For one scalar observation the serial EAKF, the joint EAKF and the reduced gain
    # update x' - alpha K h x' of the serial EnSRF give the same members.
    rng = random.Random(44)
    for _ in range(20):
        n, N = rng.randint(1, 4), rng.randint(2, 7)
        ens = [[rng.gauss(0, 1) for _ in range(n)] for _ in range(N)]
        h = [rng.uniform(-1, 1) for _ in range(n)]
        r = rng.uniform(0.2, 2.0)
        a = eakf_serial(ens, [0.3], lambda x: [scimat.dot(h, x)], [r])
        b = eakf_joint(ens, [0.3], [h], [[r]])
        xbar, P = ensemble_moments(ens)
        Ph = scimat.matvec(P, h)
        s = scimat.dot(h, Ph)
        K = [v / (s + r) for v in Ph]
        alpha = 1 / (1 + math.sqrt(r / (s + r)))
        d = 0.3 - scimat.dot(h, xbar)
        for i in range(N):
            xp = scimat.sub(ens[i], xbar)
            hxp = scimat.dot(h, xp)
            c = [xbar[j] + K[j] * d + xp[j] - alpha * K[j] * hxp for j in range(n)]
            for j in range(n):
                assert abs(a[i][j] - c[j]) < 1e-9
                assert abs(b[i][j] - c[j]) < 1e-9


def test_observation_with_no_spread_is_skipped():
    ens = [[1.0, 0.0], [1.0, 2.0]]
    out = eakf_serial(ens, [5.0], lambda x: [x[0]], [1.0])
    assert out == ens


def test_localization_weight_zero_freezes_value():
    rng = random.Random(45)
    ens = [[rng.gauss(0, 1) for _ in range(3)] for _ in range(5)]
    out = eakf_serial(ens, [1.0], lambda x: [x[0]], [0.5], loc_state=[[1.0, 0.3, 0.0]])
    for x, z in zip(ens, out):
        assert z[2] == x[2]

History

Anderson introduced the filter in 2001 for atmospheric models. His paper defined the adjustment matrix and showed in an appendix how to compute it with singular value decompositions. In 2003 he described the serial form as a least squares framework: a scalar update in observation space followed by a regression onto each state value. In the same year Tippett, Anderson, Bishop, Hamill and Whitaker showed that the EAKF, the ETKF and the filter of Whitaker and Hamill are all square root filters.

References

  1. J. L. Anderson, An ensemble adjustment Kalman filter for data assimilation, Monthly Weather Review 129(12) (2001) 2884-2903, the adjustment matrix A, and Appendix A for its existence and its computation with singular value decompositions
  2. J. L. Anderson, A local least squares framework for ensemble filtering, Monthly Weather Review 131(4) (2003) 634-642, the two step update: the scalar update in observation space and the regression onto the state
  3. M. K. Tippett, J. L. Anderson, C. H. Bishop, T. M. Hamill and J. S. Whitaker, Ensemble square root filters, Monthly Weather Review 131(7) (2003) 1485-1490, the EAKF as a square root filter and the nonuniqueness of the square root
  4. I. Grooms, A note on the formulation of the ensemble adjustment Kalman filter, arXiv:2006.02941 (2020), the adjustment matrix when the forecast covariance is singular
  5. E. Kwiatkowski and J. Mandel, Convergence of the square root ensemble Kalman filter in the large ensemble limit, SIAM/ASA Journal on Uncertainty Quantification 3(1) (2015) 1-17, convergence of the EAKF to the Kalman filter as N goes to infinity, for linear models
  6. Geir Evensen, Data Assimilation: The Ensemble Kalman Filter, 2nd edition, Springer, 2009, Chapter 13, Square root analysis schemes
  7. 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