Algorithm Search⌘K

Modelintro

Wright-Fisher model

Also called Wright-Fisher process.

A population of N diploids (2N gene copies) in discrete generations: each new copy picks a parent copy uniformly at random, so the allele count is binomial each generation.

The Wright-Fisher model is the standard model of a finite population in population genetics. A population of NN diploid individuals carries 2N2N copies of a gene, generations do not overlap, and each copy of the next generation is a copy of a parent copy chosen uniformly at random. So the number of copies of an allele is a Markov chain whose steps are binomial draws. It is the base of the theory of genetic drift, of the diffusion approximation and of the Kingman coalescent.

The machine

The state. One locus with two alleles, AA and aa. The state is Xt∈{0,1,…,2N}X_t \in \{0, 1, \ldots, 2N\}, the number of copies of AA in generation tt, and pt=Xt/(2N)p_t = X_t/(2N) is the allele frequency. Time is in generations. For a haploid population of NN copies, replace 2N2N by NN everywhere on this page.

The step without selection. Each of the 2N2N copies of generation t+1t + 1 picks a parent copy among the 2N2N copies of generation tt, uniformly and independently of the other copies. So, given Xt=iX_t = i,

Xt+1∼Binomial(2N,i2N),Pij=(2Nj)(i2N)j(1−i2N)2N−j.X_{t+1} \sim \text{Binomial}\Big(2N, \frac{i}{2N}\Big), \qquad P_{ij} = \binom{2N}{j} \Big(\frac{i}{2N}\Big)^j \Big(1 - \frac{i}{2N}\Big)^{2N - j}.

The states 0 (loss of AA) and 2N2N (fixation of AA) are absorbing; all other states are transient.

The step with selection. Give the genotypes AAAA, AaAa and aaaa the fitnesses 1+s1 + s, 1+hs1 + hs and 11. Selection acts first, as in an infinite population, and then the 2N2N copies are drawn with the frequency p′p' after selection. With q=1−pq = 1 - p and the mean fitness wˉ=p2(1+s)+2pq(1+hs)+q2\bar w = p^2(1 + s) + 2pq(1 + hs) + q^2,

p′=p (p(1+s)+q(1+hs))wˉ,Xt+1∼Binomial(2N,p′).p' = \frac{p\,\big(p(1 + s) + q(1 + hs)\big)}{\bar w}, \qquad X_{t+1} \sim \text{Binomial}(2N, p').

Kimura's genic form, with fitnesses 11, 1+s1 + s and 1+2s1 + 2s, is the case s→2ss \to 2s, h=1/2h = 1/2. Mutation enters the same way: change p′p' by the mutation step before the draw.

