Algorithm Search⌘K

Algorithmcore

Tajima's D

Also called Tajima's D test.

A neutrality test from the scaled difference between nucleotide diversity and Watterson's estimate. Selection or growth shifts its sign.

Time
Θ(n m) worst · average · best
Space
Θ(1) extra
Where
m = the number of aligned sites; n = the number of sequences
Properties
deterministicexactonlineiterative
Origin
Fumio Tajima, 1989

Tajima's D tests whether a sample of DNA sequences fits the neutral model of a population of constant size. It compares two estimators of θ=4Nμ\theta = 4N\mu that have the same mean under that model: the mean pairwise difference π^\hat\pi, and Watterson's estimator S/anS / a_n from the number of segregating sites SS. Their difference, divided by an estimate of its standard deviation, is DD. A value far below 0 means an excess of rare variants, which a recent selective sweep or population growth can cause; a value far above 0 means an excess of intermediate-frequency variants, which balancing selection, structure or a decline can cause. Like every test of this kind, it rejects the null model, not a specific cause.

In plain words

Two numbers measure how much variation a sample has. One counts the places where the sequences are not all the same. The other takes two sequences at a time and counts how many places they differ, then averages over all pairs. A rare variant, carried by one sequence, counts fully in the first number but adds little to the second, because few pairs differ at it. A variant that splits the sample in half counts once in the first number and in many pairs in the second.

In a neutral population of steady size, the two numbers agree on average after a known correction. Tajima's D is their difference, put on a scale where about 0 is normal and values beyond about 2 in size are rare. The sign says which kind of variant is in excess.

The problem

Input. A sample of n≥4n \ge 4 aligned sequences of mm sites each, without missing data.

Output. The statistic

D=π^−S/a1e1S+e2S(S−1),D = \frac{\hat\pi - S / a_1}{\sqrt{e_1 S + e_2 S (S - 1)}},

where SS is the number of segregating sites, π^\hat\pi is the mean number of pairwise differences, and a1a_1, e1e_1, e2e_2 depend only on nn:

a1=∑i=1n−11i,a2=∑i=1n−11i2,b1=n+13(n−1),b2=2(n2+n+3)9n(n−1),a_1 = \sum_{i=1}^{n-1} \frac{1}{i}, \qquad a_2 = \sum_{i=1}^{n-1} \frac{1}{i^2}, \qquad b_1 = \frac{n + 1}{3(n - 1)}, \qquad b_2 = \frac{2(n^2 + n + 3)}{9 n (n - 1)},
c1=b1−1a1,c2=b2−n+2a1n+a2a12,e1=c1a1,e2=c2a12+a2.c_1 = b_1 - \frac{1}{a_1}, \qquad c_2 = b_2 - \frac{n + 2}{a_1 n} + \frac{a_2}{a_1^2}, \qquad e_1 = \frac{c_1}{a_1}, \qquad e_2 = \frac{c_2}{a_1^2 + a_2}.

DD is not defined when S=0S = 0. For n=3n = 3 every segregating site splits the sample 1 to 2 or 2 to 1, so π^=S/a1\hat\pi = S / a_1 always and c1=c2=0c_1 = c_2 = 0; the test needs n≥4n \ge 4.

The null model. Neutral mutations under the infinite sites model, a constant population size, random mating, no structure, and no recombination inside the region (the variance formula assumes one tree).

The algorithm

  1. TAJIMA-D(H)
  2. 1S ← 0; P ← 0
  3. 2for each site j = 1, ..., m do
  4. 3if column j is not all equal then S ← S + 1
  5. 4P ← P + the number of pairs of sequences that differ at site j
  6. 5π ← P / (n(n − 1)/2)
  7. 6compute a_1, e_1 and e_2 from n
  8. 7if S = 0 then return undefined
  9. 8return (π − S / a_1) / sqrt(e_1 S + e_2 S (S − 1))

Line L4 does not look at pairs. If the alleles of column jj occur c1,…,crc_1, \ldots, c_r times, with ∑c=n\sum c = n, the number of differing pairs is (n2−∑ici2)/2(n^2 - \sum_i c_i^2)/2; for two alleles this is c(n−c)c(n - c). So one pass over the alignment gives both SS and π^\hat\pi.

