Algorithm Search⌘K

Algorithmresearch

Local particle filter

Also called localized particle filter.

Weights and resamples particles at each grid point with nearby observations only, so the weights need not collapse as the state dimension grows.

Time
Θ(N p + n N q) worst
Space
Θ(N p + n N) extra
Where
N = the number of particles; n = the number of grid points; p = the number of observations; q = the largest number of observations inside the taper of one grid point
Properties
randomized
Origin
Stephen G. Penny, Takemasa Miyoshi, Jonathan Poterjoy, 2016

A local particle filter gives each particle a separate weight at each grid point, computed only from the observations near that point, and resamples each grid point separately. The particle filter with global weights needs a number of particles that grows exponentially with the number of independent observations, because one particle soon takes almost all the weight (see particle filter collapse in high dimensions). With local weights the number of observations that act on a weight is bounded by the size of the taper, so the local weights stay spread out as the state grows. The price is a localization bias, and new particles that are stitched together from parts of different old particles.

In plain words

A particle filter keeps many guesses of the state and scores each guess by how well it fits the measurements. When there are many measurements, one guess almost always fits better than all others in total, and the filter keeps only copies of that one guess. The local filter scores each guess again for each place, with only the measurements near that place. At each place it then keeps the guesses that fit well there. A new guess can take its value at one place from one old guess and its value at another place from a different old guess, so it can fit the measurements at both places.

The problem

Input. Particles x1,…,xNx_1, \ldots, x_N from the forecast, each a vector of values at nn grid points on a ring, and observations (poso,yo,ro)(\mathrm{pos}_o, y_o, r_o), o=1,…,po = 1, \ldots, p: observation oo measures the value at grid point poso\mathrm{pos}_o with Gaussian error of variance ror_o. A taper ρ\rho with a radius: ρ(0)=1\rho(0) = 1, and ρ(d)=0\rho(d) = 0 for large distances dd. Notation of Ide, Courtier, Ghil and Lorenc (1997), with yy for the observations.

Output. New particles x~1,…,x~N\tilde x_1, \ldots, \tilde x_N, where the values at grid point jj are a resample of the old values at jj with the local weights

wi(j)∝exp⁡(−12∑oρ(dist(j,poso)) (yo−xi,poso)2ro).w_i(j) \propto \exp\Big(-\tfrac12\sum_{o} \rho(\mathrm{dist}(j, \mathrm{pos}_o))\,\frac{(y_o - x_{i,\mathrm{pos}_o})^2}{r_o}\Big).

The algorithm

  1. LOCAL-PF-ANALYSIS({x_i}, {(pos_o, y_o, r_o)}, radius, u)
  2. 1n <- number of grid points ; N <- number of particles
  3. 2w_i(j) <- normalized exp(-1/2 sum_o rho(dist(j, pos_o)) (y_o - x_i[pos_o])^2 / r_o)
  4. 3new particles x~_1..x~_N
  5. 4for each grid point j
  6. 5a_j <- systematic resampling of w_.(j) with the points (i + u) / N
  7. 6for i = 1..N
  8. 7x~_i[j] <- x_(a_j(i))[j]
  9. 8return {x~_i}

The same offset uu is used at all grid points, so that neighboring points with similar weights pick the same old particles and the new particles stay smooth where the weights change slowly. In a filter cycle, each particle is first moved by a stochastic model step and the analysis step follows. The taper is the Gaspari-Cohn function here; radius 0 uses only the observations at the point itself.

Example

Two grid points. Take the particles x1=(0,0)x_1 = (0, 0) and x2=(1,1)x_2 = (1, 1), the observations y=(1,0)y = (1, 0) at the points 0 and 1 with r=12r = \tfrac12, radius 0 and u=0.45u = 0.45. At point 0 only y0=1y_0 = 1 acts: particle 1 has the misfit 1/12=21/\tfrac12 = 2 and particle 2 has 0, so the weights are w(0)=(e−1,1)/(1+e−1)=(0.269,0.731)w(0) = (e^{-1}, 1)/(1 + e^{-1}) = (0.269, 0.731). At point 1 the roles are swapped, w(1)=(0.731,0.269)w(1) = (0.731, 0.269). The resampling points are (0+0.45)/2=0.225(0 + 0.45)/2 = 0.225 and (1+0.45)/2=0.725(1 + 0.45)/2 = 0.725. At point 0 they pick particles 1 and 2, because 0.225≤0.269<0.7250.225 \le 0.269 < 0.725. At point 1 both are at most 0.7310.731, so both pick particle 1. The new particles are

