Algorithm Search⌘K

Algorithmcore

Coalescent simulation

Also called Hudson coalescent algorithm, ms simulation.

Simulate a neutral sample backward in time: draw exponential waiting times, merge random pairs of lineages, then drop mutations on the tree.

Time
Θ(n + n s + s log s) worst · average · best
Space
Θ(n + n s) extra
Where
n = the number of sampled copies; s = the number of segregating sites
Properties
randomizedexactofflineiterative
Origin
Richard R. Hudson, 1983

Coalescent simulation draws a sample of DNA sequences from a neutral population model by building the genealogy of the sample backward in time and then placing mutations on it, instead of simulating the whole population forward. The basic version, Hudson's algorithm, draws a Kingman coalescent tree with exponential waiting times and random pairs of lineages to merge, and then puts a Poisson number of mutations on each branch under the infinite sites model. It costs time linear in the size of the sample and its data, not in the size of the population or the number of generations. It produces the null distributions of statistics such as Tajima's D, and with recombination it simulates the ancestral recombination graph.

In plain words

To see what neutral data from a population of a million individuals look like, you could simulate the million individuals for many generations and then pick a few of them. Almost all that work is wasted: only the ancestors of the few picked ones matter.

So start from the sample and go back in time. At each step, ask how long until two of the current lineages find a common parent; with many lineages this happens soon, with few it takes long. When it happens, pick two lineages at random and join them. Stop at the single common ancestor. Now the tree is done, and mutations fall on it like rain: a longer branch gets more of them, and everything below a branch carries its mutations.

The problem

Input. A sample size n≥1n \ge 1, the population mutation rate θ=4Nμ\theta = 4N\mu of the locus, and a source of random numbers. As an option, a fixed number ss of segregating sites instead of θ\theta.

Output. A random genealogy and a random sample from the neutral model: a rooted binary tree on the nn sampled copies with node ages, the positions of the segregating sites in [0,1)[0, 1), and the n×Sn \times S matrix of alleles, 0 for ancestral and 1 for derived. The joint law of the output must be exactly the law of the model: the Kingman coalescent with time in units of 2N2N generations, and given the tree, mutations as a Poisson process of rate θ/2\theta/2 along the branches, each at a new uniform position.

The model assumes neutrality, a constant population size, random mating, no structure and no recombination inside the locus. The variants section lifts each of these.

The algorithm

  1. HUDSON(n, θ)
  2. 1A ← the n sampled copies, each a node of age 0; t ← 0
  3. 2while |A| > 1 do
  4. 3k ← |A|; t ← t + an exponential time with rate k(k − 1)/2
  5. 4choose two distinct lineages i and j of A uniformly at random
  6. 5make a node u of age t with the children i and j; replace i and j in A by u
  7. 6for each branch from a node v to its parent p do
  8. 7draw M from a Poisson distribution with mean θ/2 · (age of p − age of v)
  9. 8add M sites at uniform positions in [0, 1), each with allele 1 in the copies below v
  10. 9sort the sites by position and return the tree and the matrix

Lines L1 to L5 build the tree. Each pass of the loop is one coalescence. Line L3 waits for it, and line L4 picks the pair, uniform among the (k2)\binom{k}{2} pairs. Lines L6 to L8 add the mutations. The copies below a node are a bit mask in the implementation, built bottom-up in one pass, since a node is always made after its children.

With a fixed number ss of segregating sites (the option -s of ms), line L7 is replaced by drawing ss branches, each with probability proportional to its length. For a fixed tree, that is the law of the sites given S=sS = s, because given their number the points of a Poisson process fall independently and uniformly on the tree. It is not the law of the whole sample given S=sS = s, since the tree is not weighted by P(S=s∣tree)P(S = s \mid \text{tree}).

Example

Take n=4n = 4 and θ=2\theta = 2, and number the copies 1 to 4. Suppose the draws are these.

step kk rate (k2)\binom{k}{2} waiting time age tt pair new node
1 4 6 0.10 0.10 1, 2 5
2 3 3 0.25 0.35 3, 4 6
3 2 1 0.85 1.20 5, 6 7 (root)

The branch lengths are 0.10 above copies 1 and 2, 0.35 above copies 3 and 4, 1.10 above node 5 and 0.85 above node 6, a total of L=2.85L = 2.85 (the mean is 2a4=11/3=3.672 a_4 = 11/3 = 3.67). With θ=2\theta = 2, the mean number of mutations on a branch equals its length. Suppose line L7 gives one mutation above node 5, two above node 6, one above copy 3 and none elsewhere, and line L8 puts them at the positions 0.40, 0.12, 0.93 and 0.71. Sorted by position, the sites are 0.12 (copies 3, 4), 0.40 (copies 1, 2), 0.71 (copy 3) and 0.93 (copies 3, 4), and the sample is

copy 0.12 0.40 0.71 0.93
1 0 1 0 0
2 0 1 0 0
3 1 0 1 1
4 1 0 0 1