Tajima suggested comparing DD with a beta distribution on the interval [Dmin⁡,Dmax⁡][D_{\min}, D_{\max}] of possible values, with mean 0 and variance 1. Many programs use the standard normal instead, and others get the null distribution by coalescent simulation. The implementation returns DD and the limits of Dmin⁡D_{\min} and Dmax⁡D_{\max}, and leaves the choice of null distribution to the caller.

Example

The sample of the infinite sites model page has n=5n = 5:

copy s1 s2 s3 s4 s5 s6
1 1 0 0 0 0 1
2 1 0 0 0 0 0
3 0 1 0 1 0 0
4 0 0 1 1 0 0
5 0 0 1 1 1 0

The derived counts are (2,1,2,3,1,1)(2, 1, 2, 3, 1, 1), so S=6S = 6, and line L4 adds c(5−c)=6,4,6,6,4,4c(5 - c) = 6, 4, 6, 6, 4, 4, a total of P=30P = 30. Line L5 gives π^=30/10=3\hat\pi = 30/10 = 3.

For n=5n = 5 the constants are a1=25/12=2.083333a_1 = 25/12 = 2.083333, a2=1.423611a_2 = 1.423611, b1=0.5b_1 = 0.5, b2=0.366667b_2 = 0.366667, c1=0.02c_1 = 0.02, c2=0.022667c_2 = 0.022667, e1=0.0096e_1 = 0.0096 and e2=0.0039325e_2 = 0.0039325. The numerator is 3−2.88=0.123 - 2.88 = 0.12. The denominator is 0.0096⋅6+0.0039325⋅30=0.175576=0.419018\sqrt{0.0096 \cdot 6 + 0.0039325 \cdot 30} = \sqrt{0.175576} = 0.419018. So D=0.2864D = 0.2864, well inside the range of the null model: the sample has slightly more intermediate variants than expected, and six sites are far too few to say more.

A second case: n=10n = 10, S=10S = 10 and π^=3\hat\pi = 3, where S/a1=3.5349S / a_1 = 3.5349. With e1=0.0190605e_1 = 0.0190605 and e2=0.00494893e_2 = 0.00494893, D=−0.5349/0.190605+0.445404=−0.6707D = -0.5349 / \sqrt{0.190605 + 0.445404} = -0.6707.

Correctness

Lines L2 to L4 add, for each site, one to SS if it segregates and the number of differing pairs to PP. A pair of sequences differs at djkd_{jk} sites, so P=∑j<kdjkP = \sum_{j < k} d_{jk}, and line L5 gives the mean pairwise difference. Line L8 is the formula.

The test is valid because of three facts under the null model. First, E[π^]=θE[\hat\pi] = \theta (Tajima 1983) and E[S/a1]=θE[S / a_1] = \theta (Watterson 1975), so the numerator d=π^−S/a1d = \hat\pi - S / a_1 has mean 0. Second, Var⁡[d]=c1θ+c2θ2\operatorname{Var}[d] = c_1 \theta + c_2 \theta^2. This comes from Var⁡[π^]=b1θ+b2θ2\operatorname{Var}[\hat\pi] = b_1 \theta + b_2 \theta^2, Var⁡[S]=a1θ+a2θ2\operatorname{Var}[S] = a_1 \theta + a_2 \theta^2, and the covariance of π^\hat\pi and SS. Third, since E[S]=a1θE[S] = a_1 \theta and E[S(S−1)]=(a12+a2)θ2E[S(S - 1)] = (a_1^2 + a_2)\theta^2, the square of the denominator, e1S+e2S(S−1)e_1 S + e_2 S(S - 1), has mean exactly c1θ+c2θ2c_1 \theta + c_2 \theta^2. So DD is dd divided by an unbiased estimate of its variance, under the root. The proofs of the first and third facts are below; the second is Tajima's computation, which the tests check by simulation.

DD itself has mean close to 0 and variance close to 1, but not exactly, because the denominator is random and depends on SS.

Proof: TAJIMA-D computes D, and its numerator and squared denominator have the right meansfull