x~1=(0,0),x~2=(1,0).\tilde x_1 = (0, 0), \qquad \tilde x_2 = (1, 0).

The new particle (1,0)(1, 0) fits both observations exactly, and neither old particle did. A global filter would give both particles the same weight, since the total misfits are equal, and could only copy whole old particles.

Weight collapse. The prior is N(0,I)N(0, I) with N=100N = 100 particles, and every grid point is observed with error variance 1. The table gives the mean largest weight over 10 cases, for the global weights and for the local weights with a Gaspari-Cohn taper of half-width 2 (a measurement):

nn global local, mean over the grid points
10 0.37 0.08
40 0.69 0.09
160 0.83 0.09

The largest global weight moves toward 1 as nn grows. The largest local weight does not change with nn.

A cycled twin. Forty independent components follow xk=0.9xk−1+ηkx_k = 0.9x_{k-1} + \eta_k with ηk∼N(0,0.5)\eta_k \sim N(0, 0.5), every component is observed with error variance 0.5 at each of 20 cycles, and N=50N = 50. The root mean square error of the particle mean over the cycles 6 to 20 and 5 cases is 0.56 for the local filter with radius 0, 1.34 for the global bootstrap filter, and 0.55 for the exact Kalman filter (a measurement). With no assimilation the error is about 0.5/0.19=1.62\sqrt{0.5/0.19} = 1.62.

Correctness

The proof shows four facts. Systematic resampling gives each particle ⌊Nwk⌋\lfloor Nw_k\rfloor or ⌈Nwk⌉\lceil Nw_k\rceil copies, NwkNw_k on average. The values at each grid point are a resample of the local weighted marginal. With the taper equal to 1 everywhere, the step is the global bootstrap analysis. For independent components with radius 0, the local weights are the exact importance weights of the marginal posteriors, which depend only on the local observations (all theorems). For correlated states with a taper of positive radius, the local filter is a heuristic with a bias from the localization. Rebeschini and van Handel (2015) prove dimension-free error bounds for a related block particle filter under a decay of correlations condition. The tests check the resampling against a brute force inverse of the cumulative weights, the infinite radius against a separate global bootstrap step, the local weighted mean against the Kalman filter mean, and the example.

Proof: The local particle filter analysis resamples each local weighted marginal, and it is the global bootstrap step when the taper is 1full

Setting. The particles x1,…,xN∈Rnx_1, \ldots, x_N \in \mathbb R^n are given, and the observations are (poso,yo,ro)(\mathrm{pos}_o, y_o, r_o) for o=1,…,po = 1, \ldots, p. Line L2 computes, at each grid point jj, the weights

wi(j)=exp⁡(ℓi(j))∑mexp⁡(ℓm(j)),ℓi(j)=−12∑o=1pρjo (yo−xi,poso)2ro,w_i(j) = \frac{\exp(\ell_i(j))}{\sum_m \exp(\ell_m(j))}, \qquad \ell_i(j) = -\tfrac12\sum_{o=1}^p \rho_{jo}\,\frac{(y_o - x_{i,\mathrm{pos}_o})^2}{r_o},

with the taper values ρjo∈[0,1]\rho_{jo} \in [0, 1]. Lines L4 to L7 apply systematic resampling with one offset u∈[0,1)u \in [0, 1) at every grid point: grid point jj picks, for i=0,…,N−1i = 0, \ldots, N - 1, the particle aj(i)a_j(i) whose interval of cumulative weight (ck−1(j),ck(j)](c_{k-1}(j), c_k(j)] holds ti=(i+u)/Nt_i = (i + u)/N, and the new particle ii has the components x~i,j=xaj(i),j\tilde x_{i,j} = x_{a_j(i),j}.

