Algorithm Search⌘K

Algorithmresearch

ABC sequential Monte Carlo

Also called ABC-SMC, ABC population Monte Carlo.

Runs ABC over a falling sequence of tolerances, moving and reweighting a population of particles, so far fewer simulations are wasted than in rejection ABC.

Time
Θ(T (N^2 + N C / A)) expected
Space
Θ(N) extra
Where
A = the smallest acceptance rate over the generations; C = the cost of one simulation; N = the number of particles; T = the number of generations
Properties
randomizednot exactofflineiterative
Origin
Mark A. Beaumont, Jean Marie Cornuet, Jean Michel Marin, Christian P. Robert, Scott A. Sisson, Tina Toni, 2009

ABC sequential Monte Carlo runs approximate Bayesian computation on a population of NN particles through a falling sequence of tolerances ε1>ε2>⋯>εT\varepsilon_1 > \varepsilon_2 > \cdots > \varepsilon_T. The first generation is the ABC rejection algorithm at a loose tolerance. Each later generation draws a particle from the previous one, moves it by a random kernel, simulates data, and keeps the moved particle when the summaries are within the new tolerance. Proposals then come from near the current approximate posterior instead of from the prior, so far fewer simulations are wasted. The moved particles do not follow the prior any more, so each gets the importance weight π(θ)/∑jWjK(θ∣θj)\pi(\theta)/\sum_j W_j K(\theta \mid \theta_j) of Beaumont, Cornuet, Marin and Robert (2009). With these weights, the population of generation tt targets the εt\varepsilon_t-posterior for any previous population.

In plain words

Searching for the settings of a simulator that reproduce the real data, ABC rejection guesses blindly from the prior every time, so a strict match is rare. This method starts with a loose match, which is easy, and keeps a crowd of settings that pass it. Then it tightens the match step by step. At each step it picks a setting from the crowd, nudges it a little, and tests the nudged setting against the stricter match. Most guesses now land in a good region, so fewer simulations are wasted. The crowd was built by nudging, not by guessing from the prior, so some regions are now visited too often. Each setting therefore gets a weight that undoes this. Without the weights, the answer is too narrow.

The problem

Input. A proper prior density π\pi that can be sampled and evaluated; a simulator for Y∼f(⋅∣θ)Y \sim f(\cdot \mid \theta); the observed summaries sobs=S(x)s_{\mathrm{obs}} = S(x), a distance ρ\rho, and tolerances ε1≥⋯≥εT\varepsilon_1 \ge \cdots \ge \varepsilon_T; the number NN of particles.

Output. Particles θ1,…,θN\theta_1, \ldots, \theta_N with weights W1,…,WNW_1, \ldots, W_N whose weighted mean of any function hh estimates the mean of hh under the εT\varepsilon_T-posterior πεT(θ)∝π(θ) Pθ(ρ(S(Y),sobs)≤εT)\pi_{\varepsilon_T}(\theta) \propto \pi(\theta)\,P_\theta(\rho(S(Y), s_{\mathrm{obs}}) \le \varepsilon_T).

The algorithm

  1. ABC-SMC(π, simulator, S, s_obs, ρ, ε₁ ≥ … ≥ ε_T, N)
  2. 1run ABC rejection at ε₁ to get θ₁..θ_N; Wⱼ ← 1/N
  3. 2s² ← 2 · (weighted variance of θ₁..θ_N under W) ▷ the kernel K(·|θ') = N(θ', s²)
  4. 3for t ← 2 to T
  5. 4for i ← 1 to N
  6. 5repeat
  7. 6pick j with probability Wⱼ; θ* ← θⱼ + N(0, s²)
  8. 7if π(θ*) > 0 then Y ← a data set simulated from f(· | θ*)
  9. 8until π(θ*) > 0 and ρ(S(Y), s_obs) ≤ ε_t
  10. 9θᵢ' ← θ*; wᵢ ← π(θ*) / Σⱼ Wⱼ K(θ* | θⱼ)
  11. 10θ ← θ'; W ← w / Σᵢ wᵢ; recompute s² as in L2
  12. 11return θ₁..θ_N and W₁..W_N