So S=4S = 4, against the mean θa4=11/3=3.67\theta a_4 = 11/3 = 3.67. The sites 0.12 and 0.93 are on the same branch and have the same pattern; no pair of sites shows all four gametes, as the four-gamete condition requires without recombination.

Correctness

The Kingman coalescent of nn copies is a Markov chain on partitions of the sample: from a partition with kk blocks, each of the (k2)\binom{k}{2} pairs of blocks merges at rate 1. In a continuous-time Markov chain with total rate λ\lambda out of the current state, the time to the next jump is exponential with rate λ\lambda, and the jump goes to each target with probability its rate over λ\lambda, independently of the time. Here λ=(k2)\lambda = \binom{k}{2}, and every pair has the same rate, so line L3 draws the right waiting time and line L4 the right pair. The node made in line L5 is the block of the merged pair. By induction on the number of merges, the tree after the loop has the law of the Kingman coalescent tree.

Given the tree, the mutations of the model are a Poisson process on the branches with rate θ/2\theta/2. A Poisson process restricted to disjoint pieces is a set of independent Poisson processes, and the number of points on a piece of length ll is Poisson with mean θl/2\theta l / 2. So line L7 draws the right counts, independently over the branches. Under the infinite sites model each mutation is at a new site, and every copy below the mutated branch, and no other copy, carries the derived allele, which is line L8. The positions are uniform and independent of the tree. So the output has the law of the model. The full proof is below.

Proof: HUDSON samples exactly from the Kingman coalescent with infinite-sites mutationsfull

The model. The Kingman nn-coalescent is the continuous-time Markov chain (Πt)t≥0(\Pi_t)_{t \ge 0} on partitions of {1,…,n}\{1, \ldots, n\} that starts from the partition into singletons and in which, from a partition with k≥2k \ge 2 blocks, each of the (k2)\binom{k}{2} pairs of blocks merges at rate 1; the partition with one block is absorbing. Its genealogy is the tree whose leaves are the copies, whose internal nodes are the blocks formed by the merges, and whose node ages are the merge times. Given the genealogy, the mutations are a Poisson process of rate θ/2\theta/2 on the union of the branches (measured in time), and the sites have independent uniform positions in [0,1)[0, 1). Under the infinite sites model each mutation creates its own site, at which the copies below the mutated branch carry allele 1 and the others allele 0.

We use two standard facts.

Fact A (jump chain). For a continuous-time Markov chain with finitely many states and rates q(x,y)q(x, y), let λ(x)=∑y≠xq(x,y)\lambda(x) = \sum_{y \ne x} q(x, y). From state xx with λ(x)>0\lambda(x) > 0, the time to the next jump is exponential with rate λ(x)\lambda(x), the next state is yy with probability q(x,y)/λ(x)q(x, y)/\lambda(x), the two are independent, and given the next state the future is a new copy of the chain started there.

Fact B (Poisson restriction). If points form a Poisson process of rate cc on a set that is the disjoint union of intervals of lengths l1,…,lrl_1, \ldots, l_r, then the counts on the intervals are independent Poisson variables with means cl1,…,clrc l_1, \ldots, c l_r, and given the counts the points are independent and uniform on their intervals.

Lemma 1. After the loop of lines L2 to L5, the tree and its node ages have the law of the genealogy of the Kingman nn-coalescent.

Proof. The set AA in the algorithm is a partition of the copies: each element of AA is a node, and it stands for the set of copies below it. At the start (line L1) it is the partition into singletons at time 0. Suppose that before a pass, AA has k≥2k \ge 2 blocks and tt is the time of the last merge. In the chain, the total rate out of a partition with kk blocks is λ=(k2)\lambda = \binom{k}{2}, and each of the (k2)\binom{k}{2} merges has probability 1/(k2)1/\binom{k}{2}. By Fact A, the next merge happens after an exponential time with rate (k2)\binom{k}{2}, independent of which pair merges, and the pair is uniform. Line L3 draws that time and line L4 that pair, independently. Line L5 records the merge at the right time and makes the merged block a node with the two blocks as its children. By Fact A again, the rest of the chain is a new copy started from the new partition, which is what the next pass of the loop simulates with fresh random numbers. By induction on the number of passes, the sequence of partitions and merge times after n−1n - 1 passes has the law of the chain up to absorption, and so the tree has the law of the genealogy. □\square

Lemma 2. Given the tree, lines L6 to L9 output sites with the law of the infinite sites model on it.

Proof. The branches of the tree are disjoint intervals of time, one above each non-root node vv, of length lvl_v equal to the age of the parent minus the age of vv. By Fact B, the numbers of mutations on them are independent Poisson variables with means θlv/2\theta l_v / 2, which line L7 draws independently for each branch. The model gives each mutation its own site with a uniform position, independent of everything else, and allele 1 exactly in the copies below the branch, which line L8 does. Sorting in line L9 only puts the sites in the order of their positions. □\square