Lemma 1 (systematic resampling). For fixed weights ww, the number of copies nkn_k of particle kk satisfies ⌊Nwk⌋≤nk≤⌈Nwk⌉\lfloor Nw_k\rfloor \le n_k \le \lceil Nw_k\rceil, and if uu is uniform on [0,1)[0, 1) then E[nk]=Nwk\mathbb E[n_k] = Nw_k.

Proof. nkn_k is the number of points ti=(i+u)/Nt_i = (i + u)/N in the interval (ck−1,ck](c_{k-1}, c_k] of length wkw_k. The points are spaced 1/N1/N apart, so an interval of length wkw_k holds ⌊Nwk⌋\lfloor Nw_k\rfloor or ⌈Nwk⌉\lceil Nw_k\rceil of them. As uu runs over [0,1)[0, 1), the point set {ti}\{t_i\} is a uniform random shift of the grid {i/N}\{i/N\}, so each point of (0,1](0, 1] is covered by exactly one tit_i with density NN, and E[nk]=N length(ck−1,ck]=Nwk\mathbb E[n_k] = N\,\mathrm{length}(c_{k-1}, c_k] = Nw_k. □\square

Theorem 2 (local marginals). At every grid point jj, the values x~1,j,…,x~N,j\tilde x_{1,j}, \ldots, \tilde x_{N,j} are a systematic resample of the weighted sample {(xi,j,wi(j))}\{(x_{i,j}, w_i(j))\}, so for any function ff and uu uniform,

E[1N∑i=1Nf(x~i,j)]=∑i=1Nwi(j)f(xi,j).\mathbb E\Big[\frac1N\sum_{i=1}^N f(\tilde x_{i,j})\Big] = \sum_{i=1}^N w_i(j) f(x_{i,j}) .

Proof. By line L7, x~i,j=xaj(i),j\tilde x_{i,j} = x_{a_j(i),j}, so 1N∑if(x~i,j)=1N∑knk(j)f(xk,j)\frac1N\sum_i f(\tilde x_{i,j}) = \frac1N\sum_k n_k(j) f(x_{k,j}), and Lemma 1 gives the expectation. □\square

Theorem 3 (no taper). If ρjo=1\rho_{jo} = 1 for all jj and oo (radius None), the step is the analysis step of the bootstrap particle filter with systematic resampling.

Proof. Then ℓi(j)=−12∑o(yo−xi,poso)2/ro\ell_i(j) = -\tfrac12\sum_o (y_o - x_{i,\mathrm{pos}_o})^2/r_o for every jj, which is the log likelihood of particle ii under independent Gaussian observation errors, up to a constant. All grid points have the same weights, so with the same uu they pick the same indices aj(i)=a(i)a_j(i) = a(i), and x~i=xa(i)\tilde x_i = x_{a(i)} is the whole particle a(i)a(i). This is weighting by the likelihood and systematic resampling of whole particles. □\square

Theorem 4 (exact local weights). Let the prior have independent components, so that the particles have independent components with these marginals, let each observation measure one component, and let ρjo=1\rho_{jo} = 1 if poso=j\mathrm{pos}_o = j and 0 otherwise (radius 0). Then wi(j)w_i(j) is the self-normalized importance weight of xi,jx_{i,j} for the marginal posterior p(xj∣y)∝p(xj)∏o: poso=jp(yo∣xj)p(x_j \mid y) \propto p(x_j)\prod_{o:\,\mathrm{pos}_o = j} p(y_o \mid x_j), which depends only on the observations of point jj.

Proof. Under these assumptions the posterior factorizes over the components, so the marginal posterior of xjx_j is the prior marginal times the likelihood of the observations at jj. The local log weight ℓi(j)\ell_i(j) is exactly the log of that likelihood at xi,jx_{i,j}, up to a constant. □\square