Setting. HH is an alignment of n≥4n \ge 4 sequences and mm sites without missing data. For sequences j<kj < k, djkd_{jk} is the number of sites where they differ, and π^=(n2)−1∑j<kdjk\hat\pi = \binom{n}{2}^{-1} \sum_{j<k} d_{jk}. SS is the number of segregating sites. The constants a1,a2,c1,c2,e1,e2a_1, a_2, c_1, c_2, e_1, e_2 are those of the page.

Lemma 1. At a site whose alleles occur c1,…,crc_1, \ldots, c_r times, with ∑ici=n\sum_i c_i = n, the number of pairs of sequences with different alleles is (n2−∑ici2)/2(n^2 - \sum_i c_i^2)/2.

Proof. Count ordered pairs (j,k)(j, k) with j≠kj \ne k. There are n2−nn^2 - n of them, and ∑i(ci2−ci)=∑ici2−n\sum_i (c_i^2 - c_i) = \sum_i c_i^2 - n have the same allele. So n2−∑ici2n^2 - \sum_i c_i^2 ordered pairs have different alleles, and each unordered pair is counted twice. □\square

Lemma 2. After line L5, SS is the number of segregating sites and π=π^\pi = \hat\pi.

Proof. Line L3 adds one exactly for the sites that are not constant. By Lemma 1, line L4 adds to PP the number of pairs that differ at site jj. Summed over the sites, P=∑j#{{a,b}:a≠b differ at j}=∑a<bdabP = \sum_j \#\{\{a, b\} : a \ne b \text{ differ at } j\} = \sum_{a < b} d_{ab}, since both sides count the pairs (site, pair of sequences) with a difference. Line L5 divides by the number of pairs. □\square

By Lemma 2, line L8 returns the value DD of the definition when S>0S > 0, and line L7 returns undefined when S=0S = 0, where the denominator is 0.

For the rest, the sample comes from the null model: a Kingman coalescent tree with time in units of 2N2N generations, and given the tree, mutations as a Poisson process of rate θ/2\theta/2 on the branches, each at a new site.

Lemma 3. E[π^]=θE[\hat\pi] = \theta.

Proof. For two sequences jj and kk, the lineages of the pair alone form a Kingman coalescent of two: they merge after a time TT that is exponential with rate 1, so E[T]=1E[T] = 1. The path between jj and kk in the tree has length 2T2T. Each mutation on that path, and no other, separates them, and under the infinite sites model each mutation is at its own site. So djkd_{jk} is Poisson with mean θT\theta T given TT, and E[djk]=θE[d_{jk}] = \theta. The mean over the pairs has the same expectation. □\square

Lemma 4. E[S]=a1θE[S] = a_1 \theta and E[S(S−1)]=(a12+a2)θ2E[S(S - 1)] = (a_1^2 + a_2) \theta^2.

Proof. Given the total branch length LL, SS is Poisson with mean θL/2\theta L / 2, and L=∑k=2nkTkL = \sum_{k=2}^{n} k T_k with independent TkT_k exponential of rate (k2)\binom{k}{2}. So E[L]=∑k2/(k−1)=2a1E[L] = \sum_k 2/(k-1) = 2 a_1 and Var⁡[L]=∑k4/(k−1)2=4a2\operatorname{Var}[L] = \sum_k 4/(k-1)^2 = 4 a_2. For a Poisson variable with mean λ\lambda, E[S(S−1)∣λ]=λ2E[S(S - 1) \mid \lambda] = \lambda^2. Hence E[S]=θa1E[S] = \theta a_1 and E[S(S−1)]=E[(θL/2)2]=(θ2/4)(Var⁡[L]+E[L]2)=θ2(a2+a12)E[S(S - 1)] = E[(\theta L/2)^2] = (\theta^2/4)(\operatorname{Var}[L] + E[L]^2) = \theta^2 (a_2 + a_1^2). □\square

Theorem. Under the null model, the numerator d=π^−S/a1d = \hat\pi - S / a_1 has E[d]=0E[d] = 0, and the squared denominator has

E[e1S+e2S(S−1)]=c1θ+c2θ2.E[e_1 S + e_2 S(S - 1)] = c_1 \theta + c_2 \theta^2.