Theorem. HUDSON returns a tree and a sample matrix with the joint law of the Kingman coalescent with infinite-sites mutations of rate θ\theta.

Proof. The random numbers of lines L6 to L8 are drawn after the tree and independently of the draws of lines L3 and L4. By Lemma 1 the tree has the law of the model, and by Lemma 2 the conditional law of the sites given the tree is the law of the model. A joint law is the law of the first part times the conditional law of the second given the first. ■\blacksquare

The option with a fixed number of sites. Given the tree and given that the Poisson process has exactly ss points, by Fact B (applied to the union of all branches) the points are independent and uniform on the union of the branches. So each point is on branch vv with probability lv/Ll_v / L, with L=∑vlvL = \sum_v l_v, independently. The implementation draws the branches that way, so for a fixed tree it gives the law of the sites given S=sS = s. It does not give the law of the sample given S=sS = s under the model, because that would also weight the tree by the probability P(S=s∣L)P(S = s \mid L); like ms, the implementation draws the tree without this weight.

Remarks. The tests check the consequences E[TMRCA]=2(1−1/n)E[T_{\text{MRCA}}] = 2(1 - 1/n) and Var⁡[TMRCA]=∑k=2n1/(k2)2\operatorname{Var}[T_{\text{MRCA}}] = \sum_{k=2}^{n} 1/\binom{k}{2}^2, E[L]=2anE[L] = 2 a_n and Var⁡[L]=4bn\operatorname{Var}[L] = 4 b_n, E[S]=θanE[S] = \theta a_n and Var⁡[S]=θan+θ2bn\operatorname{Var}[S] = \theta a_n + \theta^2 b_n, E[ξi]=θ/iE[\xi_i] = \theta / i, the law 2i/(n(n−1))2i/(n(n-1)) of the size of the side of the root that holds copy 1, and the geometric law of SS for n=2n = 2, the last two by a chi-squared test.

Complexity

  • Tree. The loop runs n−1n - 1 times. With an array of the active lineages and removal by swapping with the last entry, each pass takes O(1)O(1) time, so the tree takes Θ(n)\Theta(n) time and space.
  • Mutations. Line L7 takes O(1)O(1) expected time per branch for small means. The ss sites take Θ(s)\Theta(s) to draw and Θ(slog⁡s)\Theta(s \log s) to sort, and the matrix has nsn s entries. In total Θ(n+ns+slog⁡s)\Theta(n + n s + s \log s) time. The expected number of sites is θan\theta a_n, which grows like θln⁡n\theta \ln n.
  • Space. The tree and the matrix: Θ(n+ns)\Theta(n + n s). Storing, for each site, only the branch it is on instead of a column of the matrix takes Θ(n+s)\Theta(n + s), which is what tree sequence formats do.
  • Against forward simulation. A Wright-Fisher simulation of 2N2N copies over the about 4N4N generations to the common ancestor of the sample costs Θ(N2)\Theta(N^2) time. The coalescent costs nothing for the copies that are not ancestors of the sample.

Properties

  • Exact for its model. The output has exactly the law of the Kingman coalescent with infinite-sites mutations, not an approximation of it. The coalescent is itself the large-population limit of the Wright-Fisher and Moran models.
  • Separation of genealogy and mutation. Under neutrality, mutations do not change the genealogy, so the tree can be drawn first. This is the reason the method works, and it fails for selected sites.
  • Tree shape and times are independent. The pairs of line L4 do not depend on the times of line L3. The shape of the tree is the random-joining (Yule-Harding) shape. If the two sides of the root are put in random order, the number of copies on the first side is uniform on 1,…,n−11, \ldots, n - 1.
  • Reproducible. With a seeded generator, the draws are made in a fixed order, so the same seed gives the same sample.
  • Expected values to check against. E[TMRCA]=2(1−1/n)E[T_{\text{MRCA}}] = 2(1 - 1/n), which is 1.81.8 for n=10n = 10; E[L]=2an=5.657937E[L] = 2 a_n = 5.657937 for n=10n = 10; E[S]=θanE[S] = \theta a_n; E[ξi]=θ/iE[\xi_i] = \theta / i; for n=2n = 2, SS is geometric with P(S=k)=(1/(1+θ))(θ/(1+θ))kP(S = k) = (1/(1 + \theta)) (\theta/(1 + \theta))^k. The tests check all of them.

