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
- Model
- Real RAM
- Properties
- deterministicexactonlineiterative
- Evidence
- Proof sketchCode in 1 languages
- 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 that have the same mean under that model: the mean pairwise difference , and Watterson's estimator from the number of segregating sites . Their difference, divided by an estimate of its standard deviation, is . 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 aligned sequences of sites each, without missing data.
Output. The statistic
where is the number of segregating sites, is the mean number of pairwise differences, and , , depend only on :
is not defined when . For every segregating site splits the sample 1 to 2 or 2 to 1, so always and ; the test needs .
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
TAJIMA-D(H)- 1
S ← 0; P ← 0 - 2
for each site j = 1, ..., m do - 3
if column j is not all equal then S ← S + 1 - 4
P ← P + the number of pairs of sequences that differ at site j - 5
π ← P / (n(n − 1)/2) - 6
compute a_1, e_1 and e_2 from n - 7
if S = 0 then return undefined - 8
return (π − S / a_1) / sqrt(e_1 S + e_2 S (S − 1))
Line L4 does not look at pairs. If the alleles of column occur times, with , the number of differing pairs is ; for two alleles this is . So one pass over the alignment gives both and .
Tajima suggested comparing with a beta distribution on the interval 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 and the limits of and , and leaves the choice of null distribution to the caller.
Example
The sample of the infinite sites model page has :
| 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 , so , and line L4 adds , a total of . Line L5 gives .
For the constants are , , , , , , and . The numerator is . The denominator is . So , 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: , and , where . With and , .
Correctness
Lines L2 to L4 add, for each site, one to if it segregates and the number of differing pairs to . A pair of sequences differs at sites, so , 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, (Tajima 1983) and (Watterson 1975), so the numerator has mean 0. Second, . This comes from , , and the covariance of and . Third, since and , the square of the denominator, , has mean exactly . So is 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.
itself has mean close to 0 and variance close to 1, but not exactly, because the denominator is random and depends on .
Proof: TAJIMA-D computes D, and its numerator and squared denominator have the right meansfull
Setting. is an alignment of sequences and sites without missing data. For sequences , is the number of sites where they differ, and . is the number of segregating sites. The constants are those of the page.
Lemma 1. At a site whose alleles occur times, with , the number of pairs of sequences with different alleles is .
Proof. Count ordered pairs with . There are of them, and have the same allele. So ordered pairs have different alleles, and each unordered pair is counted twice.
Lemma 2. After line L5, is the number of segregating sites and .
Proof. Line L3 adds one exactly for the sites that are not constant. By Lemma 1, line L4 adds to the number of pairs that differ at site . Summed over the sites, , since both sides count the pairs (site, pair of sequences) with a difference. Line L5 divides by the number of pairs.
By Lemma 2, line L8 returns the value of the definition when , and line L7 returns undefined when , where the denominator is 0.
For the rest, the sample comes from the null model: a Kingman coalescent tree with time in units of generations, and given the tree, mutations as a Poisson process of rate on the branches, each at a new site.
Lemma 3. .
Proof. For two sequences and , the lineages of the pair alone form a Kingman coalescent of two: they merge after a time that is exponential with rate 1, so . The path between and in the tree has length . Each mutation on that path, and no other, separates them, and under the infinite sites model each mutation is at its own site. So is Poisson with mean given , and . The mean over the pairs has the same expectation.
Lemma 4. and .
Proof. Given the total branch length , is Poisson with mean , and with independent exponential of rate . So and . For a Poisson variable with mean , . Hence and .
Theorem. Under the null model, the numerator has , and the squared denominator has
Proof. By Lemmas 3 and 4, . By Lemma 4 and the definitions and ,
Remarks. Tajima (1989) showed that under the null model without recombination, from (Tajima 1983), and the covariance of and . Together with the theorem, the squared denominator is an unbiased estimate of . That variance is cited here and not proved. The tests check it, the variance of and the theorem on 15000 samples simulated with and , where and . 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 in every case. Line L6 takes time.
- Space. A few counters and the allele counts of one column: 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 in sliding windows. With prefix sums of the per-site values of and , every window costs after one pass.
Properties
- Scaled. Division by the estimated standard deviation puts on a common scale, so values from regions with different mutation rates can be compared roughly.
- Bounded. For a given , is smallest when all sites are singletons () and largest when every site splits the sample as evenly as possible. As these bounds tend to and , with for even and for odd . For the limits are and ; for , and ; for , and . With small samples, values beyond 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 and are the same whichever allele is ancestral.
- Conservative with recombination. Recombination makes the sites partly independent and shrinks the true variance of , 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 or . They need an outgroup for the unfolded version.
- Fay and Wu's H. Compares 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 and proposed the joint use of and , 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 tests selection against that demography and not against constant size.
- Per-window scans. Compute 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 genome-wide, and a bottleneck or structure in the sample can give positive . A significant under the constant-size null model does not prove selection.
- Sequencing errors. False singletons push down. Low coverage, which misses rare variants, pushes it up.
- Missing data. The formula assumes the same at every site. Drop or impute missing calls first, or use a version with per-site sample sizes.
- Sample size. is the number of sequences (twice the number of diploid individuals), not the number of individuals.
- Small . 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 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.
# 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
- 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)
- Fumio Tajima, Evolutionary relationship of DNA sequences in finite populations, Genetics 105(2), 1983, pp. 437-460 (the variance of the mean pairwise difference)
- 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)
- 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.
| Ladder | Level | What the next level needs |
|---|---|---|
| Human proof | H1 sketch |
|
| Lean | L0 no Lean part |
|
| Code (python) | I0 not checked yet |
|
| Visual | V0 none |
|
| Writing | W2 basic |
|
Tag GAQA42 Edit this page History Report an error Markdown