Algorithm Search⌘K

Modelcore

Moran model

Also called Moran process.

A population model with overlapping generations: at each step one individual reproduces and one dies, so the allele count is a birth-death chain that moves by at most one.

The Moran model is a model of a finite population in which generations overlap. At each step one individual is chosen to reproduce and one is chosen to die, and the offspring takes the place of the one that died. So the number of individuals of one type changes by at most one per step, and it is a birth-death process in discrete time. This makes exact formulas for fixation probabilities and absorption times easy to get, which is why the model is used next to the Wright-Fisher model.

The machine

The state. A haploid population of NN individuals of two types, AA and aa. The state is X∈{0,…,N}X \in \{0, \ldots, N\}, the number of AA individuals. Time is in steps, and one generation is NN steps, so each individual lives one generation on average. For a diploid population, Moran models are usually applied to the 2N2N gene copies; this page keeps NN for the number of individuals of the haploid model.

The step. Type AA has fitness rr and type aa has fitness 1 (the neutral case is r=1r = 1). In each step:

  1. One individual is chosen to reproduce, with probability proportional to fitness, so it is of type AA with probability rX/(rX+N−X)rX/(rX + N - X).
  2. One individual is chosen uniformly to die, so it is of type AA with probability X/NX/N. The same individual can be chosen in both draws.
  3. The offspring, of the type of its parent, replaces the one that died.

So from X=iX = i the chain moves to i+1i + 1 with probability bib_i, to i−1i - 1 with probability did_i, and stays with probability 1−bi−di1 - b_i - d_i, where

bi=riri+N−i⋅N−iN,di=N−iri+N−i⋅iN.b_i = \frac{r i}{r i + N - i} \cdot \frac{N - i}{N}, \qquad d_i = \frac{N - i}{r i + N - i} \cdot \frac{i}{N}.

The states 0 and NN are absorbing. The ratio di/bi=1/rd_i/b_i = 1/r does not depend on ii; this is the reason for the simple closed forms below.

A simulation.

  1. MORAN(i0, N, r, T)
  2. 1X ← i0
  3. 2for k ← 1 to T do
  4. 3B ← 1 with probability r X / (r X + N - X), else 0 (the parent is of type A)
  5. 4D ← 1 with probability X / N, else 0 (the one that dies is of type A)
  6. 5X ← X + B - D
  7. 6return the path of X

Each step costs two Bernoulli draws, so TT steps take O(T)O(T) time. The implementation stops when XX reaches 0 or NN, and it solves the tridiagonal systems for the exact absorption times.

A trace. With seed 7, N=10N = 10, r=1r = 1 and X0=3X_0 = 3, the implementation goes down to 1 copy, back up to 3, down to 1 again, and then rises to fixation after 86 steps (8.6 generations). The exact mean time to absorption from 3 is 56.456.4 steps. With r=1.1r = 1.1, X0=1X_0 = 1 and the same seed, the mutant dies in the second step.

What it counts

  • The number XX of individuals of one type after each birth and death.
  • The probability that a type fixes, in particular a single mutant.
  • The number of steps (or generations, dividing by NN) to fixation or loss.
  • With mutation, the number of types and their frequencies, as in the infinite alleles model.
  • The genealogy of a sample, which merges two lineages when the newborn and its parent are both ancestors of the sample.

Relation to other models

  • Wright-Fisher model. In Wright-Fisher, all individuals are replaced at once in each generation; in Moran, one at a time. Per generation, drift in the Moran model is twice as fast as in a haploid Wright-Fisher population of the same size: a Moran population of NN individuals behaves like a Wright-Fisher population of N/2N/2 copies. So its effective population size is N/2N/2. The variance of the number of offspring per generation is 2 in Moran and 1 in Wright-Fisher, and this factor explains the difference.
  • Wright-Fisher diffusion. With time in units of N2/2N^2/2 steps (N/2N/2 generations) and NsNs fixed, the frequency X/NX/N tends to the same diffusion as the Wright-Fisher frequency.
  • Kingman coalescent. A step merges two of kk sample lineages with probability k(k−1)/N2k(k-1)/N^2, so the genealogy tends to the Kingman coalescent in units of N2/2N^2/2 steps.
  • Galton-Watson process and birth-death process. A rare type in a large population grows like a birth-death process with birth rate rr and death rate 1 per unit of time, and its survival probability 1−1/r1 - 1/r is the large NN limit of the fixation probability.
  • Moran process on graphs. If individuals sit on the vertices of a graph and the offspring replaces a neighbour, the fixation probability can depend on the graph. On a complete graph it is the model of this page.