Variants and improvements

  • Recombination. Hudson's 1983 algorithm adds recombination events: a lineage that carries ancestral material over a stretch of sequence splits at rate ρ/2\rho/2 times the length of that stretch, with ρ=4Nr\rho = 4Nr. The result is the ancestral recombination graph, with one tree per stretch of sequence. Its cost grows quickly with ρ\rho, because many lineages carry no material that reaches the sample in some regions.
  • Along the sequence. The sequentially Markov coalescent approximates the recombination process by building the local trees from left to right, each from the one before, which is much faster for long sequences.
  • Changing population size. If the size is N(t)=N0λ(t)N(t) = N_0 \lambda(t), kk lineages merge at rate (k2)/λ(t)\binom{k}{2}/\lambda(t). The waiting time is then drawn by inverting the integrated rate ∫(k2)/λ(s) ds\int \binom{k}{2}/\lambda(s)\, ds, which has a closed form for piecewise constant and exponential λ\lambda.
  • Structure and migration. With several subpopulations, the state is the number of lineages in each, lineages move between them at the migration rates, and only lineages in the same subpopulation merge. The next event is drawn as in the Gillespie algorithm, from the total rate of all coalescence and migration events.
  • Finite sites. Instead of the infinite sites rule, evolve a sequence down the tree under a substitution model such as Jukes-Cantor. Then repeat hits and back mutations occur.
  • Modern programs. ms (Hudson 2002) is the reference program. msprime records the output as a tree sequence and simulates whole chromosomes with recombination for large samples. Programs for selected sites (a sweep, for example) condition the coalescent on a trajectory of the selected allele, or simulate forward in time.

When to use it

Use it to get the distribution of a statistic under a neutral model when no formula is known, for example the null distribution of Tajima's D with recombination, the expected site frequency spectrum under a demographic history, or test data with a known genealogy for inference methods. It is also the simulator in approximate Bayesian computation for population genetics. For models with selection at many sites, or with complex ecology, use forward simulation instead.

Pitfalls

  • Time units. This page and most textbooks use units of 2N2N generations, with θ=4Nμ\theta = 4N\mu and θ/2\theta/2 per branch. ms uses units of 4N4N generations, so its times and its tree lengths are half of these; the mutation parameter θ\theta is the same. Mixing the two conventions gives errors by a factor of 2.
  • Haploid and diploid. For a haploid population of NN copies, time is in units of NN generations and θ=2Nμ\theta = 2N\mu. The nn of the algorithm is the number of sequences, not of individuals.
  • Choosing the pair. The pair must be uniform among all pairs. A common mistake is to join the first lineage with a random other one, or to join two neighbors in a list, which gives a wrong tree shape with the right times.
  • Fixed ss is not a fixed θ\theta. Samples given S=sS = s are not samples with θ=s/an\theta = s / a_n: the conditioning changes the law of the tree length, and the null distribution of a statistic can differ from the one with θ\theta fixed, most of all in the tails.
  • Random numbers. Simulation studies run millions of replicates; a generator with a short period or bad seeding across parallel jobs makes replicates dependent.

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.

biostoch.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Shared helper of the biology pages of https://algorithm.tamnd.com/. The authors are listed in prov/.
"""Random variates, exact probability mass functions and test helpers for
the stochastic pages of the biology area.

Every sampler takes a random.Random object as its first argument and never
uses the module-level random functions. Each sampler draws its random
numbers in the order that its docstring gives, so two runs with the same
seed give the same output.

Conventions:
- A reaction network with n species and m reactions is given by `stoich`, a
  list of the m change vectors nu_1, ..., nu_m. So stoich[j][i] is the entry
  S[i][j] of the n by m stoichiometric matrix S.
- `propensity(x)` takes the state as a tuple of n integer counts and returns
  the m propensities a_1(x), ..., a_m(x) as a sequence of floats >= 0.
- nbinom_pmf uses the mean mu and the dispersion alpha, with
  Var = mu + alpha mu^2. The size is r = 1 / alpha; alpha = 0 is Poisson.
- hypergeom_pmf(k, total, good, draws) is the probability of k good items
  in `draws` draws without replacement from `total` items of which `good`
  are good.

Requires Python 3.12 or later (random.Random.binomialvariate).
"""

from __future__ import annotations

import math
from statistics import NormalDist
from typing import Callable, List, Sequence, Tuple

State = Tuple[int, ...]

_POISSON_PART = 30.0


# Random variates

def poisson(rng, lam: float) -> int:
    """A Poisson(lam) variate.

    For lam <= 30, inversion of the cumulative distribution with one
    rng.random() draw. For lam > 30, the sum of p = ceil(lam / 30)
    independent Poisson(lam / p) variates, drawn one after the other by
    inversion (one rng.random() draw each).
    """
    if lam < 0 or math.isnan(lam):
        raise ValueError("lam must be >= 0")
    if lam == 0:
        return 0
    if lam > _POISSON_PART:
        parts = math.ceil(lam / _POISSON_PART)
        part = lam / parts
        return sum(_poisson_inversion(rng, part) for _ in range(parts))
    return _poisson_inversion(rng, lam)


def _poisson_inversion(rng, lam: float) -> int:
    u = rng.random()
    k = 0
    p = math.exp(-lam)
    cdf = p
    while u >= cdf:
        k += 1
        p *= lam / k
        if p == 0.0:
            # Rounding left u above the computed total mass; stop at the tail.
            break
        cdf += p
    return k