A simulation.

  1. WRIGHT-FISHER(i0, 2N, T, s, h)
  2. 1X_0 ← i0
  3. 2for t ← 0 to T - 1 do
  4. 3p ← X_t / (2N); q ← 1 - p
  5. 4p' ← p (p (1 + s) + q (1 + h s)) / (p² (1 + s) + 2 p q (1 + h s) + q²)
  6. 5X_{t+1} ← a draw from Binomial(2N, p')
  7. 6return X_0, ..., X_T

Each generation costs one binomial draw, which takes O(1)O(1) expected time with a good sampler, so TT generations take O(T)O(T) time. The implementation stops early when XtX_t reaches 0 or 2N2N. It also builds the exact (2N+1)×(2N+1)(2N + 1) \times (2N + 1) transition matrix and solves for the absorption probabilities and times; the tests compare the simulation with these exact values for 2N=202N = 20.

A trace. With seed 7, 2N=202N = 20, no selection and X0=5X_0 = 5, the implementation gives 5,3,2,1,1,05, 3, 2, 1, 1, 0: the allele is lost in generation 5. From 5 copies the exact chance of loss is 15/20=0.7515/20 = 0.75.

What it counts

  • XtX_t and ptp_t, the count and frequency of an allele in each generation.
  • The probability that an allele fixes or is lost, and the time until one of these happens.
  • The expected heterozygosity Ht=E[2ptqt]H_t = \mathbb E[2 p_t q_t], the chance that two copies drawn with replacement carry different alleles.
  • The genealogy of a sample of copies, by following parents back in time.
  • With mutation, the number of alleles and their frequencies at equilibrium, as in the infinite alleles model.

Relation to other models

  • Moran model. One birth and one death per step, so generations overlap. Many results agree after a change of time scale: genetic drift is twice as fast per generation in the Moran model, which has effective population size N/2N/2 in Wright-Fisher units for NN copies.
  • Cannings models. Wright-Fisher is the exchangeable model in which the offspring numbers of the 2N2N copies are multinomial. Other offspring laws with variance σ2\sigma^2 per copy behave like a Wright-Fisher population of size 2N/σ22N/\sigma^2 copies (Ewens 2004, Section 3.3).
  • Wright-Fisher diffusion. For large NN, with time in units of 2N2N generations and NsNs fixed, ptp_t tends to a diffusion with generator 12x(1−x) d2/dx2\tfrac12 x(1 - x)\,d^2/dx^2 plus a selection drift. The Kimura fixation probability is a result of this limit.
  • Kingman coalescent. Two copies have the same parent copy with probability 1/(2N)1/(2N). With time in units of 2N2N generations, the genealogy of a sample tends to the Kingman coalescent.
  • Galton-Watson process. While an allele is rare, the copies of it reproduce almost independently with Poisson offspring numbers of mean 1+s1 + s for a genic advantage ss, so its early fate is that of a branching process.

Known results in the model

Each result is for the neutral chain (s=0s = 0) unless it says otherwise, with time in generations.

The frequency is a martingale, and an allele fixes with probability equal to its frequency. E[Xt+1∣Xt]=Xt\mathbb E[X_{t+1} \mid X_t] = X_t, and Pr⁡(fixation∣X0=i)=i/(2N)\Pr(\text{fixation} \mid X_0 = i) = i/(2N).

Proof. The mean of Binomial(2N,i/(2N))\text{Binomial}(2N, i/(2N)) is ii, so XtX_t is a martingale. From each transient state the chain moves to 0 in one step with probability (1−i/(2N))2N>0(1 - i/(2N))^{2N} > 0, so it is absorbed in finite time with probability 1, and the absorption time τ\tau has a geometric tail. XtX_t is bounded by 2N2N, so the optional stopping theorem gives E[Xτ]=i\mathbb E[X_\tau] = i. Since Xτ∈{0,2N}X_\tau \in \{0, 2N\}, E[Xτ]=2NPr⁡(Xτ=2N)\mathbb E[X_\tau] = 2N \Pr(X_\tau = 2N). □\square

Heterozygosity decays at the rate 1/(2N)1/(2N). Ht=H0 (1−1/(2N))tH_t = H_0\,(1 - 1/(2N))^t, where Ht=E[2ptqt]H_t = \mathbb E[2 p_t q_t].

Proof. Given pt=pp_t = p, pt+1p_{t+1} has mean pp and variance pq/(2N)pq/(2N). So E[pt+12∣pt]=p2+pq/(2N)\mathbb E[p_{t+1}^2 \mid p_t] = p^2 + pq/(2N) and E[pt+1qt+1∣pt]=p−p2−pq/(2N)=pq (1−1/(2N))\mathbb E[p_{t+1} q_{t+1} \mid p_t] = p - p^2 - pq/(2N) = pq\,(1 - 1/(2N)). Take expectations and use induction on tt. □\square

For N=50N = 50 and t=10t = 10 the ratio is 0.9910≈0.9043820.99^{10} \approx 0.904382. The half-life of the heterozygosity is about 2Nln⁡22N \ln 2 generations, so drift removes variation in a time of order NN generations.

The variance of the frequency. Var⁡(pt)=p0q0(1−(1−1/(2N))t)\operatorname{Var}(p_t) = p_0 q_0 \big(1 - (1 - 1/(2N))^t\big), which tends to p0q0p_0 q_0, the variance of a frequency that is 0 or 1 with chances q0q_0 and p0p_0.

Proof. E[pt]=p0\mathbb E[p_t] = p_0 and, from the previous result, E[ptqt]=p0q0(1−1/(2N))t\mathbb E[p_t q_t] = p_0 q_0 (1 - 1/(2N))^t. Then Var⁡(pt)=E[pt]−E[ptqt]−p02\operatorname{Var}(p_t) = \mathbb E[p_t] - \mathbb E[p_t q_t] - p_0^2. □\square

The eigenvalues of the transition matrix. They are λ0=λ1=1\lambda_0 = \lambda_1 = 1 and λj=∏i=0j−1(1−i2N)\lambda_j = \prod_{i=0}^{j-1} \big(1 - \tfrac{i}{2N}\big) for j=2,…,2Nj = 2, \ldots, 2N.

Proof. For Y∼Binomial(n,p)Y \sim \text{Binomial}(n, p) the falling factorial moments are E[Y(Y−1)⋯(Y−j+1)]=n(n−1)⋯(n−j+1) pj\mathbb E[Y(Y-1)\cdots(Y-j+1)] = n(n-1)\cdots(n-j+1)\,p^j. With n=2Nn = 2N and p=x/(2N)p = x/(2N), the matrix maps the polynomial x(x−1)⋯(x−j+1)x(x-1)\cdots(x-j+1) to λjxj\lambda_j x^j plus a polynomial of lower degree. So in the basis of falling factorials of degree 0,…,2N0, \ldots, 2N, which spans all functions on {0,…,2N}\{0, \ldots, 2N\}, the matrix is triangular with diagonal λ0,…,λ2N\lambda_0, \ldots, \lambda_{2N}. □\square

The two eigenvalues equal to 1 belong to the two absorbing states. The largest other one, λ2=1−1/(2N)\lambda_2 = 1 - 1/(2N), is the rate of the heterozygosity result above, and it sets the time scale of absorption.

The time to absorption. The exact mean comes from the linear system (I−Q) t=1(I - Q)\,t = \mathbf 1 on the transient states. For 2N=202N = 20 it is 26.22926.229 generations from X0=10X_0 = 10 and 7.2317.231 from X0=1X_0 = 1. The diffusion approximation gives −4N(pln⁡p+qln⁡q)-4N(p \ln p + q \ln q) generations, here 27.72627.726 and 7.9417.941: about 6 and 10 percent too high at this small size.

The genealogy. Two copies of one generation have the same parent copy with probability 1/(2N)1/(2N), so the number of generations back to their common ancestor is geometric with mean 2N2N. A sample of kk copies loses a lineage with probability (k2)/(2N)+O(1/N2)\binom{k}{2}/(2N) + O(1/N^2) per generation. This gives the Kingman coalescent in units of 2N2N generations.

With selection. There is no closed form for the fixation probability of the discrete chain. The implementation solves the linear system exactly. For N=10N = 10 (2N=202N = 20) and fitnesses 11, 1.051.05 and 1.11.1, one new copy fixes with probability 0.107650.10765, against 0.050.05 without selection and 0.110060.11006 by Kimura's diffusion formula.

Code

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)
wright_fisher_model.py 137 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/wright-fisher-model/. The authors are listed in prov/ZKD5QR.jsonl.
"""The Wright-Fisher model of one biallelic locus: a simulator and the exact
Markov chain.

The population has N diploid individuals, so 2N gene copies, in discrete
generations. X_t is the number of copies of allele A in generation t. Each
copy of generation t + 1 picks a parent copy independently. Without
selection the parent is uniform, so X_(t+1) given X_t = i is
Binomial(2N, i / (2N)). With selection the genotypes AA, Aa and aa have
fitnesses 1 + s, 1 + h s and 1, and the copies are drawn with the frequency
after selection.

The functions take the number of copies two_n = 2N. With Fraction values of
s and h (or s = 0) and exact=True, the chain is computed in exact rational
arithmetic.
"""