L1 is ABC rejection with a loose tolerance, which accepts often. L2 sets the kernel variance to twice the weighted variance of the population, the choice of Beaumont et al. (2009): wide enough to explore, narrow enough to accept often. L6 draws from the mixture gt(θ)=∑jWjK(θ∣θj)g_t(\theta) = \sum_j W_j K(\theta \mid \theta_j) of kernels centred at the particles. L7 skips the simulation when the prior is zero, for example outside [0,1][0, 1] for a probability. L8 is the ABC test at the new tolerance. L9 is the importance sampling weight: target π aεt\pi\,a_{\varepsilon_t}, proposal gt aεtg_t\,a_{\varepsilon_t}, and the unknown acceptance probability aεta_{\varepsilon_t} cancels. L9 costs NN kernel evaluations per particle. L10 normalizes the weights and updates the kernel. The effective sample size of the weights, 1/∑iWi21/\sum_i W_i^2, measures how much the weights vary.

Example

Trace with four particles. 66 successes in 2020 Bernoulli trials, uniform prior on pp, SS = the number of successes, ρ(u,v)=∣u−v∣\rho(u, v) = |u - v|, tolerances (3,1)(3, 1), random.Random(8). Generation 1 (L1) needs 66 simulations and keeps 0.2267,0.2439,0.2317,0.35140.2267, 0.2439, 0.2317, 0.3514 with equal weights. L2 gives s=0.0724s = 0.0724. Generation 2 needs 99 simulations:

new particle θi′\theta_i' 0.2985 0.3659 0.3708 0.1851
normalized weight WiW_i 0.1722 0.3075 0.3247 0.1956

The three old particles near 0.230.23 make the kernel mixture g2g_2 large there. New particles far from that cluster, at 0.370.37 and 0.190.19, have small g2g_2 and get large weights; 0.29850.2985, close to the cluster, gets the smallest weight.

A full run. Same model, N=500N = 500, tolerances (6,3,1,0)(6, 3, 1, 0), random.Random(2). The last tolerance is 00 and the summary is sufficient, so the target is the exact posterior Beta(7, 15), with mean 0.31820.3182 and variance 0.0094320.009432.

generation εt\varepsilon_t kernel ss simulations acceptance ESS weighted mean weighted variance
1 6 820 0.610 500 0.3171 0.038169
2 3 0.276 1161 0.431 495 0.3209 0.018306
3 1 0.191 2186 0.229 493 0.3168 0.009867
4 0 0.140 5071 0.099 476 0.3196 0.009897

The run uses 92389238 simulations in total. ABC rejection at ε=0\varepsilon = 0 keeps one proposal in 2121 here, so 500500 draws cost about 1050010500 simulations. The gain is small in this problem because the uniform prior is not much wider than the posterior. With 3030 successes in 100100 trials and tolerances (30,15,8,4,2,1,0)(30, 15, 8, 4, 2, 1, 0), ten runs with N=500N = 500 use 2343423434 simulations on average, against 5050050500 for rejection.

Dropping the weights. Replace wiw_i in L9 by 11. Over ten runs each, the mean of the final weighted variance is 0.0090040.009004 with the weights and 0.0070250.007025 without them, against the exact 0.0094320.009432: without the weights the answer is 2525 percent too narrow. With 100100 trials it is 0.0020420.002042 with the weights, 0.0013470.001347 without, and 0.0020540.002054 exact.

Correctness

The full proof is in proofs/correctness.md. It proves:

  1. Generation 1 follows the ε1\varepsilon_1-posterior, by the proof for ABC rejection.
  2. The proposal law. Given the previous population, the kept particles of generation tt are independent with density proportional to gt(θ)1{π(θ)>0}aεt(θ)g_t(\theta)\mathbf{1}\{\pi(\theta) > 0\}a_{\varepsilon_t}(\theta).
  3. The weight identity. With w=π/gtw = \pi/g_t, Eqt[wh]/Eqt[w]=Eπεt[h]\mathbb{E}_{q_t}[wh]/\mathbb{E}_{q_t}[w] = \mathbb{E}_{\pi_{\varepsilon_t}}[h] for every integrable hh, whatever the previous population is. The key invariant: at every generation, the weighted population is an importance sample for πεt\pi_{\varepsilon_t}.
  4. Consistency of the weighted mean for a fixed previous population as the number of new particles grows, by the law of large numbers.
  5. Equal weights are wrong. Without L9 the population targets qtq_t, whose ratio to πεt\pi_{\varepsilon_t} is proportional to gt/πg_t/\pi.