def binomial(rng, n: int, p: float) -> int:
    """A Binomial(n, p) variate by rng.binomialvariate (one call)."""
    if n < 0 or not 0.0 <= p <= 1.0:
        raise ValueError("need n >= 0 and 0 <= p <= 1")
    if n == 0 or p == 0.0:
        return 0
    if p == 1.0:
        return n
    return rng.binomialvariate(n, p)


def multinomial(rng, n: int, probs: Sequence[float]) -> List[int]:
    """A Multinomial(n, probs) vector by conditional binomials.

    probs are weights >= 0 with a positive sum; they need not sum to 1. Cell
    i gets Binomial(rest of n, probs[i] / rest of the weight), for i in
    order; the last cell with positive weight gets the rest.
    """
    if n < 0:
        raise ValueError("n must be >= 0")
    w = [float(q) for q in probs]
    if any(q < 0 for q in w):
        raise ValueError("weights must be >= 0")
    total = sum(w)
    if total <= 0:
        raise ValueError("weights must have a positive sum")
    last = max(i for i, q in enumerate(w) if q > 0)
    out = [0] * len(w)
    left = n
    rest = total
    for i in range(last):
        if left == 0:
            break
        if w[i] == 0:
            continue
        x = binomial(rng, left, min(1.0, w[i] / rest))
        out[i] = x
        left -= x
        rest -= w[i]
    out[last] += left
    return out


def categorical(rng, weights: Sequence[float]) -> int:
    """An index i with probability weights[i] / sum(weights).

    One draw u = rng.random() * sum(weights), then a cumulative search from
    index 0. Indices with weight 0 are never returned.
    """
    total = 0.0
    for w in weights:
        if w < 0:
            raise ValueError("weights must be >= 0")
        total += w
    if total <= 0:
        raise ValueError("weights must have a positive sum")
    u = rng.random() * total
    acc = 0.0
    last = -1
    for i, w in enumerate(weights):
        if w > 0:
            acc += w
            last = i
            if u < acc:
                return i
    return last


def ssa_direct(rng, x0: Sequence[int], stoich: Sequence[Sequence[int]],
               propensity: Callable[[State], Sequence[float]], t_end: float,
               max_events: int = 10 ** 6):
    """Gillespie's direct method from state x0 at time 0 up to time t_end.

    Each step computes a = propensity(x) and a0 = sum(a). If a0 = 0 the run
    stops. Otherwise it draws tau = rng.expovariate(a0) first. If
    t + tau > t_end the run stops, and no second number is drawn. Else it
    draws u = rng.random() * a0 and fires the first reaction j with
    a_1 + ... + a_j > u (a linear search), then adds stoich[j] to x.

    Returns (times, states, complete). times[0] = 0.0 and states[0] =
    tuple(x0); entry k > 0 is the time and the state just after event k.
    The state at t_end is states[-1]. complete is False only when the run
    stopped because max_events events had fired before t_end.
    """
    x = tuple(int(v) for v in x0)
    times = [0.0]
    states = [x]
    t = 0.0
    m = len(stoich)
    for _ in range(max_events):
        a = propensity(x)
        a0 = 0.0
        for v in a:
            if v < 0:
                raise ValueError("propensities must be >= 0")
            a0 += v
        if a0 <= 0.0:
            return times, states, True
        t += rng.expovariate(a0)
        if t > t_end:
            return times, states, True
        u = rng.random() * a0
        acc = 0.0
        j = -1
        for i in range(m):
            if a[i] > 0:
                acc += a[i]
                j = i
                if u < acc:
                    break
        nu = stoich[j]
        x = tuple(x[i] + nu[i] for i in range(len(x)))
        times.append(t)
        states.append(x)
    return times, states, False


# Sample statistics and test helpers

def mean_var(xs) -> Tuple[float, float]:
    """The mean and the unbiased sample variance (divisor n - 1) by the
    Welford method. The variance is 0.0 for fewer than two values."""
    n = 0
    mean = 0.0
    m2 = 0.0
    for x in xs:
        n += 1
        d = x - mean
        mean += d / n
        m2 += d * (x - mean)
    if n == 0:
        raise ValueError("empty sample")
    return mean, (m2 / (n - 1) if n > 1 else 0.0)


def check_mean(m: float, mu: float, var: float, n: int, z: float = 4.0) -> bool:
    """True when |m - mu| <= z sqrt(var / n): a sample mean m of n
    independent values with exact mean mu and exact variance var."""
    return abs(m - mu) <= z * math.sqrt(var / n)


# Exact probability mass functions

def log_choose(n: int, k: int) -> float:
    """ln C(n, k), or -inf when k < 0 or k > n."""
    if k < 0 or k > n:
        return -math.inf
    return math.lgamma(n + 1) - math.lgamma(k + 1) - math.lgamma(n - k + 1)


