Algorithm Search⌘K

Modelcore

Infinite alleles model

Also called Kimura-Crow model.

A mutation model in which every mutation creates an allele never seen before, so alleles are labels and only their counts matter.

The infinite alleles model is a model of mutation in which each mutation makes an allele that is new to the population. So two gene copies carry the same allele only if no mutation has happened on either line since their common ancestor, and an allele is only a label. Kimura and Crow used it on a Wright-Fisher population to find how much variation genetic drift and mutation keep in balance. It is the model behind the Ewens sampling formula.

The machine

The state. A population of 2N2N gene copies (for example NN diploids) in discrete generations. Each copy carries an allele label. The state is the partition of the 2N2N copies into allele classes; the names of the labels do not matter.

The step. Each copy of the next generation picks a parent copy uniformly and independently, as in the Wright-Fisher model. Then it mutates with probability uu, independently of the others. A copy that mutates gets a label that no copy has had before. A copy that does not mutate keeps the label of its parent. The scaled mutation rate is

θ=4Nu,\theta = 4Nu,

twice the expected number of new mutations per generation.

A simulation.

  1. INFINITE-ALLELES(2N, u, T)
  2. 1labels ← 2N copies of allele 0; fresh ← 1
  3. 2for t ← 1 to T do
  4. 3for each new copy, pick a parent copy uniformly among the 2N copies
  5. 4with probability u give it the label fresh and add 1 to fresh, else copy the label of its parent
  6. 5replace the population by the new copies
  7. 6return the allele classes of the labels

Each generation costs O(N)O(N) random draws, so TT generations take O(NT)O(NT) time. The implementation also has the exact homozygosity recursion and the Hoppe urn, which draws a sample from the stationary distribution directly.

A trace. With seed 7, 2N=202N = 20 and u=0.05u = 0.05 (θ=2\theta = 2), the sizes of the allele classes are (19,1)(19, 1) after 1 and 5 generations, (13,4,2,1)(13, 4, 2, 1) after 10, (11,5,1,1,1,1)(11, 5, 1, 1, 1, 1) after 20 and (8,5,3,2,1,1)(8, 5, 3, 2, 1, 1) after 40. The original allele is still the most common one, but it has lost more than half its copies.

What it counts

  • The number of distinct alleles in the population or in a sample of nn copies.
  • The allele counts: how many alleles have exactly jj copies, for each jj.
  • The homozygosity FF: the probability that two distinct copies carry the same allele. Its inverse 1/F1/F is the effective number of alleles.
  • Identity by descent: two copies have the same allele exactly when no mutation has happened on their two lines back to their common ancestor.

Relation to other models

  • Wright-Fisher model and Moran model. The infinite alleles model is a mutation rule on top of a model of reproduction. On the Moran model many results are exact (Ewens 2004, Section 3.6.4); on the Wright-Fisher model they hold to first order in uu and 1/N1/N.
  • KK-allele models. With KK alleles and mutation to each of the others at equal rates, a mutation can make an allele that already exists. As K→∞K \to \infty, this model tends to the infinite alleles model.
  • Infinite sites model. Each mutation hits a new site of a long DNA sequence. If the sequence is the allele, the infinite sites model gives an infinite alleles model, but it also keeps the information of which mutations two alleles share.
  • Kingman coalescent. Run back in time, the genealogy of a sample is the coalescent. Mutations fall on its branches at rate θ/2\theta/2 per lineage, and each mutation cuts the lineages below it off as a new allele. This gives the Ewens sampling formula.
  • The Chinese restaurant process and the Dirichlet process. The Hoppe urn that draws a sample under this model is the Chinese restaurant process with parameter θ\theta, and the allele frequencies in a large population follow the Poisson-Dirichlet law. For θ=1\theta = 1, the allele counts of a sample of nn have the law of the cycle lengths of a uniform random permutation.

Known results in the model

The homozygosity recursion. Let FtF_t be the probability that two distinct copies of generation tt carry the same allele. Then

Ft+1=(1−u)2(12N+(1−12N)Ft).F_{t+1} = (1 - u)^2\Big(\frac{1}{2N} + \Big(1 - \frac{1}{2N}\Big)F_t\Big).

Proof. Two distinct copies of generation t+1t + 1 have the same parent copy with probability 1/(2N)1/(2N), and two distinct parent copies otherwise, which carry the same allele with probability FtF_t. They carry the same allele after the step exactly when this holds and neither copy mutates, which has probability (1−u)2(1 - u)^2; a mutation always gives a new label. □\square

