Algorithmcore
Watterson estimator
Also called Watterson's theta.
Estimate theta = 4N mu as the number of segregating sites divided by the harmonic number a_n of the sample size minus one.
- 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
- G. A. Watterson, 1975
Watterson's estimator gives the population mutation rate of a DNA region from a sample of aligned sequences. It counts the segregating sites , the sites where the sample is not all the same, and divides by . Under the neutral infinite sites model with constant size, (Watterson 1975), so is unbiased. It needs only one pass over the alignment and does not need to know which allele is ancestral. With nucleotide diversity it is one of the two estimators that Tajima's D compares.
In plain words
Line up the sequences and walk along them. At each position, look down the column: if all sequences have the same letter, move on; if not, add one to a counter. The counter is the number of places where mutations have happened in the history of the sample.
The history of a larger sample has more branches, so it has more room for mutations. But most of the extra branches are short, because new sequences mostly join the tree near its tips. The total length grows only like the logarithm of the sample size, and is that growth. Dividing by removes the effect of the sample size and leaves the mutation rate.
The problem
Input. A sample of aligned sequences of sites each, as strings over an alphabet of alleles. Some characters may mark missing data.
Output. The number of segregating sites (sites whose non-missing characters show at least two alleles) and . Divided by , it is the estimate of per site.
The output is an estimate of only under a model. The model here is neutral mutations, a constant population of diploids, random mating, and the infinite sites model, so that each segregating site comes from one mutation.
The algorithm
WATTERSON(H)- 1
S ← 0 - 2
for each site j = 1, ..., m do - 3
if the non-missing characters of column j are not all equal then S ← S + 1 - 4
a ← 1 + 1/2 + ... + 1/(n − 1) - 5
return S / a
Lines L1 to L3 count the segregating sites. Line L4 computes the harmonic number , and line L5 returns the estimate. The implementation also returns an estimate of the variance of :
Example
The sample of the infinite sites model page has sequences and six sites:
| 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 |
Every column has both a 0 and a 1, so lines L1 to L3 give . Line L4 gives , and line L5 returns . If the six sites lie in a region of bases, the estimate per site is .
For the variance, . The estimate of is , and the formula above gives . So the standard error is about : six segregating sites say little about .
The nucleotide diversity of the same sample is .
Correctness
The loop of lines L2 and L3 adds one for each segregating site and nothing for the other sites, so after it is the number of segregating sites. Line L5 returns .
The estimator is unbiased under the model. Given the coalescent tree with total branch length (in units of generations), each mutation on the tree makes one new segregating site, and the mutations form a Poisson process of rate on the branches. So . While lineages exist, branches grow for a time with mean , so . So and . The same computation with the variance of the gives , so
and , which makes the estimate of the variance above unbiased too. The proofs are below.
Proof: Watterson's estimator counts the segregating sites and is unbiased for thetafull
Setting. A sample of sequences comes from the neutral infinite sites model: the genealogy is a Kingman coalescent tree, time is in units of generations, and given the tree, mutations fall on the branches as a Poisson process of rate per unit of branch length. While lineages exist, the time is exponential with rate , and are independent. Write and .
Lemma 1. WATTERSON returns , where is the number of segregating sites.
Proof. Before line L2, . The loop visits each site once, and line L3 adds one exactly when column has two different non-missing characters, which is the definition of a segregating site. So after the loop is the number of segregating sites. Line L4 sets , and line L5 returns .
Lemma 2. Let be the total branch length. Then and .
Proof. While lineages exist, branches each grow by , so the total branch length is . An exponential time with rate has mean and variance . With ,
Summing over and using the independence of the for the variance, and .
Lemma 3. , , and .
Proof. Under the infinite sites model each mutation creates a new segregating site, and every segregating site comes from one mutation. So is the number of mutations on the tree, and given it is Poisson with mean . By the laws of total expectation and total variance and Lemma 2,
Then .
Theorem. Under the model, and . The estimate
has .
Proof. By Lemma 1, . By Lemma 3, and . For , , and by Lemma 3, . By linearity, .
Remarks. The proof of uses only the expected length of the tree of each site. With recombination, each site has its own tree, every local tree is a Kingman tree with the same expected length, and so still holds when is the rate of the whole region. Lemma 3 for the variance uses one tree for all sites, so with recombination the variance is smaller than the formula. The tests check , the variance formula, and on 20000 simulated samples with and .
Complexity
- Time. Line L3 reads the characters of each of the columns, so the count takes time in every case. Line L4 takes time, or with the approximation .
- Space. Besides the input, a counter and the set of alleles of one column, which has at most the size of the alphabet: .
- From a VCF file. When the input is a list of variant sites with genotypes, is the number of sites with at least two alleles in the sample, and the work is linear in the size of the file.
Properties
- Unbiased under the neutral model, with or without recombination, because is a sum over sites and each site has the same expected tree length. Recombination changes only the variance, which then is smaller.
- Consistent in , but slowly. as , at the rate . Going from to raises only from to . For , the variance is at and at . More sequence length (with recombination) helps more than more sequences.
- Smaller variance than . The nucleotide diversity is also unbiased, but its variance tends to , not to 0. For and it is , against for .
- No outgroup needed. A site is segregating whatever allele is ancestral.
- Linear in the spectrum. , with equal weight on every class of the site frequency spectrum. Because rare variants are the most common class, reacts strongly to an excess of rare variants.
- Streaming. The sites can arrive one at a time, in any order.
Variants and improvements
- Per site. Divide by the number of sites that were sequenced, including the invariant ones. The count of invariant sites is often the hard part with real data.
- Missing data. If site has data for sequences, is still unbiased for of the region, because each site has its own expectation to first order in the per-site rate.
- Number of mutations instead of sites. At a site with alleles, count mutations. Under the infinite sites model the two counts agree; under a finite sites model the mutation count is closer to the model, and both are too small when repeat hits are common.
- Estimators with other weights. Every with is unbiased. With the covariances of the (Fu 1995), one can choose the weights of the best linear unbiased estimator under the neutral model, which has a smaller variance than both and .
- Maximum likelihood. Given the whole data and not only , the likelihood of can be computed by importance sampling or MCMC over genealogies, at a far higher cost. For data with recombination, PSMC and related methods estimate and a history of from one genome.
When to use it
Use it as the first summary of the amount of variation in a region, to compare regions or populations, and as an input to Tajima's D and related tests. To turn into an effective population size, divide by with an independent estimate of the mutation rate per generation. If the population was not of constant size, estimates a weighted average of past sizes, with more weight on recent times than has.
Pitfalls
- Sequencing errors. An error in one read makes a false singleton. Since weights singletons as much as any other site, errors inflate it more than they inflate .
- Sample size. uses the number of sequences, which for diploids is twice the number of individuals. Using the number of individuals gives the wrong .
- Missing data. With a fixed in , sites with many missing calls segregate less often, and the estimate is too small. Use the per-site version above.
- The model. Growth, bottlenecks, structure and selection all change . The number is an estimate of only under the neutral constant-size model; otherwise it is a summary of the data.
- Repeat hits. When per site is large (some viruses, distant samples), a site may have mutated more than once, and undercounts the mutations.
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)
watterson_estimator.py 101 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/watterson-estimator/. The authors are listed in prov/BFZ8DK.jsonl.
"""Watterson's estimator of theta = 4 N mu from aligned sequences.
A sample is a sequence of n >= 2 strings of the same length m. Each
character is the allele of one sequence at one site. The characters in
`missing` (by default N, n, -, ?) are not alleles. A site is segregating when
its other characters show at least two different alleles. Under the
infinite-sites model a site has at most two alleles; a site with three or
more alleles still counts as one segregating site.
The sample size used in a_n is always n, the number of sequences, so sites
with much missing data make the estimate too small.
"""
from __future__ import annotations
from fractions import Fraction
from typing import Collection, Sequence
MISSING = frozenset("Nn-?")
def harmonic(n: int) -> Fraction:
"""a_n = 1 + 1/2 + ... + 1/(n - 1), exactly."""
if n < 2:
raise ValueError("need n >= 2")
return sum((Fraction(1, i) for i in range(1, n)), Fraction(0))
def harmonic2(n: int) -> Fraction:
"""b_n = 1 + 1/4 + ... + 1/(n - 1)^2, exactly."""
if n < 2:
raise ValueError("need n >= 2")
return sum((Fraction(1, i * i) for i in range(1, n)), Fraction(0))
def segregating_sites(seqs: Sequence[str],
missing: Collection[str] = MISSING) -> int:
"""The number S of segregating sites 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")
count = 0 # @line L1
for j in range(m): # @line L2
alleles = {s[j] for s in seqs if s[j] not in missing}
if len(alleles) >= 2:
count += 1 # @line L3
return count
def watterson_from_count(s: int, n: int) -> Fraction:
"""theta_W = S / a_n for S segregating sites in n sequences, exactly."""
if s < 0:
raise ValueError("need S >= 0")
a = harmonic(n) # @line L4
return Fraction(s) / a # @line L5
def watterson_theta(seqs: Sequence[str], per_site: bool = False,
missing: Collection[str] = MISSING) -> float:
"""Watterson's estimate of theta for the whole region of seqs.
With per_site=True the estimate is divided by the number m of sites.
"""
s = segregating_sites(seqs, missing)
theta = watterson_from_count(s, len(seqs))
if per_site:
m = len(seqs[0])
if m == 0:
raise ValueError("no sites")
theta /= m
return float(theta)
def watterson_variance(theta: float, n: int) -> float:
"""Var(theta_W) = theta / a_n + theta^2 b_n / a_n^2 under the neutral
infinite-sites model without recombination."""
a = float(harmonic(n))
b = float(harmonic2(n))
return theta / a + theta * theta * b / (a * a)
def theta_squared_from_count(s: int, n: int) -> Fraction:
"""S (S - 1) / (a_n^2 + b_n), an unbiased estimate of theta^2."""
a = harmonic(n)
b = harmonic2(n)
return Fraction(s * (s - 1)) / (a * a + b)
def watterson_variance_estimate(s: int, n: int) -> float:
"""An unbiased estimate of Var(theta_W) from S alone: the formula of
watterson_variance with theta_W for theta and S (S - 1) / (a_n^2 + b_n)
for theta^2."""
a = harmonic(n)
b = harmonic2(n)
return float(watterson_from_count(s, n) / a
+ theta_squared_from_count(s, n) * b / (a * a))
test_watterson_estimator.py 108 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/watterson-estimator/. The authors are listed in prov/BFZ8DK.jsonl.
import random
from fractions import Fraction
import pytest
from biostoch import check_mean, mean_var, poisson
from watterson_estimator import (
harmonic,
harmonic2,
segregating_sites,
theta_squared_from_count,
watterson_from_count,
watterson_theta,
watterson_variance,
watterson_variance_estimate,
)
EXAMPLE = ["100001", "100000", "010100", "001100", "001110"]
def sample_segregating_sites(rng, n, theta):
"""S under the neutral infinite-sites model: a Kingman total branch
length L, then S ~ Poisson(theta L / 2)."""
total = 0.0
for k in range(n, 1, -1):
total += k * rng.expovariate(k * (k - 1) / 2.0)
return poisson(rng, theta * total / 2.0)
def test_harmonic_numbers():
assert harmonic(2) == 1
assert harmonic(5) == Fraction(25, 12)
assert abs(float(harmonic(10)) - 2.828968) < 1e-6
assert abs(float(harmonic2(10)) - 1.539768) < 1e-6
with pytest.raises(ValueError):
harmonic(1)
def test_example_matrix():
assert segregating_sites(EXAMPLE) == 6
assert watterson_from_count(6, 5) == Fraction(72, 25)
assert watterson_theta(EXAMPLE) == pytest.approx(2.88)
assert watterson_theta(EXAMPLE, per_site=True) == pytest.approx(0.48)
def test_dna_and_missing_data():
seqs = ["ACGTAC", "ACGTTC", "ACNTAG", "AC-TAC"]
# Site 3 has only G and missing values; sites 5 and 6 segregate.
assert segregating_sites(seqs) == 2
# A site with three alleles counts once.
assert segregating_sites(["A", "C", "G"]) == 1
# Invariant sites do not change S.
assert segregating_sites([s + "GGG" for s in EXAMPLE]) == 6
def test_order_does_not_matter():
rng = random.Random(7)
rows = ["".join(rng.choice("ACGT") for _ in range(30)) for _ in range(8)]
s = segregating_sites(rows)
perm = list(range(30))
rng.shuffle(perm)
cols = ["".join(r[j] for j in perm) for r in rows]
assert segregating_sites(list(reversed(rows))) == s
assert segregating_sites(cols) == s
def test_bad_input():
with pytest.raises(ValueError):
segregating_sites(["ACG"])
with pytest.raises(ValueError):
segregating_sites(["ACG", "AC"])
with pytest.raises(ValueError):
watterson_from_count(-1, 4)
def test_unbiased_under_the_neutral_model():
rng = random.Random(2024)
n, theta, reps = 10, 5.0, 20000
counts = [sample_segregating_sites(rng, n, theta) for _ in range(reps)]
estimates = [float(watterson_from_count(s, n)) for s in counts]
m, _ = mean_var(estimates)
var = watterson_variance(theta, n)
assert abs(var - 6.577362) < 1e-5
assert check_mean(m, theta, var, reps)
# The sample variance of theta_W against Watterson's formula.
sq = [(x - theta) ** 2 for x in estimates]
m2, v2 = mean_var(sq)
assert check_mean(m2, var, v2, reps)
# S (S - 1) / (a_n^2 + b_n) is unbiased for theta^2.
t2 = [float(theta_squared_from_count(s, n)) for s in counts]
m3, v3 = mean_var(t2)
assert check_mean(m3, theta * theta, v3, reps)
# The estimate of the variance is unbiased for it.
ve = [watterson_variance_estimate(s, n) for s in counts]
m4, v4 = mean_var(ve)
assert check_mean(m4, var, v4, reps)
def test_two_sequences():
rng = random.Random(11)
theta, reps = 1.5, 20000
xs = [float(watterson_from_count(sample_segregating_sites(rng, 2, theta), 2))
for _ in range(reps)]
m, _ = mean_var(xs)
assert check_mean(m, theta, theta + theta * theta, reps)
History
Watterson's 1975 paper in Theoretical Population Biology derived the distribution of the number of segregating sites in a sample from a neutral population without recombination, under Kimura's infinite sites model of 1969. It gave the mean , the variance , and the estimator , before Kingman formalized the coalescent in 1982. Tajima's 1989 test used it together with the mean pairwise difference, and it is now one of the standard outputs of population genetics software.
References
- 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 theta a_n and the variance of the number of segregating sites, and the estimator of theta)
- Fumio Tajima, Statistical method for testing the neutral mutation hypothesis by DNA polymorphism, Genetics 123(3), 1989, pp. 585-595 (the estimate of theta squared from S, used in the variance of D)
- John Wakeley, Coalescent Theory, An Introduction, Roberts and Company, 2009, Chapter 4 (the number of segregating sites and estimators of theta)
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.
| 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 BFZ8DK Edit this page History Report an error Markdown