So in this case the variance of the local log weights at point jj depends on the number of observations at jj, not on nn, and the local weights do not collapse as nn grows, while the global weights of Theorem 3 do (see particle filter collapse in high dimensions). With correlated components, a taper of positive radius is a heuristic: it ignores the information that far observations carry through the correlations, and the new particles mix components of different old particles, which can break balances between neighboring grid points. Rebeschini and van Handel (2015) prove dimension-free error bounds for a block particle filter under a decay of correlations condition, with a bias that comes from the localization.

Termination. Line L2 takes Θ(Np)\Theta(Np) steps for the misfits and Θ(nNq)\Theta(nNq) steps for the local sums, where qq is the largest number of observations with ρjo>0\rho_{jo} > 0 at one grid point. Each systematic resampling in line L5 makes one pass over the NN points and the NN cumulative weights, since both indices only increase, so lines L4 to L7 take Θ(nN)\Theta(nN) steps. Every loop is bounded, and the step ends.

Summary. The local analysis is a systematic resample of the local weighted marginal at each grid point (Theorem 2). It is the global bootstrap step when the taper is 1 (Theorem 3), and for independent components with radius 0 its weights are the exact marginal importance weights (Theorem 4). The tests check Lemma 1 against a brute force inverse of the cumulative weights, Theorem 3 by equality with a separate global bootstrap step, Theorem 4 by the weighted mean against the Kalman filter mean, and the page example. ■\blacksquare

Complexity

The misfits of all particles to all observations cost Θ(Np)\Theta(Np). The local log weights at one grid point sum over at most qq observations for each particle, Θ(nNq)\Theta(nNq) in total. Each systematic resampling is one pass over NN points and NN cumulative weights, Θ(nN)\Theta(nN) in total. So the time is Θ(Np+nNq)\Theta(Np + nNq) and the memory, for the misfits and the new particles, is Θ(Np+nN)\Theta(Np + nN). Without a taper q=pq = p, and the cost is nn times that of a global step, which computes the weights once.

Properties

  • No Gaussian assumption. The weights use the full likelihood, so the analysis can represent skewed and multimodal local distributions, unlike the ensemble Kalman filter.
  • Local weights do not collapse with nn. The number of observations in a local weight is bounded by qq, and the local largest weight stays the same as nn grows (a theorem for independent components, a measurement above).
  • Global limit. With an infinite radius and one offset uu, the step is the global bootstrap analysis (a theorem).
  • Stitched particles. A new particle takes its values at different points from different old particles. This can break physical balances and make discontinuities where the weights change fast.
  • Localization bias. Observations beyond the taper are ignored, even if the state is correlated over longer distances.

Variants and improvements

  • Weight smoothing. Penny and Miyoshi (2016) smooth the local weights over neighboring grid points to reduce the discontinuities of the stitched particles.
  • Merging with the prior. Poterjoy (2016) updates the particles as a mix of the resampled particles and the prior particles, with a weight that goes from the resampled value at the observation to the prior value far away, and processes the observations one at a time.
  • Block particle filter. Divide the grid into blocks and resample each block with the observations inside it, as analyzed by Rebeschini and van Handel (2015).
  • Hybrids with the LETKF. Use a particle filter step for part of the update and the LETKF for the rest, or a tempered sequence of local steps.
  • Optimal transport resampling. Replace the random resampling by a deterministic map from the weighted to the equally weighted particles, which keeps the new particles closer to the old ones.

When to use it

Use a local particle filter when the state is large, the errors are not Gaussian, and the correlations decay with distance, for example in geophysical models with strongly nonlinear observation operators. If the errors are close to Gaussian, the LETKF is cheaper and usually more accurate with the same number of members. If the state is small, a global particle filter with enough particles has no localization bias.

Pitfalls

  • A different offset at each grid point (line L5). Then neighboring points pick unrelated particles even when their weights are equal, and the new particles are noise from point to point.
  • Weights without a shift (line L2). The log weights can be very negative; subtract their maximum before taking exponentials, or all weights underflow to zero.
  • Too large a radius (line L2). The local weights then see many observations and collapse like the global weights.
  • No model noise or jitter. After resampling, many particles are equal at a grid point. Without stochastic model errors or a small jitter, the particle set loses its spread over the cycles.
  • Discontinuous new particles (line L7). Where the weights change fast, stitched particles can violate physical balances and excite spurious waves in the next forecast; smooth the weights or merge with the prior.

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.