The equilibrium homozygosity. The recursion is linear with the factor (1−u)2(1−1/(2N))<1(1 - u)^2(1 - 1/(2N)) < 1, so FtF_t tends to its unique fixed point

F∗=(1−u)22N−(2N−1)(1−u)2≈11+4Nu=11+θ.F^* = \frac{(1 - u)^2}{2N - (2N - 1)(1 - u)^2} \approx \frac{1}{1 + 4Nu} = \frac{1}{1 + \theta}.

The approximation drops terms of order u2u^2 and u/Nu/N. It is good when uu is small: for N=50N = 50 and u=0.001u = 0.001 (θ=0.2\theta = 0.2), F∗=0.833125F^* = 0.833125 against 1/(1+θ)=0.8333331/(1 + \theta) = 0.833333. It is poor when uu is not small: for 2N=202N = 20 and u=0.05u = 0.05 (θ=2\theta = 2), F∗=0.316389F^* = 0.316389 against 0.3333330.333333, 5 percent off. The approach to F∗F^* is geometric with rate about 2u+1/(2N)2u + 1/(2N) per generation. The implementation checks the recursion against 10000 simulated populations.

The same value comes from the genealogy: going back, the two lines merge at rate 1/(2N)1/(2N) and one of them mutates at rate 2u2u per generation, so the chance that they merge first is about (1/(2N))/(1/(2N)+2u)=1/(1+θ)(1/(2N))/(1/(2N) + 2u) = 1/(1 + \theta).

The effective number of alleles (Kimura and Crow 1964). The number ne=1/F∗≈1+4Nun_e = 1/F^* \approx 1 + 4Nu is the number of equally common alleles that would give the same homozygosity. The true number of alleles present is larger, because most of them are rare. For θ=2\theta = 2 there are about 3 alleles in this sense, while the trace above has 6 after 40 generations.

Samples. In the limit of large NN with θ\theta fixed, the allele counts of a sample of nn copies have the Ewens sampling formula as their law. A sample can be drawn with the Hoppe urn: copy k+1k + 1 is a new allele with probability θ/(θ+k)\theta/(\theta + k), and otherwise a copy of one of the first kk copies, chosen uniformly. The number of alleles KnK_n in the sample has

E[Kn]=∑i=0n−1θθ+i≈θln⁡n.\mathbb E[K_n] = \sum_{i=0}^{n-1} \frac{\theta}{\theta + i} \approx \theta \ln n.

With θ=1\theta = 1 this is 4.504.50 for n=50n = 50 and 5.195.19 for n=100n = 100: doubling the sample adds less than one allele on average. The implementation compares the Hoppe urn with the exact formula by a chi-squared test.

Without mutation. With u=0u = 0 the recursion gives 1−Ft=(1−1/(2N))t(1−F0)1 - F_t = (1 - 1/(2N))^t(1 - F_0): drift alone removes all variation, and one allele fixes.

A test of neutrality. Given the number of alleles in a sample, the law of the allele counts does not depend on θ\theta. Watterson (1977) used this to test neutrality: a sample with too even counts suggests balancing selection, and one with too many rare alleles suggests a recent expansion or weak purifying selection.

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)
infinite_alleles_model.py 143 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/infinite-alleles-model/. The authors are listed in prov/AWDSAS.jsonl.
"""The infinite alleles model on a Wright-Fisher population, with its exact
homozygosity recursion and the Hoppe urn for samples.

The population has 2N gene copies in discrete generations. Each copy of the
next generation copies a parent copy chosen uniformly, and then, with
probability u, mutates to an allele that has never been seen before. Alleles
are labels: only the partition of the copies into allele classes matters.

theta = 4 N u is the scaled mutation rate. Functions that take two_n use the
number of copies 2N.
"""

from __future__ import annotations

from fractions import Fraction
from typing import Dict, Iterator, List, Sequence, Tuple


def simulate(rng, two_n: int, u: float, generations: int,
             start: Sequence[int] | None = None) -> List[int]:
    """The allele labels of the 2N copies after the given number of
    generations. The start is all copies of allele 0 unless given."""
    if two_n < 1 or not 0.0 <= u <= 1.0 or generations < 0:
        raise ValueError("need two_n >= 1, 0 <= u <= 1, generations >= 0")
    pop = list(start) if start is not None else [0] * two_n  # @line L1
    if len(pop) != two_n:
        raise ValueError("start must have two_n labels")
    fresh = max(pop) + 1
    for _ in range(generations):  # @line L2
        nxt = []
        for _ in range(two_n):
            parent = pop[rng.randrange(two_n)]  # @line L3
            if rng.random() < u:  # @line L4
                nxt.append(fresh)  # @line L4
                fresh += 1
            else:
                nxt.append(parent)  # @line L4
        pop = nxt  # @line L5
    return pop  # @line L6