Proof. By Lemmas 3 and 4, E[d]=θ−a1θ/a1=0E[d] = \theta - a_1 \theta / a_1 = 0. By Lemma 4 and the definitions e1=c1/a1e_1 = c_1 / a_1 and e2=c2/(a12+a2)e_2 = c_2 / (a_1^2 + a_2),

E[e1S+e2S(S−1)]=c1a1a1θ+c2a12+a2(a12+a2)θ2=c1θ+c2θ2.■E[e_1 S + e_2 S(S - 1)] = \frac{c_1}{a_1} a_1 \theta + \frac{c_2}{a_1^2 + a_2} (a_1^2 + a_2) \theta^2 = c_1 \theta + c_2 \theta^2. \qquad \blacksquare

Remarks. Tajima (1989) showed that Var⁡[d]=c1θ+c2θ2\operatorname{Var}[d] = c_1 \theta + c_2 \theta^2 under the null model without recombination, from Var⁡[π^]=b1θ+b2θ2\operatorname{Var}[\hat\pi] = b_1 \theta + b_2 \theta^2 (Tajima 1983), Var⁡[S]=a1θ+a2θ2\operatorname{Var}[S] = a_1 \theta + a_2 \theta^2 and the covariance of π^\hat\pi and SS. Together with the theorem, the squared denominator is an unbiased estimate of Var⁡[d]\operatorname{Var}[d]. That variance is cited here and not proved. The tests check it, the variance of π^\hat\pi and the theorem on 15000 samples simulated with n=10n = 10 and θ=5\theta = 5, where Var⁡[d]=1.4503\operatorname{Var}[d] = 1.4503 and Var⁡[π^]=9.0123\operatorname{Var}[\hat\pi] = 9.0123. Lemmas 3 and 4 hold with recombination too, since they use only the tree of one site or one pair at a time; the variance does not.

Complexity

  • Time. Lines L3 and L4 read every character once and count the alleles of a column, so the time is Θ(nm)\Theta(n m) in every case. Line L6 takes O(n)O(n) time.
  • Space. A few counters and the allele counts of one column: Θ(1)\Theta(1) for a fixed alphabet.
  • From a VCF file. Only the variant sites matter, so the work is linear in the size of the genotype matrix of the variants.
  • Windows. Genome scans compute DD in sliding windows. With prefix sums of the per-site values of SS and PP, every window costs O(1)O(1) after one pass.

Properties

  • Scaled. Division by the estimated standard deviation puts DD on a common scale, so values from regions with different mutation rates can be compared roughly.
  • Bounded. For a given nn, DD is smallest when all sites are singletons (π^=2S/n\hat\pi = 2S / n) and largest when every site splits the sample as evenly as possible. As S→∞S \to \infty these bounds tend to (2/n−1/a1)/e2(2/n - 1/a_1)/\sqrt{e_2} and (hn−1/a1)/e2(h_n - 1/a_1)/\sqrt{e_2}, with hn=n/(2(n−1))h_n = n/(2(n-1)) for even nn and (n+1)/(2n)(n+1)/(2n) for odd nn. For n=5n = 5 the limits are −1.276-1.276 and 1.9141.914; for n=10n = 10, −2.182-2.182 and 2.8722.872; for n=50n = 50, −3.011-3.011 and 4.7144.714. With small samples, values beyond ±2\pm 2 cannot occur at all.
  • Not exactly normal or beta. The beta approximation and the normal approximation are both approximations; with few sites, the true null distribution is discrete and skewed.
  • No outgroup needed. Both π^\hat\pi and SS are the same whichever allele is ancestral.
  • Conservative with recombination. Recombination makes the sites partly independent and shrinks the true variance of dd, while the formula assumes one tree. So the test rejects less often than its nominal level.