local_particle_filter.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/local-particle-filter/. The authors are listed in prov/7NZNER.jsonl.

"""Local particle filter: an analysis step with local weights and local resampling.

The state has n grid points on a ring. An observation o measures one grid
point pos_o with the value y_o and the error variance r_o. Particle i
gets at grid point j the local log weight

    log w_i(j) = -1/2 sum_o rho(dist(j, pos_o)) (y_o - x_i[pos_o])^2 / r_o,

where rho is a taper that is 1 at distance 0 and 0 far away, as in the
observation localization of the LETKF. At each grid point the weights are
normalized and resampled with systematic resampling. One offset u is used
at all grid points, so neighboring points with similar weights pick the
same particles. Component j of the new particle i is component j of the
old particle that grid point j picks.

With radius None the taper is 1 everywhere, all grid points have the same
weights and pick the same particles, and the step is the analysis step of
the global bootstrap particle filter with systematic resampling.
"""

import math


def gaspari_cohn(r, c):
    """Return the Gaspari-Cohn fifth order taper at distance r for the half-width c (zero beyond 2c)."""
    z = abs(r) / c
    if z <= 1.0:
        return -0.25 * z**5 + 0.5 * z**4 + 0.625 * z**3 - (5.0 / 3.0) * z**2 + 1.0
    if z <= 2.0:
        return z**5 / 12.0 - 0.5 * z**4 + 0.625 * z**3 + (5.0 / 3.0) * z**2 - 5.0 * z + 4.0 - 2.0 / (3.0 * z)
    return 0.0


def taper(d, radius):
    """Return rho(d): 1 for radius None, the indicator of d = 0 for radius 0, else Gaspari-Cohn."""
    if radius is None:
        return 1.0
    if radius == 0:
        return 1.0 if d == 0 else 0.0
    return gaspari_cohn(d, radius)


def ring_distance(j, k, n):
    """Return the distance between the grid points j and k on a ring of n points."""
    d = abs(j - k) % n
    return min(d, n - d)


def normalize(logw):
    """Return the normalized weights exp(logw) / sum, shifted by the maximum to avoid underflow."""
    top = max(logw)
    w = [math.exp(v - top) for v in logw]
    s = sum(w)
    return [v / s for v in w]


def systematic_resample(w, u):
    """Return N indices: index i is the particle whose cumulative weight interval holds (i + u) / N."""
    N = len(w)
    out = []
    c = w[0]
    k = 0
    for i in range(N):
        t = (i + u) / N
        while t > c and k < N - 1:
            k += 1
            c += w[k]
        out.append(k)
    return out


def local_weights(particles, obs, radius):
    """Return W with W[j] the normalized local weights of all particles at grid point j."""
    n = len(particles[0])
    N = len(particles)
    misfit = [[(y - x[pos]) ** 2 / r for pos, y, r in obs] for x in particles]
    W = []
    for j in range(n):
        rho = [taper(ring_distance(j, pos, n), radius) for pos, y, r in obs]
        near = [o for o in range(len(obs)) if rho[o] > 0.0]
        logw = [-0.5 * sum(rho[o] * misfit[i][o] for o in near) for i in range(N)]
        W.append(normalize(logw))
    return W


def local_pf_analysis(particles, obs, radius, u):
    """Return the new particles of one local particle filter analysis with the offset u in [0, 1)."""
    n = len(particles[0])  # @line L1
    N = len(particles)
    W = local_weights(particles, obs, radius)  # @line L2
    new = [[0.0] * n for _ in range(N)]  # @line L3
    for j in range(n):  # @line L4
        pick = systematic_resample(W[j], u)  # @line L5
        for i in range(N):  # @line L6
            new[i][j] = particles[pick[i]][j]  # @line L7
    return new  # @line L8