def binom_pmf(k: int, n: int, p: float) -> float:
    """P(K = k) for K ~ Binomial(n, p)."""
    if k < 0 or k > n:
        return 0.0
    if p == 0.0:
        return 1.0 if k == 0 else 0.0
    if p == 1.0:
        return 1.0 if k == n else 0.0
    return math.exp(log_choose(n, k) + k * math.log(p) + (n - k) * math.log1p(-p))


def poisson_pmf(k: int, lam: float) -> float:
    """P(K = k) for K ~ Poisson(lam)."""
    if k < 0:
        return 0.0
    if lam == 0:
        return 1.0 if k == 0 else 0.0
    return math.exp(k * math.log(lam) - lam - math.lgamma(k + 1))


def nbinom_pmf(k: int, mu: float, alpha: float) -> float:
    """P(K = k) for the negative binomial with mean mu and Var = mu + alpha mu^2."""
    if k < 0:
        return 0.0
    if alpha == 0:
        return poisson_pmf(k, mu)
    if mu == 0:
        return 1.0 if k == 0 else 0.0
    r = 1.0 / alpha
    return math.exp(math.lgamma(k + r) - math.lgamma(r) - math.lgamma(k + 1)
                    + r * math.log(r / (r + mu)) + k * math.log(mu / (r + mu)))


def hypergeom_pmf(k: int, total: int, good: int, draws: int) -> float:
    """P(K = k) for k good items in `draws` draws without replacement from
    `total` items of which `good` are good."""
    if k < 0 or k > good or draws - k < 0 or draws - k > total - good:
        return 0.0
    return math.exp(log_choose(good, k) + log_choose(total - good, draws - k)
                    - log_choose(total, draws))


def logsumexp(xs) -> float:
    """ln(sum of exp(x)) without overflow; -inf for an empty input."""
    xs = list(xs)
    if not xs:
        return -math.inf
    top = max(xs)
    if top == -math.inf:
        return -math.inf
    if top == math.inf:
        return math.inf
    return top + math.log(sum(math.exp(x - top) for x in xs))


# Tail probabilities

def _gamma_q(a: float, x: float) -> float:
    """The regularized upper incomplete gamma function Q(a, x)."""
    if a <= 0:
        raise ValueError("a must be > 0")
    if x <= 0:
        return 1.0
    log_front = -x + a * math.log(x) - math.lgamma(a)
    if x < a + 1.0:
        # Series for P(a, x).
        ap = a
        term = 1.0 / a
        total = term
        for _ in range(100000):
            ap += 1.0
            term *= x / ap
            total += term
            if abs(term) < abs(total) * 1e-16:
                break
        return max(0.0, 1.0 - total * math.exp(log_front))
    # Continued fraction for Q(a, x), by the modified Lentz method.
    tiny = 1e-300
    b = x + 1.0 - a
    c = 1.0 / tiny
    d = 1.0 / b
    h = d
    for i in range(1, 100000):
        an = -i * (i - a)
        b += 2.0
        d = an * d + b
        if abs(d) < tiny:
            d = tiny
        c = b + an / c
        if abs(c) < tiny:
            c = tiny
        d = 1.0 / d
        delta = d * c
        h *= delta
        if abs(delta - 1.0) < 1e-16:
            break
    return math.exp(log_front) * h


def chi2_sf(x: float, df: float) -> float:
    """P(X > x) for X chi-squared with df degrees of freedom."""
    if df <= 0:
        raise ValueError("df must be > 0")
    if x <= 0:
        return 1.0
    return _gamma_q(df / 2.0, x / 2.0)


_STD_NORMAL = NormalDist()


def normal_sf(x: float, mu: float = 0.0, sigma: float = 1.0) -> float:
    """P(X > x) for X ~ Normal(mu, sigma^2), by statistics.NormalDist."""
    return _STD_NORMAL.cdf(-(x - mu) / sigma)
coalescent_simulation.py 115 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/coalescent-simulation/. The authors are listed in prov/V8W27B.jsonl.
"""Hudson's algorithm: a neutral sample under the Kingman coalescent and the
infinite-sites model, without recombination.

Time runs backward from the sample at time 0 and is in units of 2N
generations, so k lineages merge at rate k (k - 1) / 2, and theta = 4 N mu is
the mutation rate of the whole locus. (The program ms uses units of 4N
generations; its times are half of these.)

Nodes 0 .. n-1 are the sampled copies. Each merge makes a new node, so the
internal nodes are n .. 2n-2, in the order in which they were made, and node
2n-2 is the root. parent[v] is the parent of node v (-1 for the root) and
time[v] is its age.

Random numbers are drawn in this order: first, for each merge, one
expovariate and one sample of two positions; then, for each branch in the
order of the node numbers, one Poisson count and one random() per mutation.
"""

from __future__ import annotations

from typing import List, Optional, Sequence, Tuple

from biostoch import categorical, poisson