Variants and improvements

  • Fu and Li's D and F. They compare the number of singletons (or external mutations) with SS or π^\hat\pi. They need an outgroup for the unfolded version.
  • Fay and Wu's H. Compares π^\hat\pi with an estimator that weights high-frequency derived variants, which a sweep leaves near the selected site. It needs the ancestral state.
  • Normalized versions. Zeng and coauthors normalized HH and proposed the joint use of DD and HH, which separates sweeps from demography better than either alone.
  • Simulated null distributions. Instead of a fixed approximation, simulate the null with coalescent simulation, with recombination and with a demographic model fitted to the genome-wide data. Then DD tests selection against that demography and not against constant size.
  • Per-window scans. Compute DD in windows along the genome and look for outliers relative to the genome-wide distribution, which removes most of the shared effect of demography.

When to use it

Use it as a first check of whether a gene or region fits the neutral model, and in genome scans to find candidate regions under selection, compared with the genome-wide distribution. It needs only aligned sequences and no outgroup. For a test of positive selection in coding genes that uses divergence from another species, use the McDonald-Kreitman test. For recent, incomplete sweeps that are not yet visible in the frequency spectrum, use haplotype statistics such as extended haplotype homozygosity.

Pitfalls

  • Demography mimics selection. Population growth gives negative DD genome-wide, and a bottleneck or structure in the sample can give positive DD. A significant DD under the constant-size null model does not prove selection.
  • Sequencing errors. False singletons push DD down. Low coverage, which misses rare variants, pushes it up.
  • Missing data. The formula assumes the same nn at every site. Drop or impute missing calls first, or use a version with per-site sample sizes.
  • Sample size. nn is the number of sequences (twice the number of diploid individuals), not the number of individuals.
  • Small SS. With few segregating sites the test has little power, and the null distribution is far from any continuous approximation.
  • Pooled samples. Samples from several populations have an excess of intermediate variants, and D>0D > 0 then reflects the sampling scheme.

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)
tajimas_d.py 90 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/tajimas-d/. The authors are listed in prov/GAQA42.jsonl.
"""Tajima's D from aligned sequences.

A sample is a sequence of n >= 4 strings of the same length m. Every
character is an allele; remove or impute missing data before the call. A
site with three or more alleles counts as one segregating site, and its
pairwise differences are counted in full.

The constants follow Tajima (1989), with a1 = a_n and a2 = b_n.
"""

from __future__ import annotations

import math
from collections import Counter
from fractions import Fraction
from typing import Dict, Optional, Sequence, Tuple


def tajima_constants(n: int) -> Dict[str, Fraction]:
    """The exact constants a1, a2, b1, b2, c1, c2, e1 and e2 for n sequences."""
    if n < 4:
        raise ValueError("need n >= 4")
    a1 = sum((Fraction(1, i) for i in range(1, n)), Fraction(0))
    a2 = sum((Fraction(1, i * i) for i in range(1, n)), Fraction(0))
    b1 = Fraction(n + 1, 3 * (n - 1))
    b2 = Fraction(2 * (n * n + n + 3), 9 * n * (n - 1))
    c1 = b1 - 1 / a1
    c2 = b2 - Fraction(n + 2) / (a1 * n) + a2 / (a1 * a1)
    e1 = c1 / a1
    e2 = c2 / (a1 * a1 + a2)
    return {"a1": a1, "a2": a2, "b1": b1, "b2": b2,
            "c1": c1, "c2": c2, "e1": e1, "e2": e2}


def site_statistics(seqs: Sequence[str]) -> Tuple[int, float]:
    """(S, pi): the number of segregating sites and the mean number of
    pairwise differences of the alignment seqs."""
    n = len(seqs)
    if n < 2:
        raise ValueError("need at least two sequences")
    m = len(seqs[0])
    if any(len(s) != m for s in seqs):
        raise ValueError("sequences must have the same length")
    s = 0  # @line L1
    pairs = 0
    for j in range(m):  # @line L2
        counts = Counter(row[j] for row in seqs)
        if len(counts) >= 2:
            s += 1  # @line L3
        # Pairs of sequences with different characters at site j.
        pairs += (n * n - sum(c * c for c in counts.values())) // 2  # @line L4
    pi = pairs / (n * (n - 1) / 2)  # @line L5
    return s, pi