What is proved and what is measured: items 1 to 5 are exact. The behaviour of all generations together as NN grows, and the error at a fixed NN, are not proved on this page; the tables measure them against the exact posterior. The tests check item 3 in rational arithmetic on 500500 random finite models, and the weighted distribution of the final population against Beta(7, 15) with a Kolmogorov-Smirnov bound of 2.5/ESS2.5/\sqrt{\mathrm{ESS}}. That bound is a working tolerance, since weighted samples do not follow the usual Kolmogorov-Smirnov law.

Proof: The importance weights of ABC sequential Monte Carlofull

Setting. π\pi is a prior density on Θ⊆Rd\Theta \subseteq \mathbb{R}^d. For a tolerance ε\varepsilon, write aε(θ)=Pθ(ρ(S(Y),sobs)≤ε)a_\varepsilon(\theta) = P_\theta(\rho(S(Y), s_{\mathrm{obs}}) \le \varepsilon) and let

πε(θ)=π(θ) aε(θ)Aε,Aε=∫π aε>0,\pi_\varepsilon(\theta) = \frac{\pi(\theta)\, a_\varepsilon(\theta)}{A_\varepsilon}, \qquad A_\varepsilon = \int \pi\, a_\varepsilon > 0,

be the ε\varepsilon-posterior. The tolerances are ε1≥ε2≥⋯≥εT\varepsilon_1 \ge \varepsilon_2 \ge \cdots \ge \varepsilon_T. At generation t≥2t \ge 2 the previous population is a fixed set of particles θ1,…,θN\theta_1, \ldots, \theta_N with weights Wj>0W_j > 0, ∑jWj=1\sum_j W_j = 1, and Kt(⋅∣θ′)K_t(\cdot \mid \theta') is a transition density, for example the normal density with mean θ′\theta' and variance st2s_t^2. The mixture

gt(θ)=∑j=1NWj Kt(θ∣θj)g_t(\theta) = \sum_{j=1}^N W_j\, K_t(\theta \mid \theta_j)

is the density of a proposal on lines L6 and L7.

Claim 1: generation 1

The particles of generation 1 are independent draws from πε1\pi_{\varepsilon_1}, with equal weights.

Proof. Line L1 is the ABC rejection algorithm at tolerance ε1\varepsilon_1; the law of its kept values is πε1\pi_{\varepsilon_1}, with independence, by Claim 1 of the proof on the ABC rejection algorithm page. ■\blacksquare

Claim 2: the law of an accepted proposal

Given the previous population, the new particles θ1∗,…,θN∗\theta_1^*, \ldots, \theta_N^* of generation tt are independent with density

qt(θ)=gt(θ) 1{π(θ)>0} aεt(θ)ct,ct=∫gt 1{π>0} aεt,q_t(\theta) = \frac{g_t(\theta)\, \mathbf{1}\{\pi(\theta) > 0\}\, a_{\varepsilon_t}(\theta)}{c_t}, \qquad c_t = \int g_t\, \mathbf{1}\{\pi > 0\}\, a_{\varepsilon_t},

provided ct>0c_t > 0.

Proof. One attempt on lines L6 to L8 draws jj with probability WjW_j and then θ∗∼Kt(⋅∣θj)\theta^* \sim K_t(\cdot \mid \theta_j), so θ∗\theta^* has density gtg_t. It is kept with probability 1{π(θ∗)>0} aεt(θ∗)\mathbf{1}\{\pi(\theta^*) > 0\}\, a_{\varepsilon_t}(\theta^*), using fresh simulations. As in rejection sampling, for a set BB, P(θ∗∈B and kept)=∫Bgt1{π>0}aεtP(\theta^* \in B \text{ and kept}) = \int_B g_t \mathbf{1}\{\pi > 0\} a_{\varepsilon_t}, so a kept value has density qtq_t. Attempts are independent given the previous population, so the kept values are independent and identically distributed. ■\blacksquare

Claim 3: the weights correct the proposal exactly

Assume gt(θ)>0g_t(\theta) > 0 wherever π(θ)aεt(θ)>0\pi(\theta)a_{\varepsilon_t}(\theta) > 0 (true for a normal kernel). Let w(θ)=π(θ)/gt(θ)w(\theta) = \pi(\theta)/g_t(\theta), the weight of line L9. Then for every function hh with ∫πεt∣h∣<∞\int \pi_{\varepsilon_t}|h| < \infty,

Eqt[w(θ∗)h(θ∗)]Eqt[w(θ∗)]=Eπεt[h].\frac{\mathbb{E}_{q_t}[w(\theta^*)h(\theta^*)]}{\mathbb{E}_{q_t}[w(\theta^*)]} = \mathbb{E}_{\pi_{\varepsilon_t}}[h].

This holds for every previous population: the particles θj\theta_j and weights WjW_j need not be correct.

Proof. Where π(θ)>0\pi(\theta) > 0,

qt(θ) w(θ)=gt(θ) aεt(θ)ct⋅π(θ)gt(θ)=π(θ) aεt(θ)ct=Aεtct πεt(θ),q_t(\theta)\, w(\theta) = \frac{g_t(\theta)\, a_{\varepsilon_t}(\theta)}{c_t} \cdot \frac{\pi(\theta)}{g_t(\theta)} = \frac{\pi(\theta)\, a_{\varepsilon_t}(\theta)}{c_t} = \frac{A_{\varepsilon_t}}{c_t}\, \pi_{\varepsilon_t}(\theta),

and where π(θ)=0\pi(\theta) = 0 both sides are 00. So Eqt[wh]=(Aεt/ct) Eπεt[h]\mathbb{E}_{q_t}[wh] = (A_{\varepsilon_t}/c_t)\,\mathbb{E}_{\pi_{\varepsilon_t}}[h] and Eqt[w]=Aεt/ct\mathbb{E}_{q_t}[w] = A_{\varepsilon_t}/c_t. Divide. ■\blacksquare

The unknown acceptance probability aεta_{\varepsilon_t} appears in both the target and the proposal law and cancels, so the weight needs only π\pi and gtg_t. This is the weight of Beaumont, Cornuet, Marin and Robert (2009).

Claim 4: consistency for a fixed previous population

Fix the previous population and draw MM new particles. With normalized weights Wi∗=w(θi∗)/∑kw(θk∗)W_i^* = w(\theta_i^*)/\sum_k w(\theta_k^*) and a function hh with ∫πεt∣h∣<∞\int \pi_{\varepsilon_t}|h| < \infty, ∑iWi∗h(θi∗)→Eπεt[h]\sum_i W_i^* h(\theta_i^*) \to \mathbb{E}_{\pi_{\varepsilon_t}}[h] almost surely as M→∞M \to \infty.

Proof. By Claim 2 the θi∗\theta_i^* are independent with density qtq_t. Eqt∣wh∣=(Aεt/ct)∫πεt∣h∣<∞\mathbb{E}_{q_t}|wh| = (A_{\varepsilon_t}/c_t)\int\pi_{\varepsilon_t}|h| < \infty and Eqtw=Aεt/ct∈(0,∞)\mathbb{E}_{q_t}w = A_{\varepsilon_t}/c_t \in (0, \infty), so the strong law of large numbers applies to the numerator 1M∑iw(θi∗)h(θi∗)\frac1M\sum_i w(\theta_i^*)h(\theta_i^*) and to the denominator 1M∑iw(θi∗)\frac1M\sum_i w(\theta_i^*). The ratio converges to the ratio of the limits, which is Eπεt[h]\mathbb{E}_{\pi_{\varepsilon_t}}[h] by Claim 3. ■\blacksquare

Claim 5: equal weights target the wrong law

If line L9 is replaced by w≡1w \equiv 1, the weighted population of generation tt targets qtq_t, not πεt\pi_{\varepsilon_t}, and

qt(θ)πεt(θ)=Aεtct⋅gt(θ)π(θ).\frac{q_t(\theta)}{\pi_{\varepsilon_t}(\theta)} = \frac{A_{\varepsilon_t}}{c_t}\cdot\frac{g_t(\theta)}{\pi(\theta)}.

Proof. The first statement is Claim 2 with all weights equal, and the ratio is the display in the proof of Claim 3. ■\blacksquare

Since gtg_t is concentrated where the previous particles are, qtq_t puts too much mass near the centre of the previous population and too little in the tails. With a uniform prior, qtq_t is the product of πεt\pi_{\varepsilon_t} and a bump, which is narrower than πεt\pi_{\varepsilon_t}.

What is proved and what is measured

Claims 1 to 5 are exact. Claim 4 is a limit in the number of particles of one generation, with the previous population held fixed; the joint behaviour of all generations as NN grows, and the size of the error at a fixed NN, are not proved here. The page measures them against the exact posterior of a binomial model. The tests check Claim 3 in rational arithmetic on 500500 random finite models.

Complexity

Generation tt needs about N/AtN/A_t simulations of cost CC, where AtA_t is its acceptance rate, and N2N^2 kernel evaluations for the weights on L9. Over TT generations the expected time is Θ(T(N2+NC/A))\Theta(T(N^2 + NC/A)) with AA the smallest rate. When simulations are expensive, the simulations dominate; for cheap simulators and large NN, the N2N^2 term does, and a kernel density approximation of gtg_t removes it. The population takes Θ(N)\Theta(N) space.

Properties

  • Not exact. It targets the εT\varepsilon_T-posterior, and the weighted estimates have a bias of order 1/N1/N, like every self-normalized importance sampling estimate.
  • Valid for any kernel. The weight identity holds for every kernel with gt>0g_t > 0 on the support of the target. The kernel affects only efficiency.
  • Parallel within a generation. The NN particles of one generation are independent given the previous population.
  • Weight degeneracy. If the kernel is too wide or too narrow, a few weights dominate, which the effective sample size shows.
  • Gives the intermediate posteriors. Each generation is an estimate of πεt\pi_{\varepsilon_t}, so one run shows how the answer changes as the tolerance falls.

Variants and improvements

  • Adaptive tolerances. Choose εt\varepsilon_t as a quantile of the distances of the previous generation, or, as in Del Moral, Doucet and Jasra (2012), so that the effective sample size falls by a fixed fraction. Stop when the acceptance rate becomes too small.
  • MCMC moves. Del Moral, Doucet and Jasra (2012) resample the population and move each particle by an ABC Metropolis-Hastings step, which needs no O(N2)O(N^2) weight and keeps the population at the target.
  • Local kernels. Use a covariance estimated from the nearest particles, or an optimal local covariance, in place of the single s2s^2 of L2.
  • Model choice. Toni and coauthors (2009) add a model index to the particle and run the same scheme to estimate posterior model probabilities, which are valid only with summaries sufficient for the model index.
  • Regression adjustment of the final population, as for ABC rejection.

When to use it

Use ABC-SMC when the likelihood is intractable, simulations are costly, and the prior is much wider than the posterior, so that ABC rejection would waste most simulations. It is the standard ABC sampler in systems biology and epidemiology. For cheap simulators and a narrow prior, plain ABC rejection is simpler and gives independent draws. When the likelihood can be evaluated, use sequential Monte Carlo or MCMC on the true posterior. Check the calibration with simulation-based calibration.

Pitfalls

  • Missing or wrong weights. Setting wi=1w_i = 1 on L9 because "the ABC test already selects the right particles" gives a population that is too narrow, by 2525 percent in variance in the example. Keep wi=π(θ∗)/∑jWjK(θ∗∣θj)w_i = \pi(\theta^*)/\sum_j W_j K(\theta^* \mid \theta_j), and recompute the mixture with the previous weights, not the new ones.
  • A kernel that is too small. A tiny ss on L6 gives high acceptance but leaves the population stuck where it started, and the weights then degenerate. Use the rule of L2 or an adaptive kernel, and watch the effective sample size.
  • Falling too fast. Jumping from a loose to a strict tolerance in L3 makes the acceptance rate on L8 tiny, like plain rejection. Lower εt\varepsilon_t gradually, for example by a quantile rule.
  • Forgetting the prior support. If L7 simulates at θ∗\theta^* outside the support, the simulator may fail or return nonsense. Test π(θ∗)>0\pi(\theta^*) > 0 first, as L7 does.
  • Treating the result as the posterior. With εT>0\varepsilon_T > 0 or an insufficient summary, the population targets πεT\pi_{\varepsilon_T} given S(x)S(x), not π(θ∣x)\pi(\theta \mid x). Report εT\varepsilon_T and the summaries.

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.

abc_sequential_monte_carlo.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/abc-sequential-monte-carlo/. The authors are listed in prov/HY1FY8.jsonl.
"""ABC sequential Monte Carlo, in the population Monte Carlo form of Beaumont, Cornuet,
Marin and Robert (2009), for a scalar parameter.

Generation 1 is ABC rejection at tolerance eps_1. Generation t >= 2 proposes
theta* = theta_j + N(0, s^2) with j drawn from the previous weights, keeps theta* when its
simulated summary is within eps_t, and gives it the importance weight

    w = pi(theta*) / sum_j W_j K(theta* | theta_j).

The weighted population targets the eps_t-posterior pi(theta) P_theta(rho <= eps_t), for
any previous population, because the acceptance probability appears in both the target
and the proposal and cancels.

Cost per generation: N / A simulations for acceptance rate A, plus N^2 kernel
evaluations for the weights.
"""

import math
import random
from typing import Callable, Sequence


def normal_pdf(z: float, s: float) -> float:
    return math.exp(-0.5 * (z / s) ** 2) / (s * math.sqrt(2 * math.pi))


def weighted_variance(xs: Sequence[float], ws: Sequence[float]) -> float:
    m = math.fsum(w * x for x, w in zip(xs, ws))
    return math.fsum(w * (x - m) ** 2 for x, w in zip(xs, ws))


def smc_weight(theta, prior_pdf: Callable, prev: Sequence, prev_w: Sequence, kernel_pdf: Callable):
    """The importance weight pi(theta) / sum_j W_j K(theta | theta_j) (line L9).

    Works with floats or with Fractions (for the exact tests).
    """
    g = sum(w * kernel_pdf(theta, p) for p, w in zip(prev, prev_w))
    return prior_pdf(theta) / g


def abc_smc(
    prior_draw: Callable,
    prior_pdf: Callable,
    simulate: Callable,
    summary: Callable,
    s_obs,
    distance: Callable,
    eps_schedule: Sequence[float],
    n: int,
    rng: random.Random,
    equal_weights: bool = False,
) -> dict:
    """Run ABC-SMC. Returns the final particles, normalized weights, the kernel scales,
    the number of simulations per generation, and the effective sample sizes.

    Precondition: eps_schedule is non-increasing; prior_pdf(theta) > 0 exactly where the
    prior has mass. equal_weights=True drops the importance weights (a wrong variant,
    kept for the tests and the page).
    """
    sims = []
    parts = []
    count = 0
    while len(parts) < n:  # @line L1
        count += 1
        th = prior_draw(rng)
        if distance(summary(simulate(th, rng)), s_obs) <= eps_schedule[0]:
            parts.append(th)
    sims.append(count)
    weights = [1.0 / n] * n
    scales = []
    for eps in eps_schedule[1:]:  # @line L3
        s = math.sqrt(2 * weighted_variance(parts, weights))  # @line L2
        s = max(s, 1e-12)
        scales.append(s)
        cum = []
        acc = 0.0
        for w in weights:
            acc += w
            cum.append(acc)
        new_parts, new_w = [], []
        count = 0
        for _ in range(n):  # @line L4
            while True:  # @line L5
                j = min(_bisect(cum, rng.random() * acc), n - 1)  # @line L6
                th = parts[j] + rng.gauss(0.0, s)
                if prior_pdf(th) <= 0:  # @line L8
                    continue
                count += 1  # count simulations only
                y = simulate(th, rng)  # @line L7
                if distance(summary(y), s_obs) <= eps:
                    break
            new_parts.append(th)
            if equal_weights:
                new_w.append(1.0)
            else:
                new_w.append(smc_weight(th, prior_pdf, parts, weights, lambda a, b: normal_pdf(a - b, s)))  # @line L9
        tot = math.fsum(new_w)
        parts, weights = new_parts, [w / tot for w in new_w]  # @line L10
        sims.append(count)
    return {  # @line L11
        "particles": parts,
        "weights": weights,
        "scales": scales,
        "sims": sims,
        "ess": 1.0 / math.fsum(w * w for w in weights),
    }


def _bisect(cum: Sequence[float], u: float) -> int:
    lo, hi = 0, len(cum)
    while lo < hi:
        mid = (lo + hi) // 2
        if cum[mid] <= u:
            lo = mid + 1
        else:
            hi = mid
    return lo
test_abc_sequential_monte_carlo.py 105 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/abc-sequential-monte-carlo/. The authors are listed in prov/HY1FY8.jsonl.
"""Tests for ABC-SMC: the weight identity in exact arithmetic, and the final population
against the exact beta posterior of a binomial model."""

import math
import random
import unittest
from fractions import Fraction as F

from abc_sequential_monte_carlo import abc_smc, smc_weight, weighted_variance


def beta_cdf_int(t, a, b):
    m = a + b - 1
    return math.fsum(math.comb(m, j) * t**j * (1 - t) ** (m - j) for j in range(a, m + 1))


class TestWeightIdentity(unittest.TestCase):
    def test_weights_correct_any_previous_population_exactly(self):
        # Finite parameter set {0..k-1}. Accepted proposals have law q ~ g * a, with
        # g = sum_j W_j K(. | theta_j). Weighting by pi / g must give the eps-posterior
        # pi * a / (sum pi a) exactly, whatever the previous population is.
        rng = random.Random(1)
        for _ in range(500):
            k = rng.randint(1, 6)
            prior = [F(rng.randint(1, 5)) for _ in range(k)]
            prior = [p / sum(prior) for p in prior]
            a = [F(rng.randint(0, 6), 6) for _ in range(k)]
            if sum(p * x for p, x in zip(prior, a)) == 0:
                continue
            rows = [[F(rng.randint(1, 4)) for _ in range(k)] for _ in range(k)]
            kern = [[v / sum(r) for v in r] for r in rows]  # kern[old][new], all positive

            def kernel_pdf(new, old):
                return kern[old][new]

            m = rng.randint(1, 5)
            prev = [rng.randrange(k) for _ in range(m)]
            pw = [F(rng.randint(1, 5)) for _ in range(m)]
            pw = [w / sum(pw) for w in pw]
            g = [sum(w * kernel_pdf(t, p) for p, w in zip(prev, pw)) for t in range(k)]
            q = [g[t] * a[t] for t in range(k)]
            w = [smc_weight(t, lambda u: prior[u], prev, pw, kernel_pdf) for t in range(k)]
            h = [F(rng.randint(-5, 5)) for _ in range(k)]
            lhs = sum(q[t] * w[t] * h[t] for t in range(k)) / sum(q[t] * w[t] for t in range(k))
            rhs = sum(prior[t] * a[t] * h[t] for t in range(k)) / sum(prior[t] * a[t] for t in range(k))
            self.assertEqual(lhs, rhs)

    def test_weighted_variance(self):
        self.assertAlmostEqual(weighted_variance([0.0, 1.0], [0.5, 0.5]), 0.25)


def binomial(n):
    def prior_draw(rng):
        return rng.random()

    def prior_pdf(t):
        return 1.0 if 0.0 < t < 1.0 else 0.0

    def simulate(p, rng):
        return sum(1 for _ in range(n) if rng.random() < p)

    return prior_draw, prior_pdf, simulate


def wstats(res):
    xs, ws = res["particles"], res["weights"]
    m = math.fsum(w * x for x, w in zip(xs, ws))
    return m, weighted_variance(xs, ws)


class TestBinomial(unittest.TestCase):
    def setUp(self):
        # 6 successes in 20 trials, uniform prior: the posterior is Beta(7, 15).
        self.n, self.x = 20, 6
        self.mean, self.var = 7 / 22, 7 * 15 / (22**2 * 23)

    def test_final_population_matches_the_exact_posterior(self):
        pd, pp, sim = binomial(self.n)
        res = abc_smc(pd, pp, sim, lambda y: y, self.x, lambda u, v: abs(u - v), (6, 3, 1, 0), 500, random.Random(2))
        m, v = wstats(res)
        ess = res["ess"]
        self.assertGreater(ess, 400)
        self.assertLess(abs(m - self.mean), 4 * math.sqrt(self.var / ess))
        self.assertLess(abs(v / self.var - 1), 0.2)
        order = sorted(zip(res["particles"], res["weights"]))
        cdf, d = 0.0, 0.0
        for t, w in order:
            f = beta_cdf_int(t, 7, 15)
            d = max(d, abs(cdf - f), abs(cdf + w - f))
            cdf += w
        self.assertLess(d, 2.5 / math.sqrt(ess))
        # Fewer simulations than rejection ABC with eps = 0 (21 per kept value).
        self.assertLess(sum(res["sims"]), 500 * 21)

    def test_dropping_the_weights_gives_too_narrow_an_answer(self):
        pd, pp, sim = binomial(self.n)
        res = abc_smc(pd, pp, sim, lambda y: y, self.x, lambda u, v: abs(u - v), (6, 3, 1, 0), 500, random.Random(3), equal_weights=True)
        _, v = wstats(res)
        self.assertLess(v / self.var, 0.88)


if __name__ == "__main__":
    unittest.main()

History

Sisson, Fan and Tanaka (2007) proposed the first sequential ABC sampler, based on partial rejection control. Beaumont, Cornuet, Marin and Robert (2009) showed that its weights give a biased answer, and gave the population Monte Carlo version with the weights of L9 and a kernel variance of twice the previous variance. Sisson and coauthors published a correction in 2009. Toni and coauthors (2009) proposed the same weighted scheme for parameter inference and model selection in dynamical systems, which made it popular in systems biology. Del Moral, Doucet and Jasra (2012) placed ABC in the framework of sequential Monte Carlo samplers, with adaptive tolerances and MCMC moves.

References

  1. Mark A. Beaumont, Jean-Marie Cornuet, Jean-Michel Marin and Christian P. Robert, Adaptive approximate Bayesian computation, Biometrika 96(4), 2009, pages 983 to 990: the ABC population Monte Carlo algorithm, its importance weights, the kernel variance equal to twice the weighted variance of the previous population, and the bias of the earlier partial rejection control weights (general locator)
  2. Scott A. Sisson, Yanan Fan and Mark M. Tanaka, Sequential Monte Carlo without likelihoods, Proceedings of the National Academy of Sciences 104(6), 2007, pages 1760 to 1765: the first sequential ABC sampler (ABC partial rejection control); see the correction, doi:10.1073/pnas.0908847106, 2009 (general locator)
  3. Tina Toni, David Welch, Natalja Strelkowa, Andreas Ipsen and Michael P. H. Stumpf, Approximate Bayesian computation scheme for parameter inference and model selection in dynamical systems, Journal of the Royal Society Interface 6(31), 2009, pages 187 to 202: ABC-SMC with importance weights, and its use for model selection (general locator)
  4. Pierre Del Moral, Arnaud Doucet and Ajay Jasra, An adaptive sequential Monte Carlo method for approximate Bayesian computation, Statistics and Computing 22(5), 2012, pages 1009 to 1020: tolerances chosen adaptively from the effective sample size, with MCMC moves (general locator)

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.expected
  • 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