def allele_counts(labels: Sequence[int]) -> List[int]:
    """The sizes of the allele classes, largest first."""
    counts: Dict[int, int] = {}
    for x in labels:
        counts[x] = counts.get(x, 0) + 1
    return sorted(counts.values(), reverse=True)


def homozygosity(labels: Sequence[int]) -> float:
    """The share of pairs of distinct copies that carry the same allele."""
    n = len(labels)
    if n < 2:
        raise ValueError("need at least two copies")
    return sum(c * (c - 1) for c in allele_counts(labels)) / (n * (n - 1))


def homozygosity_step(F, two_n: int, u):
    """F' = (1 - u)^2 (1/(2N) + (1 - 1/(2N)) F): two copies of the next
    generation are identical if neither mutates and their parents are the
    same copy or identical distinct copies."""
    return (1 - u) ** 2 * (Fraction(1, two_n) + (1 - Fraction(1, two_n)) * F)


def homozygosity_after(two_n: int, u, generations: int, F0=Fraction(1)):
    """The expected homozygosity after the given number of generations."""
    F = F0
    for _ in range(generations):
        F = homozygosity_step(F, two_n, u)
    return F


def homozygosity_equilibrium(two_n: int, u):
    """The fixed point F* = (1 - u)^2 / (2N - (2N - 1)(1 - u)^2), which is
    about 1 / (1 + theta) with theta = 4 N u = 2 two_n u."""
    r = (1 - u) ** 2
    return r / (two_n - (two_n - 1) * r)


def hoppe_urn(rng, n: int, theta: float) -> List[int]:
    """Allele labels of a sample of n genes drawn by the Hoppe urn: gene k + 1
    is a new allele with probability theta / (theta + k), else a copy of one
    of the k earlier genes chosen uniformly."""
    if n < 1 or theta <= 0:
        raise ValueError("need n >= 1 and theta > 0")
    labels: List[int] = []
    fresh = 0
    for k in range(n):
        if rng.random() * (theta + k) < theta:
            labels.append(fresh)
            fresh += 1
        else:
            labels.append(labels[rng.randrange(k)])
    return labels


def allele_profile(counts: Sequence[int], n: int) -> Tuple[int, ...]:
    """(a_1, ..., a_n): a_j is the number of alleles with exactly j copies."""
    a = [0] * n
    for c in counts:
        a[c - 1] += 1
    return tuple(a)


def rising(theta, n: int):
    """theta (theta + 1) ... (theta + n - 1)."""
    out = theta ** 0
    for i in range(n):
        out *= theta + i
    return out


def ewens_probability(a: Sequence[int], theta) -> Fraction:
    """The Ewens sampling formula n! / theta^(n rising) prod (theta/j)^a_j / a_j!.
    Exact for Fraction or integer theta."""
    n = sum((j + 1) * x for j, x in enumerate(a))
    p = Fraction(1)
    for i in range(1, n + 1):
        p *= i
    p /= rising(Fraction(theta), n)
    for j, x in enumerate(a, start=1):
        for k in range(1, x + 1):
            p *= Fraction(theta) / j / k
    return p


def partitions(n: int, largest: int | None = None) -> Iterator[List[int]]:
    """The partitions of n as lists of parts, largest first."""
    if largest is None:
        largest = n
    if n == 0:
        yield []
        return
    for first in range(min(n, largest), 0, -1):
        for rest in partitions(n - first, first):
            yield [first] + rest


def expected_alleles(n: int, theta):
    """E[K] = sum over i = 0..n-1 of theta / (theta + i) in a sample of n."""
    return sum(Fraction(theta) / (Fraction(theta) + i) for i in range(n))
test_infinite_alleles_model.py 111 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/infinite-alleles-model/. The authors are listed in prov/AWDSAS.jsonl.

import random
from fractions import Fraction

from biostoch import check_mean, chi2_sf, mean_var
from infinite_alleles_model import (
    allele_counts,
    allele_profile,
    ewens_probability,
    expected_alleles,
    homozygosity,
    homozygosity_after,
    homozygosity_equilibrium,
    homozygosity_step,
    hoppe_urn,
    partitions,
    simulate,
)