from __future__ import annotations

import math
from fractions import Fraction
from typing import Dict, List, Sequence

from biostoch import binom_pmf, binomial


def selected_frequency(p, s=0, h=Fraction(1, 2)):
    """The frequency of A after selection with fitnesses 1 + s, 1 + h s, 1
    for AA, Aa, aa, given the frequency p before selection."""
    q = 1 - p
    w_A = p * (1 + s) + q * (1 + h * s)  # mean fitness of a copy of A
    w_bar = p * p * (1 + s) + 2 * p * q * (1 + h * s) + q * q
    return p * w_A / w_bar


def simulate(rng, i0: int, two_n: int, generations: int, s: float = 0.0,
             h: float = 0.5) -> List[int]:
    """The counts X_0, ..., X_T of allele A for T = generations steps.

    Each step makes one draw from Binomial(2N, p') by biostoch.binomial, where
    p' is the frequency after selection. The run stops early when the
    allele is lost or fixed, because the chain cannot leave these states."""
    if not 0 <= i0 <= two_n or two_n < 1:
        raise ValueError("need 0 <= i0 <= 2N and 2N >= 1")
    xs = [i0]  # @line L1
    x = i0
    for _ in range(generations):  # @line L2
        if x == 0 or x == two_n:
            break
        p = x / two_n  # @line L3
        p_sel = selected_frequency(p, s, h)  # @line L4
        x = binomial(rng, two_n, min(1.0, max(0.0, p_sel)))  # @line L5
        xs.append(x)
    return xs  # @line L6