Known results in the model

Fixation probability. With r≠1r \ne 1, a type AA that starts with ii individuals fixes with probability

πi=1−r−i1−r−N,π1=1−1/r1−1/rN,\pi_i = \frac{1 - r^{-i}}{1 - r^{-N}}, \qquad \pi_1 = \frac{1 - 1/r}{1 - 1/r^N},

and with r=1r = 1, πi=i/N\pi_i = i/N.

Proof. The steps that stay in place do not change the outcome, so πi=bibi+diπi+1+dibi+diπi−1\pi_i = \frac{b_i}{b_i + d_i}\pi_{i+1} + \frac{d_i}{b_i + d_i}\pi_{i-1} for 0<i<N0 < i < N, with π0=0\pi_0 = 0 and πN=1\pi_N = 1. Write γ=di/bi=1/r\gamma = d_i/b_i = 1/r. Then πi+1−πi=γ(πi−πi−1)\pi_{i+1} - \pi_i = \gamma (\pi_i - \pi_{i-1}), so πi+1−πi=γiπ1\pi_{i+1} - \pi_i = \gamma^i \pi_1, and πi=π1(1+γ+⋯+γi−1)\pi_i = \pi_1 (1 + \gamma + \cdots + \gamma^{i-1}). The condition πN=1\pi_N = 1 fixes π1\pi_1, and summing the geometric series gives the formula. For r=1r = 1 all differences are equal. □\square

For N=10N = 10 and r=1.1r = 1.1, π1=0.147950\pi_1 = 0.147950, against 1/N=0.11/N = 0.1 without selection. As N→∞N \to \infty with rr fixed, π1→1−1/r\pi_1 \to 1 - 1/r, which is about ss for r=1+sr = 1 + s. For r=1.01r = 1.01 it is 0.01570.0157 with N=100N = 100 and 0.0099010.009901 with N=1000N = 1000. A haploid Wright-Fisher population gives about 2s2s, twice as much, because its offspring variance is half as large.

Absorption time, neutral case. With r=1r = 1, the mean number of steps to absorption from ii is

ti=N((N−i)∑j=1i1N−j+i∑j=i+1N−11j).t_i = N \Big( (N - i) \sum_{j=1}^{i} \frac{1}{N - j} + i \sum_{j=i+1}^{N-1} \frac{1}{j} \Big).

Proof. The mean time satisfies ti=1+biti+1+diti−1+(1−bi−di)tit_i = 1 + b_i t_{i+1} + d_i t_{i-1} + (1 - b_i - d_i) t_i, so b(ti+1−2ti+ti−1)=−1b(t_{i+1} - 2t_i + t_{i-1}) = -1 with b=bi=di=i(N−i)/N2b = b_i = d_i = i(N - i)/N^2, and t0=tN=0t_0 = t_N = 0. The solution is ti=∑jG(i,j)/bjt_i = \sum_j G(i, j)/b_j with the Green function G(i,j)=j(N−i)/NG(i, j) = j(N - i)/N for j≤ij \le i and i(N−j)/Ni(N - j)/N for j>ij > i of the second difference. Substituting bjb_j gives the formula. □\square

From one copy, t1=N(1+1/2+⋯+1/(N−1))≈Nln⁡Nt_1 = N(1 + 1/2 + \cdots + 1/(N-1)) \approx N \ln N steps, which is only ln⁡N\ln N generations: a new neutral mutant is usually lost fast. From i=N/2i = N/2, ti≈N2ln⁡2t_i \approx N^2 \ln 2 steps, or Nln⁡2N \ln 2 generations. For N=10N = 10, t1=28.29t_1 = 28.29 and t5=64.56t_5 = 64.56 steps; the value N2ln⁡2=69.3N^2 \ln 2 = 69.3 is the large NN form.