def local_particle_filter(particles, step, observations, radius, rng):
    """Cycle forecast and analysis. observations[k] is the list of (pos, y, r) at time k = 1, 2, ...

    step(x, rng) is one stochastic model step. Return the list of particle sets after each analysis.
    """
    history = []
    for obs in observations:
        particles = [step(x, rng) for x in particles]
        particles = local_pf_analysis(particles, obs, radius, rng.random())
        history.append(particles)
    return history
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_local_particle_filter.py 130 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/local-particle-filter/. The authors are listed in prov/7NZNER.jsonl.

import math
import random

from local_particle_filter import (
    local_particle_filter,
    local_pf_analysis,
    local_weights,
    normalize,
    systematic_resample,
)


def global_bootstrap_analysis(particles, obs, u):
    """Reference: global weights from all observations, then systematic resampling of whole particles."""
    logw = [-0.5 * sum((y - x[pos]) ** 2 / r for pos, y, r in obs) for x in particles]
    w = normalize(logw)
    N = len(particles)
    out = []
    for i in range(N):
        t = (i + u) / N
        k = 0
        while k < N - 1 and sum(w[: k + 1]) < t:
            k += 1
        out.append(list(particles[k]))
    return out


def test_page_example():
    # Particles (0, 0) and (1, 1), y = (1, 0), r = 1/2, radius 0 and u = 0.45: the new particles are (0, 0) and (1, 0).
    obs = [(0, 1.0, 0.5), (1, 0.0, 0.5)]
    W = local_weights([[0.0, 0.0], [1.0, 1.0]], obs, 0)
    small = math.exp(-1.0) / (1.0 + math.exp(-1.0))
    assert abs(W[0][0] - small) < 1e-12 and abs(W[1][1] - small) < 1e-12
    new = local_pf_analysis([[0.0, 0.0], [1.0, 1.0]], obs, 0, 0.45)
    assert new == [[0.0, 0.0], [1.0, 0.0]]


def test_systematic_resampling_against_inverse_cdf():
    rng = random.Random(2)
    for _ in range(200):
        N = rng.randint(1, 12)
        w = normalize([rng.gauss(0, 2) for _ in range(N)])
        u = rng.random()
        pick = systematic_resample(w, u)
        for i, k in enumerate(pick):
            t = (i + u) / N
            ref = next((m for m in range(N) if sum(w[: m + 1]) >= t), N - 1)
            assert k == ref
        for m in range(N):
            assert math.floor(N * w[m]) - 1e-9 <= pick.count(m) <= math.ceil(N * w[m]) + 1e-9


def test_infinite_radius_is_global_bootstrap_filter():
    rng = random.Random(9)
    n, N = 6, 15
    particles = [[rng.gauss(0, 1) for _ in range(n)] for _ in range(N)]
    obs = [(j, rng.gauss(0, 1), 0.7) for j in (0, 2, 3, 5)]
    for u in (0.0, 0.31, 0.77):
        assert local_pf_analysis(particles, obs, None, u) == global_bootstrap_analysis(particles, obs, u)


def test_local_weighted_mean_matches_kalman_filter():
    # Independent N(0, 1) components, each observed with r = 1/2: the posterior mean is y / 1.5 at every point.
    rng = random.Random(4)
    n, N = 6, 4000
    particles = [[rng.gauss(0, 1) for _ in range(n)] for _ in range(N)]
    y = [rng.gauss(0, 1.2) for _ in range(n)]
    W = local_weights(particles, [(j, y[j], 0.5) for j in range(n)], 0)
    for j in range(n):
        mean = sum(W[j][i] * particles[i][j] for i in range(N))
        assert abs(mean - y[j] / 1.5) < 0.05