def test_equilibrium_is_fixed_point():
    for two_n, u in ((20, Fraction(1, 20)), (100, Fraction(1, 1000)), (7, Fraction(1, 3))):
        F = homozygosity_equilibrium(two_n, u)
        assert homozygosity_step(F, two_n, u) == F
    # N = 50, u = 0.001, theta = 0.2: F* = 0.833125 against 1 / (1 + theta) = 0.833333.
    F = homozygosity_equilibrium(100, Fraction(1, 1000))
    assert abs(float(F) - 0.833125) < 5e-7
    assert abs(float(F) - 1 / 1.2) < 3e-4


def test_recursion_converges():
    two_n, u = 20, Fraction(1, 20)
    F = homozygosity_after(two_n, u, 200)
    assert abs(float(F - homozygosity_equilibrium(two_n, u))) < 1e-12
    # Without mutation the homozygosity only rises: 1 - F_t = (1 - 1/(2N))^t (1 - F_0).
    assert homozygosity_after(10, 0, 3, Fraction(0)) == 1 - Fraction(9, 10) ** 3


def test_simulated_homozygosity_matches_recursion():
    rng = random.Random(1964)
    two_n, u, gens, reps = 20, 0.05, 60, 10000
    values = [homozygosity(simulate(rng, two_n, u, gens)) for _ in range(reps)]
    m, v = mean_var(values)
    mu = float(homozygosity_after(two_n, Fraction(1, 20), gens))
    assert check_mean(m, mu, v, reps)
    assert abs(mu - float(homozygosity_equilibrium(two_n, Fraction(1, 20)))) < 1e-4


def test_no_mutation_keeps_labels():
    rng = random.Random(3)
    pop = simulate(rng, 12, 0.0, 30, start=list(range(12)))
    assert set(pop) <= set(range(12))
    assert sum(allele_counts(pop)) == 12


def test_ewens_formula_values():
    # n = 3, theta = 2: (3,0,0), (1,1,0), (0,0,1) have 1/3, 1/2, 1/6.
    assert ewens_probability((3, 0, 0), 2) == Fraction(1, 3)
    assert ewens_probability((1, 1, 0), 2) == Fraction(1, 2)
    assert ewens_probability((0, 0, 1), 2) == Fraction(1, 6)
    # theta = 1 gives the cycle types of a uniform random permutation.
    assert ewens_probability((0, 2, 0, 0), 1) == Fraction(1, 8)
    for n, theta in ((6, Fraction(3, 2)), (8, 1), (5, Fraction(1, 7))):
        total = sum(ewens_probability(allele_profile(p, n), theta) for p in partitions(n))
        assert total == 1


def test_hoppe_urn_matches_ewens():
    rng = random.Random(1972)
    n, theta, reps = 4, 1.0, 100000
    counts = {}
    for _ in range(reps):
        a = allele_profile(allele_counts(hoppe_urn(rng, n, theta)), n)
        counts[a] = counts.get(a, 0) + 1
    stat = 0.0
    parts = list(partitions(n))
    for p in parts:
        a = allele_profile(p, n)
        e = reps * float(ewens_probability(a, 1))
        stat += (counts.get(a, 0) - e) ** 2 / e
    assert sum(counts.values()) == reps and len(counts) <= len(parts)
    assert chi2_sf(stat, len(parts) - 1) > 0.001


def test_expected_number_of_alleles():
    assert expected_alleles(3, 1) == Fraction(11, 6)
    assert abs(float(expected_alleles(10, 2)) - 4.03975) < 5e-6
    rng = random.Random(5)
    n, theta, reps = 10, 2.0, 40000
    ks = [len(set(hoppe_urn(rng, n, theta))) for _ in range(reps)]
    m, _ = mean_var(ks)
    var = sum(theta * i / (theta + i) ** 2 for i in range(n))
    assert check_mean(m, float(expected_alleles(n, 2)), var, reps)


def test_invalid():
    for bad in ((0, 0.1, 1), (10, 1.5, 1), (10, 0.1, -1)):
        try:
            simulate(random.Random(0), *bad)
        except ValueError:
            pass
        else:
            raise AssertionError("expected ValueError")
    try:
        hoppe_urn(random.Random(0), 5, 0.0)
    except ValueError:
        pass
    else:
        raise AssertionError("expected ValueError")

References

  1. Kimura and Crow 1964, pp. 725-738 (the model, the equilibrium homozygosity and the effective number of alleles 4Nu + 1)
  2. Ewens 1972, the distribution of the allele counts in a sample under this model
  3. Warren J. Ewens, Mathematical Population Genetics I, Theoretical Introduction, 2nd edition, Springer, 2004, Section 3.6 (infinitely many alleles models, p. 111) and Section 3.6.4 (the Moran model with infinitely many alleles, p. 117)

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