def run_to_absorption(rng, i0: int, two_n: int, s: float = 0.0, h: float = 0.5,
                      max_generations: int = 10 ** 6):
    """Run until loss or fixation. Returns (fixed, generations)."""
    x = i0
    t = 0
    while 0 < x < two_n:
        if t >= max_generations:
            raise RuntimeError("no absorption within max_generations")
        x = binomial(rng, two_n, min(1.0, max(0.0, selected_frequency(x / two_n, s, h))))
        t += 1
    return x == two_n, t


def transition_matrix(two_n: int, s=0, h=Fraction(1, 2), exact: bool = False):
    """The (2N + 1) by (2N + 1) matrix P[i][j] = Pr(X_(t+1) = j | X_t = i)."""
    rows = []
    for i in range(two_n + 1):
        if exact:
            p = selected_frequency(Fraction(i, two_n), Fraction(s), Fraction(h))
            q = 1 - p
            rows.append([math.comb(two_n, j) * p ** j * q ** (two_n - j) for j in range(two_n + 1)])
        else:
            p = selected_frequency(i / two_n, s, h)
            rows.append([binom_pmf(j, two_n, min(1.0, max(0.0, p))) for j in range(two_n + 1)])
    return rows


def _solve(a: List[list], b: List[list]) -> List[list]:
    """Solve a x = b by Gaussian elimination; b has one column per right side.
    Works for floats (partial pivoting) and for Fractions (exact)."""
    n = len(a)
    m = [row[:] + rhs[:] for row, rhs in zip(a, b)]
    k = len(b[0])
    for col in range(n):
        piv = max(range(col, n), key=lambda r: abs(m[r][col]))
        if m[piv][col] == 0:
            raise ZeroDivisionError("singular system")
        m[col], m[piv] = m[piv], m[col]
        for r in range(n):
            if r != col and m[r][col] != 0:
                f = m[r][col] / m[col][col]
                for c in range(col, n + k):
                    m[r][c] -= f * m[col][c]
    return [[m[r][n + c] / m[r][r] for c in range(k)] for r in range(n)]