def tajimas_d_from_stats(n: int, s: int, pi: float) -> Optional[float]:
    """Tajima's D for n sequences with S = s segregating sites and mean
    pairwise difference pi. None when s = 0, where D is not defined."""
    if s < 0:
        raise ValueError("need S >= 0")
    k = tajima_constants(n)  # @line L6
    if s == 0:
        return None  # @line L7
    a1 = float(k["a1"])
    e1 = float(k["e1"])
    e2 = float(k["e2"])
    return (pi - s / a1) / math.sqrt(e1 * s + e2 * s * (s - 1))  # @line L8


def tajimas_d(seqs: Sequence[str]) -> Optional[float]:
    """Tajima's D of the alignment seqs, or None if no site segregates."""
    s, pi = site_statistics(seqs)
    return tajimas_d_from_stats(len(seqs), s, pi)


def tajimas_d_limits(n: int) -> Tuple[float, float]:
    """The limits of the smallest and the largest possible D as S grows,
    for n sequences: all sites singletons, and all sites split as evenly
    as possible."""
    k = tajima_constants(n)
    a1 = float(k["a1"])
    root = math.sqrt(float(k["e2"]))
    low = (2.0 / n - 1.0 / a1) / root
    if n % 2 == 0:
        top = n / (2.0 * (n - 1))
    else:
        top = (n + 1) / (2.0 * n)
    return low, (top - 1.0 / a1) / root
test_tajimas_d.py 129 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/tajimas-d/. The authors are listed in prov/GAQA42.jsonl.

import itertools
import random
from fractions import Fraction

import pytest

from biostoch import check_mean, mean_var, poisson
from tajimas_d import (
    site_statistics,
    tajima_constants,
    tajimas_d,
    tajimas_d_from_stats,
    tajimas_d_limits,
)

EXAMPLE = ["100001", "100000", "010100", "001100", "001110"]


def simulate_sample(rng, n, theta):
    """A sample of n binary sequences from the neutral infinite-sites model
    without recombination. A lineage is the bit mask of the leaves below it;
    each mutation on it is a column with those leaves set to 1."""
    lineages = [1 << i for i in range(n)]
    columns = []
    while len(lineages) > 1:
        k = len(lineages)
        t = rng.expovariate(k * (k - 1) / 2.0)
        for lin in lineages:
            columns.extend([lin] * poisson(rng, theta * t / 2.0))
        i, j = rng.sample(range(k), 2)
        merged = lineages[i] | lineages[j]
        lineages = [x for idx, x in enumerate(lineages) if idx not in (i, j)]
        lineages.append(merged)
    return ["".join("1" if (c >> r) & 1 else "0" for c in columns)
            for r in range(n)]


def brute_pi(seqs):
    pairs = list(itertools.combinations(seqs, 2))
    return sum(sum(x != y for x, y in zip(a, b)) for a, b in pairs) / len(pairs)


def test_constants():
    k = tajima_constants(5)
    assert k["a1"] == Fraction(25, 12)
    assert k["c1"] == Fraction(1, 50)
    assert float(k["e1"]) == pytest.approx(0.0096)
    assert float(k["e2"]) == pytest.approx(0.0039325, abs=1e-7)
    k = tajima_constants(10)
    assert float(k["c1"]) == pytest.approx(0.0539216, abs=1e-7)
    assert float(k["c2"]) == pytest.approx(0.0472268, abs=1e-7)
    assert float(k["e1"]) == pytest.approx(0.0190605, abs=1e-7)
    assert float(k["e2"]) == pytest.approx(0.00494893, abs=1e-8)
    with pytest.raises(ValueError):
        tajima_constants(3)


def test_denominator_is_unbiased_for_the_variance():
    # E[S] = theta a1 and E[S(S-1)] = theta^2 (a1^2 + a2), so the expected
    # square of the denominator is c1 theta + c2 theta^2, exactly.
    for n in (4, 7, 12):
        k = tajima_constants(n)
        theta = Fraction(3, 2)
        lhs = k["e1"] * theta * k["a1"] + k["e2"] * theta ** 2 * (k["a1"] ** 2 + k["a2"])
        assert lhs == k["c1"] * theta + k["c2"] * theta ** 2


