Algorithm Search⌘K

Algorithmadvanced

ABC rejection algorithm

Also called rejection ABC.

Draw a parameter from the prior, simulate a data set, and accept the parameter when its summaries lie within epsilon of the observed ones. The accepted draws approximate the posterior.

Time
Θ(N C / A) expected
Space
Θ(N) extra
Where
A = the acceptance probability, P(rho(S(Y), s_obs) <= eps) under the prior predictive; C = the cost of one simulation; N = the number of accepted values
Properties
randomizednot exactonlineiterative
Origin
Simon Tavaré, David J. Balding, Robert C. Griffiths, Peter Donnelly, Jonathan K. Pritchard, Mark A. Beaumont, 1997

The ABC rejection algorithm samples from an approximate posterior when the likelihood f(x∣θ)f(x \mid \theta) cannot be evaluated but data can be simulated from the model. It draws θ\theta from the prior π\pi, simulates a data set YY at θ\theta, and keeps θ\theta when the summaries S(Y)S(Y) lie within a tolerance ε\varepsilon of the observed summaries sobs=S(x)s_{\mathrm{obs}} = S(x). The kept values are an exact, independent sample from the ε\varepsilon-posterior πε(θ)∝π(θ) Pθ(ρ(S(Y),sobs)≤ε)\pi_\varepsilon(\theta) \propto \pi(\theta)\,P_\theta(\rho(S(Y), s_{\mathrm{obs}}) \le \varepsilon). With discrete data, a sufficient statistic and ε=0\varepsilon = 0, that is the exact posterior. It is the simplest member of approximate Bayesian computation.

In plain words

Suppose you have a machine that can produce fake data for any setting of its knobs, but no formula for how likely real data are. To learn which settings explain the real data, pick a setting at random from what you believed beforehand, run the machine, and look at the fake data. If it looks like the real data, keep the setting; if not, throw it away. Repeat many times. The settings you keep are the ones that often produce data like yours, and in the right proportions. Comparing whole data sets is too strict, so you compare a few numbers that describe them, and you allow a small gap. A smaller gap gives a better answer, but you throw away more runs.

The problem

Input. A proper prior π\pi that can be sampled; a simulator that draws a data set Y∼f(⋅∣θ)Y \sim f(\cdot \mid \theta) for any θ\theta; observed data xx; a summary map SS, a distance ρ\rho and a tolerance ε≥0\varepsilon \ge 0; the number NN of values to keep.

Output. NN independent draws from πε(θ)∝π(θ) aε(θ)\pi_\varepsilon(\theta) \propto \pi(\theta)\, a_\varepsilon(\theta), where aε(θ)=Pθ(ρ(S(Y),sobs)≤ε)a_\varepsilon(\theta) = P_\theta(\rho(S(Y), s_{\mathrm{obs}}) \le \varepsilon) is the probability that a simulation at θ\theta is close enough.

The algorithm

  1. ABC-REJECTION(π, simulator, S, s_obs, ρ, ε, N)
  2. 1K ← empty list
  3. 2while |K| < N
  4. 3θ ← a draw from π
  5. 4Y ← a data set simulated from f(· | θ)
  6. 5if ρ(S(Y), s_obs) ≤ ε then
  7. 6append θ to K
  8. 7return K

L3 and L4 draw a pair (θ,Y)(\theta, Y) from the joint law π(θ)f(y∣θ)\pi(\theta) f(y \mid \theta). L5 keeps the pair when the simulated summaries fall in a ball of radius ε\varepsilon around the observed ones; this is rejection sampling from the joint law conditioned on that ball, and L6 keeps only the θ\theta part. The algorithm never evaluates f(x∣θ)f(x \mid \theta). Each pass of the loop is independent, so the passes can run in parallel, and the implementation also stops after a given number of simulations.

Example

Trace. 33 successes in 1010 Bernoulli trials, uniform prior on pp, SS = the number of successes, ρ(u,v)=∣u−v∣\rho(u, v) = |u - v|, ε=0\varepsilon = 0. With random.Random(3):

proposal pp (L3) successes S(Y)S(Y) (L4) kept (L5)
1 0.2380 3 yes
2 0.4703 2 no
3 0.7582 7 no
4 0.8009 7 no
5 0.5072 2 no
6 0.1631 1 no
7 0.8539 8 no
8 0.0449 1 no
9 0.1974 2 no
10 0.5201 4 no
11 0.9778 10 no
12 0.4663 5 no