def absorption(two_n: int, s=0, h=Fraction(1, 2), exact: bool = False) -> Dict[str, list]:
    """Exact fixation probabilities and the first two moments of the time to
    absorption (in generations), for each start i = 0, ..., 2N.

    Solves (I - Q) u = r, (I - Q) t = 1 and (I - Q) m2 = 1 + 2 Q t, where Q is
    the transition matrix on the interior states 1, ..., 2N - 1 and r is the
    column of the jumps to 2N."""
    P = transition_matrix(two_n, s, h, exact)
    zero, one = (Fraction(0), Fraction(1)) if exact else (0.0, 1.0)
    inner = range(1, two_n)
    if two_n == 1:
        return {"fix": [zero, one], "time": [zero, zero], "time2": [zero, zero]}
    a = [[(one if i == j else zero) - P[i][j] for j in inner] for i in inner]
    rhs = [[P[i][two_n], one] for i in inner]
    sol = _solve(a, rhs)
    u = [row[0] for row in sol]
    t = [row[1] for row in sol]
    rhs2 = [[one + 2 * sum(P[i][j] * t[j - 1] for j in inner)] for i in inner]
    m2 = [row[0] for row in _solve(a, rhs2)]
    return {"fix": [zero] + u + [one], "time": [zero] + t + [zero], "time2": [zero] + m2 + [zero]}


def propagate(dist: Sequence, P: List[list], steps: int) -> list:
    """The law of X_t after `steps` generations from the law dist of X_0."""
    d = list(dist)
    n = len(d)
    for _ in range(steps):
        d = [sum(d[i] * P[i][j] for i in range(n)) for j in range(n)]
    return d


def heterozygosity_decay(N: int, t: int) -> float:
    """E[H_t] / H_0 = (1 - 1/(2N))^t under neutral drift, N diploids."""
    return (1.0 - 1.0 / (2 * N)) ** t
test_wright_fisher_model.py 132 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/wright-fisher-model/. The authors are listed in prov/ZKD5QR.jsonl.

import math
import random
from fractions import Fraction

from biostoch import binom_pmf, chi2_sf
from wright_fisher_model import (
    absorption,
    heterozygosity_decay,
    propagate,
    run_to_absorption,
    selected_frequency,
    simulate,
    transition_matrix,
)


def chi2_against(counts, probs, reps):
    """Pearson statistic with the cells of expected count < 5 pooled into one."""
    stat, df = 0.0, -1
    pool_o, pool_e = 0, 0.0
    for k, p in enumerate(probs):
        e = reps * p
        if e < 5:
            pool_o += counts.get(k, 0)
            pool_e += e
        else:
            stat += (counts.get(k, 0) - e) ** 2 / e
            df += 1
    if pool_e > 0:
        stat += (pool_o - pool_e) ** 2 / pool_e
        df += 1
    return stat, df


def test_one_step_is_binomial():
    rng = random.Random(1931)
    two_n, i, reps = 20, 7, 4000
    for s, h in ((0.0, 0.5), (0.3, 0.25)):
        counts = {}
        for _ in range(reps):
            x = simulate(rng, i, two_n, 1, s, h)[1]
            counts[x] = counts.get(x, 0) + 1
        p = selected_frequency(i / two_n, s, h)
        probs = [binom_pmf(k, two_n, p) for k in range(two_n + 1)]
        stat, df = chi2_against(counts, probs, reps)
        assert chi2_sf(stat, df) > 0.001


def test_selected_frequency():
    # Genic selection: fitnesses 1 + 2s', 1 + s', 1 gives p' = p (1 + s' + s' p) / (1 + 2 s' p).
    sp = Fraction(1, 10)
    p = Fraction(3, 10)
    assert selected_frequency(p, 2 * sp, Fraction(1, 2)) == p * (1 + sp + sp * p) / (1 + 2 * sp * p)
    assert selected_frequency(p, 0) == p
    assert selected_frequency(Fraction(0), Fraction(1, 2)) == 0
    assert selected_frequency(Fraction(1), Fraction(1, 2)) == 1


def test_rows_sum_to_one_and_martingale():
    for two_n in (1, 2, 5, 10):
        P = transition_matrix(two_n, exact=True)
        for i, row in enumerate(P):
            assert sum(row) == 1
            assert sum(j * pj for j, pj in enumerate(row)) == i