def test_example():
    s, pi = site_statistics(EXAMPLE)
    assert s == 6 and pi == pytest.approx(3.0)
    assert tajimas_d(EXAMPLE) == pytest.approx(0.286384, abs=1e-6)
    assert tajimas_d_from_stats(10, 10, 3.0) == pytest.approx(-0.670667, abs=1e-6)


def test_pi_matches_pairs():
    rng = random.Random(5)
    for _ in range(30):
        n = rng.randint(2, 9)
        seqs = ["".join(rng.choice("ACG") for _ in range(12)) for _ in range(n)]
        assert site_statistics(seqs)[1] == pytest.approx(brute_pi(seqs))
    assert site_statistics(["A", "C", "G", "G"]) == (1, pytest.approx(5 / 6))


def test_sign_and_limits():
    n = 10
    singletons = ["".join("1" if j == r else "0" for j in range(n)) for r in range(n)]
    assert tajimas_d(singletons) < 0
    half = ["1" * 8 if r < 5 else "0" * 8 for r in range(n)]
    assert tajimas_d(half) > 0
    low, high = tajimas_d_limits(n)
    assert low == pytest.approx(-2.18179, abs=1e-5)
    assert high == pytest.approx(2.87241, abs=1e-5)
    assert tajimas_d_limits(5)[0] == pytest.approx(-1.27572, abs=1e-5)
    assert tajimas_d_limits(5)[1] == pytest.approx(1.91357, abs=1e-5)
    big = 10 ** 7
    assert tajimas_d_from_stats(n, big, 2.0 * big / n) == pytest.approx(low, abs=1e-4)
    assert tajimas_d_from_stats(n, big, big * n / (2.0 * (n - 1))) == pytest.approx(high, abs=1e-4)
    assert tajimas_d_from_stats(n, 0, 0.0) is None
    assert tajimas_d(["AC", "AC", "AC", "AC"]) is None


def test_moments_under_the_neutral_model():
    rng = random.Random(1989)
    n, theta, reps = 10, 5.0, 15000
    k = tajima_constants(n)
    a1 = float(k["a1"])
    var_d = float(k["c1"]) * theta + float(k["c2"]) * theta ** 2
    var_pi = float(k["b1"]) * theta + float(k["b2"]) * theta ** 2
    assert var_pi == pytest.approx(9.012346, abs=1e-6)
    ds, d2, pi2, den = [], [], [], []
    for _ in range(reps):
        seqs = simulate_sample(rng, n, theta)
        s, pi = site_statistics(seqs)
        d = pi - s / a1
        ds.append(d)
        d2.append(d * d)
        pi2.append((pi - theta) ** 2)
        den.append(float(k["e1"]) * s + float(k["e2"]) * s * (s - 1))
    m, _ = mean_var(ds)
    assert check_mean(m, 0.0, var_d, reps)
    m, v = mean_var(d2)
    assert check_mean(m, var_d, v, reps)
    m, v = mean_var(pi2)
    assert check_mean(m, var_pi, v, reps)
    m, v = mean_var(den)
    assert check_mean(m, var_d, v, reps)

History

Tajima published the test in Genetics in 1989, building on his 1983 result for the variance of the mean pairwise difference and on Watterson's 1975 results for the number of segregating sites. It was the first widely used neutrality test based on the frequency spectrum, and Fu and Li (1993) and Fay and Wu (2000) followed with tests that use the frequencies more directly. Most population genetics toolkits compute it.

References

  1. Fumio Tajima, Statistical method for testing the neutral mutation hypothesis by DNA polymorphism, Genetics 123(3), 1989, pp. 585-595 (the statistic D, its constants, the bounds of D and the beta approximation for critical values)
  2. Fumio Tajima, Evolutionary relationship of DNA sequences in finite populations, Genetics 105(2), 1983, pp. 437-460 (the variance of the mean pairwise difference)
  3. G. A. Watterson, On the number of segregating sites in genetical models without recombination, Theoretical Population Biology 7(2), 1975, pp. 256-276 (the mean and the variance of the number of segregating sites)
  4. John Wakeley, Coalescent Theory, An Introduction, Roberts and Company, 2009, Chapter 4 (tests of the neutral model based on the site frequency spectrum)

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