def simulate_genealogy(rng, n: int) -> Tuple[List[int], List[float]]:
    """A Kingman coalescent tree of n sampled copies as (parent, time)."""
    if n < 1:
        raise ValueError("need n >= 1")
    parent = [-1] * n
    time = [0.0] * n
    active = list(range(n))  # @line L1
    t = 0.0
    while len(active) > 1:  # @line L2
        k = len(active)
        t += rng.expovariate(k * (k - 1) / 2.0)  # @line L3
        i, j = rng.sample(range(k), 2)  # @line L4
        u = len(parent)
        parent.append(-1)
        time.append(t)
        parent[active[i]] = u
        parent[active[j]] = u
        # Replace lineage i by u and remove lineage j.
        active[i] = u  # @line L5
        active[j] = active[-1]
        active.pop()
    return parent, time


def leaves_below(parent: Sequence[int], n: int) -> List[int]:
    """For each node, the bit mask of the sampled copies below it."""
    below = [1 << v if v < n else 0 for v in range(len(parent))]
    # A parent is made after its children, so it has a larger number.
    for v in range(len(parent)):
        if parent[v] >= 0:
            below[parent[v]] |= below[v]
    return below


def place_mutations(rng, parent: Sequence[int], time: Sequence[float], n: int,
                    theta: float, segsites: Optional[int] = None
                    ) -> Tuple[List[float], List[str]]:
    """Mutations on the tree under the infinite-sites model.

    With segsites None, each branch of length l gets Poisson(theta l / 2)
    mutations. With segsites = s, exactly s mutations are placed, each on a
    branch chosen with probability proportional to its length (as ms -s
    does); theta is then not used.

    Returns (positions, haplotypes): the positions in [0, 1) in increasing
    order, and one 0/1 string per sampled copy, with 1 for the derived allele.
    """
    if theta < 0:
        raise ValueError("need theta >= 0")
    below = leaves_below(parent, n)
    branches = [v for v in range(len(parent)) if parent[v] >= 0]
    lengths = [time[parent[v]] - time[v] for v in branches]
    sites = []
    if segsites is None:
        for v, length in zip(branches, lengths):  # @line L6
            count = poisson(rng, theta * length / 2.0)  # @line L7
            for _ in range(count):
                sites.append((rng.random(), below[v]))  # @line L8
    else:
        if segsites < 0:
            raise ValueError("need segsites >= 0")
        if segsites > 0 and not branches:
            raise ValueError("a sample of one copy has no branches")
        for _ in range(segsites):
            v = branches[categorical(rng, lengths)]
            sites.append((rng.random(), below[v]))
    sites.sort()  # @line L9
    positions = [x for x, _ in sites]
    haplotypes = ["".join("1" if (mask >> r) & 1 else "0" for _, mask in sites)
                  for r in range(n)]
    return positions, haplotypes


def simulate(rng, n: int, theta: float, segsites: Optional[int] = None):
    """One sample: (parent, time, positions, haplotypes)."""
    parent, time = simulate_genealogy(rng, n)
    positions, haplotypes = place_mutations(rng, parent, time, n, theta, segsites)
    return parent, time, positions, haplotypes


def tmrca(time: Sequence[float]) -> float:
    """The age of the root."""
    return max(time)


def total_branch_length(parent: Sequence[int], time: Sequence[float]) -> float:
    """The sum of the lengths of all branches."""
    return sum(time[p] - time[v] for v, p in enumerate(parent) if p >= 0)
test_coalescent_simulation.py 140 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/coalescent-simulation/. The authors are listed in prov/V8W27B.jsonl.

import random

import pytest

from biostoch import check_mean, chi2_sf, mean_var
from coalescent_simulation import (
    leaves_below,
    place_mutations,
    simulate,
    simulate_genealogy,
    tmrca,
    total_branch_length,
)


def harmonic(n, power=1):
    return sum(1.0 / i ** power for i in range(1, n))


def chi2_stat(observed, expected):
    return sum((o - e) ** 2 / e for o, e in zip(observed, expected))


def test_tree_structure():
    rng = random.Random(1)
    for n in (1, 2, 3, 7, 20):
        parent, time = simulate_genealogy(rng, n)
        assert len(parent) == 2 * n - 1
        assert parent.count(-1) == 1 and parent[-1] == -1
        for v, p in enumerate(parent):
            if p >= 0:
                assert p > v and time[p] > time[v]
        kids = [0] * len(parent)
        for p in parent:
            if p >= 0:
                kids[p] += 1
        assert kids[:n] == [0] * n and kids[n:] == [2] * (n - 1)
        assert leaves_below(parent, n)[-1] == (1 << n) - 1


def test_same_seed_same_sample():
    a = simulate(random.Random(42), 8, 3.0)
    b = simulate(random.Random(42), 8, 3.0)
    assert a == b


def test_columns_are_tree_splits():
    rng = random.Random(3)
    n = 9
    parent, time, positions, haps = simulate(rng, n, 6.0)
    assert positions == sorted(positions)
    assert all(0.0 <= x < 1.0 for x in positions)
    splits = set(leaves_below(parent, n)[:-1])
    for j in range(len(positions)):
        mask = sum(1 << r for r in range(n) if haps[r][j] == "1")
        assert mask in splits
        assert 1 <= bin(mask).count("1") <= n - 1