Eigenvalues, neutral case (Moran 1958). The transition matrix has the eigenvalues 1−k(k−1)/N21 - k(k-1)/N^2 for k=0,1,…,Nk = 0, 1, \ldots, N.

Proof. With bi=di=i(N−i)/N2b_i = d_i = i(N - i)/N^2, for any function ff, E[f(X′)∣X=x]=f(x)+x(N−x)N2(f(x+1)−2f(x)+f(x−1))\mathbb E[f(X') \mid X = x] = f(x) + \frac{x(N - x)}{N^2}\big(f(x+1) - 2f(x) + f(x-1)\big). For the falling factorial f(x)=x(x−1)⋯(x−k+1)f(x) = x(x-1)\cdots(x-k+1), the second difference is k(k−1)k(k-1) times the falling factorial of degree k−2k - 2 at x−1x - 1, and x(N−x)x(N - x) times that is $-(x)_k + $ terms of lower degree. So the matrix maps (x)k(x)_k to (1−k(k−1)/N2)(x)k(1 - k(k-1)/N^2)(x)_k plus lower terms: it is triangular in the basis of falling factorials, with these values on the diagonal. □\square

The value for k=2k = 2 is 1−2/N21 - 2/N^2, so the heterozygosity E[X(N−X)]\mathbb E[X(N - X)] drops by this factor per step and by about 1−2/N1 - 2/N per generation. A haploid Wright-Fisher population of NN copies loses it at 1−1/N1 - 1/N per generation; this is the factor 2 of the effective size.

With selection, times. There is no short closed form, but the times are the solution of a tridiagonal linear system, which takes O(N)O(N) operations. For N=10N = 10 and r=1.1r = 1.1, a single mutant needs 30.5830.58 steps on average until fixation or loss.

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)
moran_model.py 142 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/moran-model/. The authors are listed in prov/QM5Y7F.jsonl.
"""The Moran model of a haploid population of N individuals with two types.

X is the number of individuals of type A. In each step one individual is
chosen to reproduce, with probability proportional to fitness (r for A and
1 for a), and one individual is chosen uniformly to die; the offspring takes
its place. The same individual can be chosen for both. So X moves by +1, -1
or 0, and the chain is a birth-death chain on 0, ..., N with absorbing ends.
Time is in steps; one generation is N steps.

Exact results use the birth and death probabilities
    b_i = r i (N - i) / ((r i + N - i) N),   d_i = (N - i) i / ((r i + N - i) N).
With r a Fraction (or an int), they are exact rationals.
"""

from __future__ import annotations

from fractions import Fraction
from typing import List, Tuple

from biostoch import binomial


def rates(i: int, N: int, r=1):
    """(b_i, d_i): the probabilities that one step moves X from i to i + 1
    and to i - 1."""
    w = r * i + (N - i)
    if w == 0:
        return 0, 0
    if isinstance(r, (int, Fraction)):
        b = Fraction(r * i, 1) / w * Fraction(N - i, N)
        d = Fraction(N - i, 1) / w * Fraction(i, N)
    else:
        b = r * i / w * (N - i) / N
        d = (N - i) / w * i / N
    return b, d


def step(rng, x: int, N: int, r: float = 1.0) -> int:
    """One birth and one death. Two draws from biostoch.binomial(rng, 1, .):
    first the type of the parent, then the type of the individual that dies."""
    birth_a = binomial(rng, 1, r * x / (r * x + N - x))  # @line L3
    death_a = binomial(rng, 1, x / N)  # @line L4
    return x + birth_a - death_a  # @line L5


def simulate(rng, i0: int, N: int, steps: int, r: float = 1.0) -> List[int]:
    """The counts X_0, ..., X_steps; the run stops early at 0 or N."""
    if N < 1 or not 0 <= i0 <= N:
        raise ValueError("need N >= 1 and 0 <= i0 <= N")
    x = i0  # @line L1
    xs = [x]
    for _ in range(steps):  # @line L2
        if x == 0 or x == N:
            break
        x = step(rng, x, N, r)
        xs.append(x)
    return xs  # @line L6


def run_to_absorption(rng, i0: int, N: int, r: float = 1.0) -> Tuple[bool, int]:
    """Run until one type is lost. Returns (A fixed, number of steps)."""
    x, t = i0, 0
    while 0 < x < N:
        x = step(rng, x, N, r)
        t += 1
    return x == N, t


def fixation_formula(i: int, N: int, r=1):
    """(1 - r^(-i)) / (1 - r^(-N)), and i / N when r = 1."""
    if r == 1:
        return Fraction(i, N) if isinstance(r, (int, Fraction)) else i / N
    return (1 - r ** (-i)) / (1 - r ** (-N))


def fixation_by_sums(i: int, N: int, r=1):
    """The birth-death formula sum_{k<i} prod_{j<=k} gamma_j / sum_{k<N} (same),
    with gamma_j = d_j / b_j, which needs no closed form."""
    terms = []
    prod = 1
    for k in range(N):
        terms.append(prod)
        if k + 1 < N:
            b, d = rates(k + 1, N, r)
            prod = prod * (d / b)
    return sum(terms[:i]) / sum(terms)


def absorption_times(N: int, r=1) -> Tuple[list, list]:
    """The first two moments of the number of steps to absorption from each
    start 0, ..., N, by solving the tridiagonal systems
        t_i = 1 + b_i t_(i+1) + d_i t_(i-1) + (1 - b_i - d_i) t_i,
    and the same with right side 1 + 2 (b_i t_(i+1) + d_i t_(i-1) + (1 - b_i - d_i) t_i)
    for the second moment, by the Thomas algorithm."""
    exact = isinstance(r, (int, Fraction))
    zero, one = (Fraction(0), Fraction(1)) if exact else (0.0, 1.0)
    n = N - 1
    if n <= 0:
        return [zero] * (N + 1), [zero] * (N + 1)
    lo, di, up = [], [], []
    for i in range(1, N):
        b, d = rates(i, N, r)
        lo.append(-d)
        di.append(b + d)
        up.append(-b)

    def solve(rhs):
        c = [zero] * n
        g = [zero] * n
        c[0] = up[0] / di[0]
        g[0] = rhs[0] / di[0]
        for k in range(1, n):
            den = di[k] - lo[k] * c[k - 1]
            c[k] = up[k] / den
            g[k] = (rhs[k] - lo[k] * g[k - 1]) / den
        x = [zero] * n
        x[-1] = g[-1]
        for k in range(n - 2, -1, -1):
            x[k] = g[k] - c[k] * x[k + 1]
        return x

    t = [zero] + solve([one] * n) + [zero]
    rhs2 = []
    for i in range(1, N):
        b, d = rates(i, N, r)
        rhs2.append(one + 2 * (b * t[i + 1] + d * t[i - 1] + (1 - b - d) * t[i]))
    m2 = [zero] + solve(rhs2) + [zero]
    return t, m2


def transition_matrix(N: int, r=1) -> List[list]:
    P = [[0] * (N + 1) for _ in range(N + 1)]
    for i in range(N + 1):
        b, d = rates(i, N, r)
        if i < N:
            P[i][i + 1] = b
        if i > 0:
            P[i][i - 1] = d
        P[i][i] = 1 - b - d
    return P
test_moran_model.py 98 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/moran-model/. The authors are listed in prov/QM5Y7F.jsonl.

import math
import random
from fractions import Fraction

from biostoch import chi2_sf
from moran_model import (
    absorption_times,
    fixation_by_sums,
    fixation_formula,
    rates,
    run_to_absorption,
    simulate,
    step,
    transition_matrix,
)


def test_one_step_law():
    rng = random.Random(1958)
    x, N, r, reps = 4, 10, 1.5, 4000
    b, d = rates(x, N, r)
    probs = {x + 1: b, x - 1: d, x: 1 - b - d}
    counts = {k: 0 for k in probs}
    for _ in range(reps):
        counts[step(rng, x, N, r)] += 1
    stat = sum((counts[k] - reps * p) ** 2 / (reps * p) for k, p in probs.items())
    assert chi2_sf(stat, 2) > 0.001


def test_fixation_formula_matches_birth_death_sums():
    for N in (2, 5, 10, 15):
        for r in (Fraction(1), Fraction(11, 10), Fraction(1, 2), Fraction(3)):
            for i in range(N + 1):
                assert fixation_formula(i, N, r) == fixation_by_sums(i, N, r)
    assert fixation_formula(3, 10, 1) == Fraction(3, 10)
    assert abs(float(fixation_formula(1, 10, Fraction(11, 10))) - 0.147950) < 5e-7


def test_neutral_absorption_time_closed_form():
    # t_i = N ((N - i) sum_{j=1}^{i} 1/(N - j) + i sum_{j=i+1}^{N-1} 1/j) steps.
    for N in (2, 6, 10):
        t, _ = absorption_times(N)
        for i in range(1, N):
            closed = N * ((N - i) * sum(Fraction(1, N - j) for j in range(1, i + 1))
                          + i * sum(Fraction(1, j) for j in range(i + 1, N)))
            assert t[i] == closed
    t, _ = absorption_times(10)
    assert t[1] == 10 * sum(Fraction(1, j) for j in range(1, 10))


def test_martingale_and_heterozygosity_decay():
    # Neutral: E[X'] = X and E[X'(N - X')] = X (N - X) (1 - 2/N^2) per step.
    N, steps = 8, 5
    P = transition_matrix(N)
    for i in range(N + 1):
        d = [Fraction(int(k == i)) for k in range(N + 1)]
        for _ in range(steps):
            d = [sum(d[a] * P[a][b] for a in range(N + 1)) for b in range(N + 1)]
        assert sum(k * dk for k, dk in enumerate(d)) == i
        het = sum(k * (N - k) * dk for k, dk in enumerate(d))
        assert het == i * (N - i) * (1 - Fraction(2, N * N)) ** steps


def test_simulated_fixation():
    rng = random.Random(10)
    N, r, reps = 10, 1.1, 8000
    u = float(fixation_formula(1, N, Fraction(11, 10)))
    fixed = sum(run_to_absorption(rng, 1, N, r)[0] for _ in range(reps))
    z = 4
    assert abs(fixed / reps - u) <= z * math.sqrt(u * (1 - u) / reps)


def test_simulated_absorption_time():
    rng = random.Random(64)
    N, i0, reps = 10, 5, 3000
    t, m2 = absorption_times(N)
    mu = float(t[i0])
    var = float(m2[i0] - t[i0] ** 2)
    total = sum(run_to_absorption(rng, i0, N)[1] for _ in range(reps))
    z = 4
    assert abs(total / reps - mu) <= z * math.sqrt(var / reps)


def test_edges():
    rng = random.Random(1)
    assert simulate(rng, 0, 5, 10) == [0]
    assert simulate(rng, 5, 5, 10) == [5]
    assert fixation_by_sums(1, 1, Fraction(2)) == 1
    assert rates(0, 5, 2) == (0, 0)
    try:
        simulate(rng, 6, 5, 1)
    except ValueError:
        pass
    else:
        raise AssertionError("expected ValueError")

References

  1. Moran 1958, pp. 60-71 (the model with one birth and one death per step, and the rate at which variation is lost)
  2. Warren J. Ewens, Mathematical Population Genetics I, Theoretical Introduction, 2nd edition, Springer, 2004, Section 3.4 (Moran models, p. 104), Section 3.6.4 (the Moran model with infinitely many alleles, p. 117) and Section 10.6 (exact results for the Moran model, p. 338)
  3. Rasmus Nielsen and Montgomery Slatkin, An Introduction to Population Genetics, Theory and Applications, Sinauer, 2013, Chapter 2 (genetic drift) and Chapter 8 (selection in a finite population)

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/QM5Y7F/text.yaml