def test_neutral_fixation_is_initial_frequency():
    for two_n in (2, 6, 10):
        res = absorption(two_n, exact=True)
        assert res["fix"] == [Fraction(i, two_n) for i in range(two_n + 1)]
    res = absorption(20)
    for i in range(21):
        assert abs(res["fix"][i] - i / 20) < 1e-12


def test_exact_moments_by_propagation():
    # E[X_t] = X_0, E[H_t] = H_0 (1 - 1/(2N))^t and Var(p_t) = p0 q0 (1 - (1 - 1/(2N))^t).
    two_n, i0, t = 10, 3, 6
    P = transition_matrix(two_n, exact=True)
    d = propagate([Fraction(int(k == i0)) for k in range(two_n + 1)], P, t)
    p0 = Fraction(i0, two_n)
    lam = 1 - Fraction(1, two_n)
    mean_p = sum(Fraction(k, two_n) * dk for k, dk in enumerate(d))
    het = sum(2 * Fraction(k, two_n) * (1 - Fraction(k, two_n)) * dk for k, dk in enumerate(d))
    var_p = sum((Fraction(k, two_n) - p0) ** 2 * dk for k, dk in enumerate(d))
    assert mean_p == p0
    assert het == 2 * p0 * (1 - p0) * lam ** t
    assert var_p == p0 * (1 - p0) * (1 - lam ** t)


def test_heterozygosity_check_value():
    assert abs(heterozygosity_decay(50, 10) - 0.904382) < 5e-7


def test_simulated_fixation_against_exact_chain():
    # N = 10 diploids (2N = 20), fitnesses 1 + 2s, 1 + s, 1 with s = 0.05, one copy.
    rng = random.Random(1962)
    two_n, s, reps = 20, 0.05, 6000
    res = absorption(two_n, 2 * s, 0.5)
    u = res["fix"][1]
    assert abs(u - 0.10765) < 5e-6
    fixed = sum(run_to_absorption(rng, 1, two_n, 2 * s, 0.5)[0] for _ in range(reps))
    z = 4
    assert abs(fixed / reps - u) <= z * math.sqrt(u * (1 - u) / reps)


def test_simulated_absorption_time_against_exact_chain():
    rng = random.Random(2)
    two_n, i0, reps = 20, 10, 3000
    res = absorption(two_n)
    mu = res["time"][i0]
    var = res["time2"][i0] - mu * mu
    assert abs(mu - 26.229) < 5e-4
    total = sum(run_to_absorption(rng, i0, two_n)[1] for _ in range(reps))
    z = 4
    assert abs(total / reps - mu) <= z * math.sqrt(var / reps)


def test_edges():
    rng = random.Random(0)
    assert simulate(rng, 0, 10, 5) == [0]
    assert simulate(rng, 10, 10, 5) == [10]
    assert absorption(1, exact=True)["fix"] == [0, 1]
    try:
        simulate(rng, 11, 10, 1)
    except ValueError:
        pass
    else:
        raise AssertionError("expected ValueError")

References

  1. Wright 1931, pp. 97-159 (random sampling of the gametes in a population of size N, and the loss of heterozygosity at the rate 1/(2N) per generation)
  2. Fisher 1930, the random survival of genes in a finite population
  3. Warren J. Ewens, Mathematical Population Genetics I, Theoretical Introduction, 2nd edition, Springer, 2004, Section 3.2 (the Wright-Fisher model with two alleles, p. 92), Section 3.3 (Cannings models, p. 99) and Section 4.4 (the absorption time in the diffusion approximation, p. 140)
  4. John H. Gillespie, Population Genetics, A Concise Guide, 2nd edition, Johns Hopkins University Press, 2004, Section 2.2 (the decay of heterozygosity) and Section 2.6 (the coalescent)

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 proofH0 no proof
  • add a proof in proofs/ (06.5)
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)
WritingW4 complete
  • a review of the text: no review record reviews/ZKD5QR/text.yaml