def test_times_and_lengths():
    rng = random.Random(10)
    n, reps = 10, 20000
    ts, ls = [], []
    for _ in range(reps):
        parent, time = simulate_genealogy(rng, n)
        ts.append(tmrca(time))
        ls.append(total_branch_length(parent, time))
    var_t = sum(4.0 / (k * (k - 1)) ** 2 for k in range(2, n + 1))
    m, _ = mean_var(ts)
    assert 2.0 * (1 - 1.0 / n) == pytest.approx(1.8)
    assert check_mean(m, 1.8, var_t, reps)
    m, _ = mean_var(ls)
    assert 2 * harmonic(n) == pytest.approx(5.657937, abs=1e-6)
    assert check_mean(m, 2 * harmonic(n), 4 * harmonic(n, 2), reps)


def test_root_split():
    # The side of the root that holds copy 0 has i copies with
    # probability 2 i / (n (n - 1)).
    rng = random.Random(77)
    n, reps = 6, 12000
    counts = [0] * n
    for _ in range(reps):
        parent, _ = simulate_genealogy(rng, n)
        below = leaves_below(parent, n)
        v = 0
        while parent[parent[v]] != -1:
            v = parent[v]
        counts[bin(below[v]).count("1")] += 1
    expected = [reps * 2 * i / (n * (n - 1)) for i in range(1, n)]
    assert chi2_sf(chi2_stat(counts[1:], expected), n - 2) > 0.001


def test_segregating_sites_and_spectrum():
    rng = random.Random(2002)
    n, theta, reps = 10, 5.0, 8000
    a, b = harmonic(n), harmonic(n, 2)
    ss = []
    xi = [[] for _ in range(n)]
    for _ in range(reps):
        _, _, positions, haps = simulate(rng, n, theta)
        ss.append(len(positions))
        row = [0] * n
        for j in range(len(positions)):
            row[sum(h[j] == "1" for h in haps)] += 1
        for i in range(1, n):
            xi[i].append(row[i])
    m, _ = mean_var(ss)
    assert check_mean(m, theta * a, theta * a + theta * theta * b, reps)
    for i in range(1, n):
        m, v = mean_var(xi[i])
        assert check_mean(m, theta / i, v, reps)


def test_two_copies_geometric():
    # For n = 2, P(S = k) = (1 / (1 + theta)) (theta / (1 + theta))^k.
    rng = random.Random(5)
    theta, reps, top = 1.0, 20000, 6
    counts = [0] * (top + 1)
    for _ in range(reps):
        s = len(simulate(rng, 2, theta)[2])
        counts[min(s, top)] += 1
    q = theta / (1 + theta)
    probs = [(1 - q) * q ** k for k in range(top)]
    probs.append(1 - sum(probs))
    expected = [reps * p for p in probs]
    assert chi2_sf(chi2_stat(counts, expected), top) > 0.001


def test_fixed_number_of_sites():
    rng = random.Random(8)
    parent, time = simulate_genealogy(rng, 7)
    positions, haps = place_mutations(rng, parent, time, 7, 0.0, segsites=12)
    assert len(positions) == 12 and all(len(h) == 12 for h in haps)
    assert place_mutations(rng, parent, time, 7, 0.0) == ([], [""] * 7)
    with pytest.raises(ValueError):
        place_mutations(rng, parent, time, 7, -1.0)

History

Kingman described the coalescent in 1982, and Hudson's 1983 paper on intragenic recombination simulated samples backward in time with coalescence and recombination events, the first coalescent simulation. Hudson's 1990 review in Oxford Surveys in Evolutionary Biology explained the method of drawing a genealogy and then placing mutations on it, and his program ms (2002) became the standard simulator for many years. Later programs simulate recombination along whole chromosomes, such as MaCS with the sequentially Markov approximation and msprime with exact recombination and tree sequences.

References

  1. Richard R. Hudson, Properties of a neutral allele model with intragenic recombination, Theoretical Population Biology 23(2), 1983, pp. 183-201 (samples simulated backward in time, with coalescence and recombination events of the ancestral lineages)
  2. Richard R. Hudson, Generating samples under a Wright-Fisher neutral model of genetic variation, Bioinformatics 18(2), 2002, pp. 337-338 (the program ms, its options for theta, a fixed number of segregating sites and recombination, and its time unit of 4N generations)
  3. J. F. C. Kingman, The coalescent, Stochastic Processes and their Applications 13(3), 1982, pp. 235-248 (the n-coalescent and its rates)
  4. John Wakeley, Coalescent Theory, An Introduction, Roberts and Company, 2009, Chapter 3 (the coalescent) and Chapter 4 (mutations on the genealogy)

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.average
  • a full proof of time.best
  • 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