One proposal in 1212 is kept. The exact acceptance probability is ∫01(103)p3(1−p)7 dp=1/11\int_0^1 \binom{10}{3}p^3(1-p)^7\, dp = 1/11, and the kept values follow the exact posterior Beta(4, 8), with mean 1/31/3 and variance 0.0170940.017094.

The effect of the tolerance. Same model, 40004000 kept values per row, random.Random(2025). The exact columns come from πε(p)∝∑∣k−3∣≤ε(10k)pk(1−p)10−k\pi_\varepsilon(p) \propto \sum_{|k-3| \le \varepsilon}\binom{10}{k}p^k(1-p)^{10-k} in rational arithmetic.

ε\varepsilon acceptance, measured exact mean, measured exact variance, measured exact
0 0.0903 0.0909 0.3287 0.3333 0.01632 0.01709
1 0.2766 0.2727 0.3310 0.3333 0.02158 0.02137
2 0.4583 0.4545 0.3318 0.3333 0.03048 0.02991
3 0.6425 0.6364 0.3340 0.3333 0.04188 0.04274

The window is symmetric around 33, so the mean does not move, but the variance grows by 2525 percent at ε=1\varepsilon = 1 and more than doubles at ε=3\varepsilon = 3. A larger tolerance keeps more proposals and gives a wider answer.

An insufficient summary. Same data, (0,1,0,0,1,0,0,1,0,0)(0, 1, 0, 0, 1, 0, 0, 1, 0, 0), but SS = the number of successes in the first five trials only. The kept values then follow Beta(3, 4), the posterior given half of the data: measured mean 0.42850.4285 and variance 0.030100.03010, against the exact 0.42860.4286 and 0.030610.03061. The algorithm is correct for the information in SS, not for the information in xx.

The curse of dimensionality. x1,…,x5∼N(θ,1)x_1, \ldots, x_5 \sim N(\theta, 1) with prior N(0,32)N(0, 3^2); the exact posterior standard deviation is 0.44230.4423. With S=xˉS = \bar x (one number), the acceptance probability halves when ε\varepsilon halves: 0.2450.245, 0.1340.134, 0.0660.066 and 0.0250.025 for ε=1,0.5,0.25,0.1\varepsilon = 1, 0.5, 0.25, 0.1, with posterior standard deviations 0.6850.685, 0.5240.524, 0.4650.465 and 0.4450.445. With SS = the whole data vector in R5\mathbb{R}^5 and the Euclidean distance, it is 9.0×10−49.0 \times 10^{-4} at ε=1\varepsilon = 1 and 3.5×10−53.5 \times 10^{-5} at ε=0.5\varepsilon = 0.5, and 2×1062 \times 10^6 simulations give only one kept value at ε=0.25\varepsilon = 0.25.

Correctness

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

  1. The ε\varepsilon-posterior. The kept values are independent draws from πε(θ)∝π(θ)aε(θ)\pi_\varepsilon(\theta) \propto \pi(\theta)a_\varepsilon(\theta), and the number of simulations per kept value is geometric with mean 1/A1/A, where A=∫aε dπA = \int a_\varepsilon\, d\pi.
  2. Exactness at ε=0\varepsilon = 0. For a discrete summary, π0(θ)=π(θ∣S(x))\pi_0(\theta) = \pi(\theta \mid S(x)) and A=mS(sobs)A = m_S(s_{\mathrm{obs}}), the marginal likelihood of the summary. If the data are discrete and SS is sufficient, the Fisher-Neyman factorization theorem shows fS(sobs∣θ)∝f(x∣θ)f_S(s_{\mathrm{obs}} \mid \theta) \propto f(x \mid \theta), so π0\pi_0 is the exact posterior. For the binomial with a uniform prior, A=1/(n+1)A = 1/(n+1).
  3. The limit ε→0\varepsilon \to 0. For continuous summaries in Rq\mathbb{R}^q with a bounded density continuous at sobss_{\mathrm{obs}}, πε→π(⋅∣S(x)=sobs)\pi_\varepsilon \to \pi(\cdot \mid S(x) = s_{\mathrm{obs}}) and A≈mS(sobs)VqεqA \approx m_S(s_{\mathrm{obs}})V_q\varepsilon^q.