def run_twin(radius, seeds):
    a, q, R = 0.9, 0.5, 0.5
    n, N, T = 40, 50, 20

    def step(x, rng):
        return [a * v + math.sqrt(q) * rng.gauss(0, 1) for v in x]

    pf = kf = 0.0
    for s in seeds:
        rng, trng = random.Random(7 + s), random.Random(70 + s)
        truth = [trng.gauss(0, 1) for _ in range(n)]
        observations, states = [], []
        for _ in range(T):
            truth = [a * v + math.sqrt(q) * trng.gauss(0, 1) for v in truth]
            states.append(truth)
            observations.append([(j, truth[j] + math.sqrt(R) * trng.gauss(0, 1), R) for j in range(n)])
        history = local_particle_filter([[rng.gauss(0, 1) for _ in range(n)] for _ in range(N)], step, observations, radius, rng)
        m, v = [0.0] * n, [1.0] * n
        for k in range(T):
            m = [a * x for x in m]
            v = [a * a * x + q for x in v]
            g = [x / (x + R) for x in v]
            m = [mi + gi * (o[1] - mi) for mi, gi, o in zip(m, g, observations[k])]
            v = [(1 - gi) * x for gi, x in zip(g, v)]
            if k >= 5:
                mean = [sum(p[j] for p in history[k]) / N for j in range(n)]
                pf += math.sqrt(sum((mean[j] - states[k][j]) ** 2 for j in range(n)) / n)
                kf += math.sqrt(sum((m[j] - states[k][j]) ** 2 for j in range(n)) / n)
    return pf / kf


def test_cycled_twin_local_tracks_kalman_filter_global_does_not():
    # 40 independent AR(1) components, 50 particles: a measurement, not a theorem.
    assert run_twin(0, range(3)) < 1.1
    assert run_twin(None, range(3)) > 1.8


def test_weight_collapse_grows_with_dimension_only_for_global_weights():
    N = 100
    result = {}
    for n in (10, 40, 160):
        g_max = l_max = 0.0
        for s in range(10):
            rng = random.Random(1000 * n + s)
            particles = [[rng.gauss(0, 1) for _ in range(n)] for _ in range(N)]
            obs = [(j, rng.gauss(0, 1) + rng.gauss(0, 1), 1.0) for j in range(n)]
            g = normalize([-0.5 * sum((y - x[p]) ** 2 / r for p, y, r in obs) for x in particles])
            W = local_weights(particles, obs, 2)
            g_max += max(g) / 10
            l_max += sum(max(w) for w in W) / n / 10
        result[n] = (g_max, l_max)
    assert result[10][0] < result[40][0] < result[160][0]
    assert result[160][0] > 0.7
    assert all(l < 0.15 for _, l in result.values())

History

Snyder, Bengtsson, Bickel and Anderson (2008) showed that the global particle filter needs a number of particles that grows exponentially with the variance of the log likelihood, which grows with the number of observations, and so cannot work for weather models. Rebeschini and van Handel (2015) proved that a block particle filter can have errors that do not depend on the dimension under a decay of correlations condition. In 2016, Penny and Miyoshi gave a local particle filter that weights and resamples at each grid point, and Poterjoy gave a localized particle filter that merges resampled and prior particles. van Leeuwen and coworkers (2019) review these and other methods for high-dimensional geoscience problems.

References

  1. S. G. Penny and T. Miyoshi, A local particle filter for high-dimensional geophysical systems, Nonlinear Processes in Geophysics 23 (2016) 391-405, the local weights and the resampling at each grid point
  2. J. Poterjoy, A localized particle filter for high-dimensional nonlinear systems, Monthly Weather Review 144(1) (2016) 59-76, the localized update that merges resampled and prior particles
  3. P. Rebeschini and R. van Handel, Can local particle filters beat the curse of dimensionality?, Annals of Applied Probability 25(5) (2015) 2809-2866, the dimension-free error bounds of the block particle filter under decay of correlations
  4. C. Snyder, T. Bengtsson, P. Bickel and J. Anderson, Obstacles to high-dimensional particle filtering, Monthly Weather Review 136(12) (2008) 4629-4640, the collapse of the global weights that motivates localization
  5. P. J. van Leeuwen, H. R. Künsch, L. Nerger, R. Potthast and S. Reich, Particle filters for high-dimensional geoscience applications, a review, Quarterly Journal of the Royal Meteorological Society 145(723) (2019) 2335-2365, the survey of localized particle filters and their problems

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