The key invariant is that each pass of L3 to L5 is an independent draw of (θ,Y)(\theta, Y) from the joint law, kept when YY falls in a fixed set. What is proved and what is measured: items 1 and 2 are exact, and the tests check them with exact rational probabilities over every random path of one proposal, on 500500 random discrete models. Item 3 is a limit; the size of the error at a fixed ε>0\varepsilon > 0 is not bounded on this page but measured in the tables. The Kolmogorov-Smirnov distance of 20002000 kept values to Beta(4, 8) is below 1.95/20001.95/\sqrt{2000} in the test.

Proof: The law of the values kept by the ABC rejection algorithmfull

Setting. π\pi is a proper prior on Θ\Theta. For each θ\theta, Y∼f(⋅∣θ)Y \sim f(\cdot \mid \theta) is a simulated data set, SS is a summary map, sobs=S(x)s_{\mathrm{obs}} = S(x) is the observed summary, ρ≥0\rho \ge 0 is a distance with ρ(s,s′)=0\rho(s, s') = 0 only if s=s′s = s', and ε≥0\varepsilon \ge 0. One proposal draws θ∼π\theta \sim \pi, then Y∼f(⋅∣θ)Y \sim f(\cdot \mid \theta), and keeps θ\theta when ρ(S(Y),sobs)≤ε\rho(S(Y), s_{\mathrm{obs}}) \le \varepsilon. Write

aε(θ)=Pθ(ρ(S(Y),sobs)≤ε),Aε=∫aε(θ) π(dθ).a_\varepsilon(\theta) = P_\theta\big(\rho(S(Y), s_{\mathrm{obs}}) \le \varepsilon\big), \qquad A_\varepsilon = \int a_\varepsilon(\theta)\, \pi(d\theta).

Claim 1: the kept values follow the ε\varepsilon-posterior

If Aε>0A_\varepsilon > 0, the kept values are independent with law

πε(dθ)=aε(θ) π(dθ)Aε,\pi_\varepsilon(d\theta) = \frac{a_\varepsilon(\theta)\, \pi(d\theta)}{A_\varepsilon},

each proposal is kept with probability AεA_\varepsilon, and the number of proposals per kept value is geometric with mean 1/Aε1/A_\varepsilon.

Proof. For one proposal and a measurable set BB, conditioning on θ\theta gives

P(θ∈B and kept)=∫BPθ(ρ(S(Y),sobs)≤ε) π(dθ)=∫Baε dπ.P(\theta \in B \text{ and kept}) = \int_B P_\theta(\rho(S(Y), s_{\mathrm{obs}}) \le \varepsilon)\, \pi(d\theta) = \int_B a_\varepsilon\, d\pi.

With B=ΘB = \Theta the probability of being kept is AεA_\varepsilon, and P(θ∈B∣kept)=∫Baε dπ/Aε=πε(B)P(\theta \in B \mid \text{kept}) = \int_B a_\varepsilon\, d\pi / A_\varepsilon = \pi_\varepsilon(B). Proposals use fresh randomness, so they are independent and identically distributed. The first kept proposal therefore comes after a geometric number of trials with success probability AεA_\varepsilon, its value has law πε\pi_\varepsilon, and the process starts afresh after it, which makes the kept values independent. ■\blacksquare

Claim 2: tolerance zero with discrete data

Assume that S(Y)S(Y) takes countably many values and ε=0\varepsilon = 0. Then a0(θ)=Pθ(S(Y)=sobs)=fS(sobs∣θ)a_0(\theta) = P_\theta(S(Y) = s_{\mathrm{obs}}) = f_S(s_{\mathrm{obs}} \mid \theta), the probability function of the summary, and the kept values follow

π0(θ)∝π(θ)fS(sobs∣θ)=π(θ∣S(x)=sobs).\pi_0(\theta) \propto \pi(\theta) f_S(s_{\mathrm{obs}} \mid \theta) = \pi(\theta \mid S(x) = s_{\mathrm{obs}}).

The acceptance probability is A0=mS(sobs)=∫fS(sobs∣θ) π(dθ)A_0 = m_S(s_{\mathrm{obs}}) = \int f_S(s_{\mathrm{obs}} \mid \theta)\, \pi(d\theta), the marginal likelihood of the summary.

If moreover the data are discrete and SS is a sufficient statistic, then π0\pi_0 is the exact posterior π(θ∣x)\pi(\theta \mid x).

Proof. Since ρ(s,s′)=0\rho(s, s') = 0 only if s=s′s = s', the event ρ(S(Y),sobs)≤0\rho(S(Y), s_{\mathrm{obs}}) \le 0 is {S(Y)=sobs}\{S(Y) = s_{\mathrm{obs}}\}; Claim 1 gives the first two statements by Bayes' theorem for the observation S(x)S(x). For the last one, the Fisher-Neyman factorization theorem gives f(y∣θ)=g(S(y),θ) h(y)f(y \mid \theta) = g(S(y), \theta)\, h(y). Summing over the data sets with the observed summary,

fS(sobs∣θ)=∑y:S(y)=sobsg(sobs,θ) h(y)=g(sobs,θ) c(sobs),f_S(s_{\mathrm{obs}} \mid \theta) = \sum_{y : S(y) = s_{\mathrm{obs}}} g(s_{\mathrm{obs}}, \theta)\, h(y) = g(s_{\mathrm{obs}}, \theta)\, c(s_{\mathrm{obs}}),

where c(sobs)=∑y:S(y)=sobsh(y)c(s_{\mathrm{obs}}) = \sum_{y : S(y) = s_{\mathrm{obs}}} h(y) does not depend on θ\theta. Also f(x∣θ)=g(sobs,θ) h(x)f(x \mid \theta) = g(s_{\mathrm{obs}}, \theta)\, h(x). So fS(sobs∣θ)f_S(s_{\mathrm{obs}} \mid \theta) and f(x∣θ)f(x \mid \theta) are proportional as functions of θ\theta (when h(x)>0h(x) > 0, which holds because xx was observed), and the two posteriors coincide. ■\blacksquare

Example. For nn Bernoulli trials with SS = the number of successes and a uniform prior on pp, A0=∫01(ns)ps(1−p)n−s dp=(ns)B(s+1,n−s+1)=1/(n+1)A_0 = \int_0^1 \binom{n}{s}p^s(1-p)^{n-s}\, dp = \binom{n}{s}B(s+1, n-s+1) = 1/(n+1) for every ss. For n=10n = 10, one proposal in 1111 is kept. With a window ∣S(Y)−s∣≤k|S(Y) - s| \le k that stays inside {0,…,n}\{0, \ldots, n\}, Ak=(2k+1)/(n+1)A_k = (2k+1)/(n+1).

Insufficient summaries. If SS is not sufficient, Claim 2 still holds with π(θ∣S(x)=sobs)\pi(\theta \mid S(x) = s_{\mathrm{obs}}), which is a valid posterior given less information, and usually wider than π(θ∣x)\pi(\theta \mid x).

Claim 3: tolerance tending to zero with continuous summaries

Assume that S(Y)∈RqS(Y) \in \mathbb{R}^q has a density fS(s∣θ)f_S(s \mid \theta) that is continuous in ss at sobss_{\mathrm{obs}} for every θ\theta and bounded by a constant MM, that ρ\rho is a norm, and that mS(sobs)=∫fS(sobs∣θ) π(dθ)>0m_S(s_{\mathrm{obs}}) = \int f_S(s_{\mathrm{obs}} \mid \theta)\, \pi(d\theta) > 0. Then, as ε→0\varepsilon \to 0, πε(B)→π(B∣S(x)=sobs)\pi_\varepsilon(B) \to \pi(B \mid S(x) = s_{\mathrm{obs}}) for every measurable BB, and Aε/(Vqεq)→mS(sobs)A_\varepsilon / (V_q\varepsilon^q) \to m_S(s_{\mathrm{obs}}), where VqV_q is the volume of the unit ball of ρ\rho.

Proof. Let Bε\mathcal{B}_\varepsilon be the ball of radius ε\varepsilon around sobss_{\mathrm{obs}}, of volume VqεqV_q\varepsilon^q. Then aε(θ)/(Vqεq)a_\varepsilon(\theta)/(V_q\varepsilon^q) is the mean of fS(⋅∣θ)f_S(\cdot \mid \theta) over Bε\mathcal{B}_\varepsilon, which tends to fS(sobs∣θ)f_S(s_{\mathrm{obs}} \mid \theta) by continuity and is bounded by MM. By dominated convergence (π\pi is a probability measure), ∫Baε dπ/(Vqεq)→∫BfS(sobs∣θ) π(dθ)\int_B a_\varepsilon\, d\pi / (V_q\varepsilon^q) \to \int_B f_S(s_{\mathrm{obs}} \mid \theta)\, \pi(d\theta) for every BB, including B=ΘB = \Theta. Divide the two limits. ■\blacksquare

The second limit is the curse of dimensionality: for small ε\varepsilon the expected number of simulations per kept value is about 1/(mS(sobs)Vqεq)1/(m_S(s_{\mathrm{obs}})V_q\varepsilon^q), which grows like ε−q\varepsilon^{-q}.

What is exact and what is measured

Claims 1 and 2 are exact: with discrete data, a sufficient summary and ε=0\varepsilon = 0, ABC rejection is an exact posterior sampler. The tests check Claims 1 and 2 with exact rational probabilities by listing every random path of one proposal. Claim 3 is a limit; at a fixed ε>0\varepsilon > 0 the error of πε\pi_\varepsilon is not bounded here, and the page measures it.

Complexity

Each pass costs one prior draw and one simulation of cost CC. The number of passes per kept value is geometric with mean 1/A1/A, so NN values cost Θ(NC/A)\Theta(NC/A) in expectation. AA is the prior predictive probability of the ε\varepsilon-ball. It falls like εq\varepsilon^q for qq continuous summaries, and it is small when the prior is wide compared with the posterior; for the binomial example, A=(2ε+1)/11A = (2\varepsilon + 1)/11. The kept values take Θ(N)\Theta(N) space; nothing else is stored.

Properties

  • Exact for πε\pi_\varepsilon. There is no Markov chain and no weight: the kept values are independent and identically distributed.
  • Likelihood-free. Only forward simulation is needed.
  • Embarrassingly parallel and online. Proposals are independent and can stop at any time.
  • Two approximations. The summary loses information unless it is sufficient, and the tolerance widens the answer.
  • Gives the evidence of the summary. The acceptance rate estimates AA, and A/(Vqεq)A/(V_q\varepsilon^q) estimates mS(sobs)m_S(s_{\mathrm{obs}}), which can be used for model choice only when SS is sufficient for both models together.

Variants and improvements

  • Keep the closest fraction. Simulate a fixed number MM of pairs and keep the fraction with the smallest distances; ε\varepsilon is then a quantile of the distances. This is the common form in practice.
  • Regression adjustment. Beaumont, Zhang and Balding (2002) fit a local linear regression of θ\theta on S(Y)S(Y) among the kept pairs and shift each kept value to sobss_{\mathrm{obs}}, which allows a larger ε\varepsilon for the same accuracy.
  • Smooth kernels. Replace the indicator in L5 by a kernel weight Kε(ρ)K_\varepsilon(\rho), giving weighted draws.
  • Sequential methods. ABC sequential Monte Carlo moves a population through a falling sequence of tolerances, so proposals come from near the posterior instead of the prior. ABC with a Markov chain uses the same acceptance test inside Metropolis-Hastings.
  • Scaled distances. When summaries have different scales, divide each by a robust spread, such as the median absolute deviation over prior simulations, before L5.

When to use it

Use ABC rejection when the likelihood is intractable but the model can be simulated fast: coalescent models in population genetics, epidemic models, and stochastic models of cells or ecosystems. It is the right first method when the prior is not much wider than the posterior and there are few summaries, because it is simple, parallel and gives independent draws. When the likelihood can be evaluated, use Bayesian inference with MCMC or importance sampling instead. When the acceptance rate is tiny, use ABC sequential Monte Carlo or regression adjustment. Check the result with simulation-based calibration on simulated data sets.

Pitfalls

  • Raw data as the summary. Taking S(Y)=YS(Y) = Y in L5 for continuous data has acceptance probability 00 at ε=0\varepsilon = 0 and tiny acceptance otherwise, as the five-dimensional row shows. Use a few informative summaries in L5, ideally sufficient or close to it.
  • Insufficient summaries. L5 with a summary that drops information gives the posterior given S(x)S(x), which can be much wider, or biased for model choice. Choose SS so that it captures what the parameter changes, and test the choice on simulated data with known θ\theta.
  • Unscaled distances. With ρ\rho the Euclidean distance on summaries of very different scales, L5 effectively uses only the largest one. Scale each summary before L5.
  • An improper or very wide prior. L3 needs a proper prior, and a wide one makes AA tiny. Use a proper prior that is as narrow as the knowledge allows, or a sequential method.
  • Reporting πε\pi_\varepsilon as the posterior. With ε>0\varepsilon > 0, the kept values are wider than the posterior, by 2525 percent in variance at ε=1\varepsilon = 1 in the table. Report ε\varepsilon, and check that the answer is stable as ε\varepsilon falls.

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_rejection_sampling.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/abc-rejection-sampling/. The authors are listed in prov/1PE36P.jsonl.
"""The ABC rejection algorithm (Tavare et al. 1997; Pritchard et al. 1999).

Draw theta from the prior, simulate a data set y from the model at theta, and keep
theta when the summaries S(y) lie within eps of the observed summaries s_obs.
The kept values are an exact sample from the eps-posterior

    pi_eps(theta) proportional to pi(theta) P_theta(rho(S(Y), s_obs) <= eps).

With eps = 0, discrete data and a sufficient summary, that is the exact posterior.

Cost: each proposal costs one prior draw and one simulation. The expected number of
proposals per accepted value is 1 / P(rho(S(Y), s_obs) <= eps) under the prior
predictive, which grows like eps^(-q) for q continuous summaries.
"""

import random
from typing import Callable


def abc_step(
    prior_draw: Callable,
    simulate: Callable,
    summary: Callable,
    s_obs,
    distance: Callable,
    eps: float,
    rng,
) -> tuple:
    """One proposal: returns (theta, accepted). Lines L3 to L5."""
    theta = prior_draw(rng)  # @line L3
    y = simulate(theta, rng)  # @line L4
    return theta, distance(summary(y), s_obs) <= eps  # @line L5


def abc_rejection(
    prior_draw: Callable,
    simulate: Callable,
    summary: Callable,
    s_obs,
    distance: Callable,
    eps: float,
    n_accept: int,
    rng: random.Random,
    max_sims: int = 10**8,
) -> tuple[list, int]:
    """Run proposals until n_accept values are kept or max_sims proposals are made.

    Returns (accepted values, number of proposals).
    Precondition: prior_draw(rng) draws from a proper prior; simulate(theta, rng) draws a
    data set from f(. | theta); distance(a, b) >= 0. The kept values are independent.
    """
    accepted = []  # @line L1
    sims = 0
    while len(accepted) < n_accept and sims < max_sims:  # @line L2
        sims += 1
        theta, ok = abc_step(prior_draw, simulate, summary, s_obs, distance, eps, rng)
        if ok:
            accepted.append(theta)  # @line L6
    return accepted, sims  # @line L7


class ScriptedRNG:
    """A stand-in for random.Random whose randrange(k) returns scripted values.

    Used to enumerate every random path of a discrete sampler with exact probabilities.
    When the script runs out it raises NeedChoice(k), so the caller can branch.
    """

    class NeedChoice(Exception):
        def __init__(self, k: int):
            super().__init__(k)
            self.k = k

    def __init__(self, script: list):
        self.script = script
        self.pos = 0

    def randrange(self, k: int) -> int:
        if self.pos == len(self.script):
            raise ScriptedRNG.NeedChoice(k)
        v = self.script[self.pos][0]
        self.pos += 1
        return v


def exact_accept_law(run_step: Callable) -> dict:
    """Exact law of one call run_step(rng) -> (theta, accepted) over all random paths.

    run_step must use only rng.randrange. Returns {theta: P(theta and accepted)} as
    Fractions; their sum is the acceptance probability. Paths are enumerated depth first.
    """
    from fractions import Fraction

    law: dict = {}
    stack = [[]]  # each script is a list of (value, range)
    while stack:
        script = stack.pop()
        try:
            theta, ok = run_step(ScriptedRNG(script))
        except ScriptedRNG.NeedChoice as need:
            for v in range(need.k):
                stack.append(script + [(v, need.k)])
            continue
        if ok:
            p = Fraction(1)
            for _, k in script:
                p /= k
            law[theta] = law.get(theta, Fraction(0)) + p
    return law
test_abc_rejection_sampling.py 160 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/abc-rejection-sampling/. The authors are listed in prov/1PE36P.jsonl.
"""Tests for the ABC rejection algorithm.

Discrete models: every random path of one proposal is enumerated with exact Fraction
probabilities, so the law of the kept values is compared exactly with Bayes' rule.
Continuous prior: Kolmogorov-Smirnov distance to the exact beta posterior.
"""

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

from abc_rejection_sampling import abc_rejection, abc_step, exact_accept_law


def comb(n, k):
    return math.comb(n, k)


def discrete_model(thetas, weights, den):
    """Prior on thetas (numerators of p = a/den) with integer weights; Bernoulli trials
    drawn by randrange(den) < a, so every path is enumerable."""
    total = sum(weights)

    def prior_draw(rng):
        r = rng.randrange(total)
        for a, w in zip(thetas, weights):
            if r < w:
                return a
            r -= w
        raise AssertionError

    def make_sim(n):
        def simulate(a, rng):
            return tuple(1 if rng.randrange(den) < a else 0 for _ in range(n))
        return simulate

    return prior_draw, make_sim


def normalize(law):
    z = sum(law.values())
    return {k: v / z for k, v in law.items()}, z


def hamming(a, b):
    return sum(u != v for u, v in zip(a, b))


class TestExactLaw(unittest.TestCase):
    def test_tolerance_zero_sufficient_summary_gives_the_posterior(self):
        rng = random.Random(1)
        cases = 0
        while cases < 500:
            den = rng.choice([2, 3, 4])
            k = rng.randint(1, min(3, den - 1))
            thetas = rng.sample(range(1, den), k)
            weights = [rng.randint(1, 3) for _ in thetas]
            n = rng.randint(1, 3)
            x = tuple(rng.randint(0, 1) for _ in range(n))
            s = sum(x)
            prior_draw, make_sim = discrete_model(thetas, weights, den)
            sim = make_sim(n)
            prior = {a: F(w, sum(weights)) for a, w in zip(thetas, weights)}
            lik = {a: F(a, den) ** s * (1 - F(a, den)) ** (n - s) for a in thetas}
            post, _ = normalize({a: prior[a] * lik[a] for a in thetas})

            # S = number of successes (sufficient), eps = 0.
            law = exact_accept_law(lambda r: abc_step(prior_draw, sim, sum, s, lambda u, v: abs(u - v), 0, r))
            got, acc = normalize(law)
            self.assertEqual(got, post)
            self.assertEqual(acc, sum(prior[a] * comb(n, s) * lik[a] for a in thetas))  # m_S(s_obs)

            # S = the whole data set (also sufficient), eps = 0, Hamming distance.
            law = exact_accept_law(lambda r: abc_step(prior_draw, sim, lambda y: y, x, hamming, 0, r))
            got, acc = normalize(law)
            self.assertEqual(got, post)
            self.assertEqual(acc, sum(prior[a] * lik[a] for a in thetas))  # m(x)

            # eps = 1 on the count: the eps-posterior pi(a) P_a(|S - s| <= 1).
            def window(a):
                p = F(a, den)
                return sum(comb(n, j) * p**j * (1 - p) ** (n - j) for j in range(max(0, s - 1), min(n, s + 1) + 1))

            law = exact_accept_law(lambda r: abc_step(prior_draw, sim, sum, s, lambda u, v: abs(u - v), 1, r))
            got, _ = normalize(law)
            self.assertEqual(got, normalize({a: prior[a] * window(a) for a in thetas})[0])

            # Insufficient summary (the first trial only): the posterior given x_1 alone.
            law = exact_accept_law(lambda r: abc_step(prior_draw, sim, lambda y: y[0], x[0], lambda u, v: abs(u - v), 0, r))
            got, _ = normalize(law)
            p1 = {a: F(a, den) if x[0] == 1 else 1 - F(a, den) for a in thetas}
            self.assertEqual(got, normalize({a: prior[a] * p1[a] for a in thetas})[0])
            cases += 1

    def test_insufficient_summary_differs_from_the_posterior(self):
        prior_draw, make_sim = discrete_model([1, 3], [1, 1], 4)
        sim = make_sim(3)
        x = (1, 1, 1)
        full, _ = normalize(exact_accept_law(lambda r: abc_step(prior_draw, sim, sum, 3, lambda u, v: abs(u - v), 0, r)))
        first, _ = normalize(exact_accept_law(lambda r: abc_step(prior_draw, sim, lambda y: y[0], 1, lambda u, v: abs(u - v), 0, r)))
        self.assertEqual(full, {1: F(1, 28), 3: F(27, 28)})
        self.assertEqual(first, {1: F(1, 4), 3: F(3, 4)})


def beta_cdf_int(t, a, b):
    """Beta(a, b) CDF for integer a, b: P(Binomial(a + b - 1, t) >= a)."""
    m = a + b - 1
    return math.fsum(comb(m, j) * t**j * (1 - t) ** (m - j) for j in range(a, m + 1))


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

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

    return prior_draw, simulate


class TestContinuousPrior(unittest.TestCase):
    def test_kolmogorov_smirnov_against_the_beta_posterior(self):
        # Uniform prior, 3 successes in 10 trials: the posterior is Beta(4, 8).
        rng = random.Random(7)
        prior_draw, simulate = binomial_setup(10)
        n_acc = 2000
        acc, sims = abc_rejection(prior_draw, simulate, lambda y: y, 3, lambda u, v: abs(u - v), 0, n_acc, rng)
        acc.sort()
        d = max(max((i + 1) / n_acc - beta_cdf_int(t, 4, 8), beta_cdf_int(t, 4, 8) - i / n_acc) for i, t in enumerate(acc))
        self.assertLess(d, 1.95 / math.sqrt(n_acc))
        # Acceptance probability m_S(3) = 1/11.
        rate = n_acc / sims
        self.assertLess(abs(rate - 1 / 11), 4 * math.sqrt((1 / 11) * (10 / 11) / sims))

    def test_positive_tolerance_inflates_the_variance(self):
        # eps = 1: pi_eps(p) is proportional to sum_{k=2}^{4} C(10,k) p^k (1-p)^(10-k).
        # Mean 1/3 (as the posterior), variance 0.021368 against 0.017094 for eps = 0.
        exact_var = F(62, 468) - F(1, 9)
        rng = random.Random(8)
        prior_draw, simulate = binomial_setup(10)
        acc, sims = abc_rejection(prior_draw, simulate, lambda y: y, 3, lambda u, v: abs(u - v), 1, 4000, rng)
        self.assertLess(abs(statistics.mean(acc) - 1 / 3), 4 * math.sqrt(float(exact_var) / 4000))
        self.assertLess(abs(statistics.variance(acc) - float(exact_var)), 0.0015)
        self.assertGreater(statistics.variance(acc), 32 / 1872 + 0.002)
        self.assertLess(abs(4000 / sims - 3 / 11), 4 * math.sqrt((3 / 11) * (8 / 11) / sims))

    def test_max_sims_limits_the_work(self):
        rng = random.Random(9)
        prior_draw, simulate = binomial_setup(10)
        acc, sims = abc_rejection(prior_draw, simulate, lambda y: y, 3, lambda u, v: abs(u - v), 0, 10**6, rng, max_sims=500)
        self.assertEqual(sims, 500)
        self.assertLess(len(acc), 500)


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

History

Rubin (1984) described the procedure, draw from the prior, simulate, keep the draws whose simulated data match, as a way to explain what a posterior distribution is. Tavaré, Balding, Griffiths and Donnelly (1997) used it with an exact match on the number of segregating sites to infer coalescence times from DNA data. Pritchard, Seielstad, Perez-Lezaun and Feldman (1999) used several summary statistics with a tolerance to study the growth of human populations from Y chromosome data. Beaumont, Zhang and Balding (2002) named the approach approximate Bayesian computation and introduced regression adjustment. Sequential and Markov chain versions followed, and the method spread from population genetics to ecology, epidemiology and systems biology.

References

  1. Donald B. Rubin, Bayesianly justifiable and relevant frequency calculations for the applied statistician, Annals of Statistics 12(4), 1984, pages 1151 to 1172: the description of Bayes' rule as drawing a parameter from the prior, simulating data, and keeping the parameter when the simulated data match the observed data (general locator)
  2. Simon Tavaré, David J. Balding, Robert C. Griffiths and Peter Donnelly, Inferring coalescence times from DNA sequence data, Genetics 145(2), 1997, pages 505 to 518: rejection sampling of the coalescent with an exact match on the number of segregating sites (general locator)
  3. Jonathan K. Pritchard, Mark T. Seielstad, Anna Perez-Lezaun and Marcus W. Feldman, Population growth of human Y chromosomes: a study of Y chromosome microsatellites, Molecular Biology and Evolution 16(12), 1999, pages 1791 to 1798: the rejection algorithm with summary statistics and a tolerance (general locator)
  4. Beaumont, Zhang and Balding 2002, pages 2025 to 2035: the name approximate Bayesian computation, the analysis of the tolerance, and local linear regression adjustment (general locator)

Where this leads

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