Algorithm Search⌘K

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
Properties
deterministicexactonlineiterative
Origin
G. A. Watterson, 1975

Watterson's estimator gives the population mutation rate θ=4Nμ\theta = 4N\mu of a DNA region from a sample of nn aligned sequences. It counts the segregating sites SS, the sites where the sample is not all the same, and divides by an=∑i=1n−11/ia_n = \sum_{i=1}^{n-1} 1/i. Under the neutral infinite sites model with constant size, E[S]=θanE[S] = \theta a_n (Watterson 1975), so θ^W=S/an\hat\theta_W = S / a_n 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 ana_n is that growth. Dividing by ana_n removes the effect of the sample size and leaves the mutation rate.

The problem

Input. A sample of n≥2n \ge 2 aligned sequences of mm sites each, as strings over an alphabet of alleles. Some characters may mark missing data.

Output. The number SS of segregating sites (sites whose non-missing characters show at least two alleles) and θ^W=S/an\hat\theta_W = S / a_n. Divided by mm, it is the estimate of θ\theta per site.

The output is an estimate of θ\theta only under a model. The model here is neutral mutations, a constant population of NN diploids, random mating, and the infinite sites model, so that each segregating site comes from one mutation.

The algorithm

  1. WATTERSON(H)
  2. 1S ← 0
  3. 2for each site j = 1, ..., m do
  4. 3if the non-missing characters of column j are not all equal then S ← S + 1
  5. 4a ← 1 + 1/2 + ... + 1/(n − 1)
  6. 5return S / a

Lines L1 to L3 count the segregating sites. Line L4 computes the harmonic number ana_n, and line L5 returns the estimate. The implementation also returns an estimate of the variance of θ^W\hat\theta_W:

Var⁡^[θ^W]=θ^Wan+bnan2⋅S(S−1)an2+bn,bn=∑i=1n−11i2.\widehat{\operatorname{Var}}[\hat\theta_W] = \frac{\hat\theta_W}{a_n} + \frac{b_n}{a_n^2} \cdot \frac{S(S - 1)}{a_n^2 + b_n}, \qquad b_n = \sum_{i=1}^{n-1} \frac{1}{i^2}.

Example

The sample of the infinite sites model page has n=5n = 5 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 S=6S = 6. Line L4 gives a5=1+1/2+1/3+1/4=25/12a_5 = 1 + 1/2 + 1/3 + 1/4 = 25/12, and line L5 returns θ^W=6⋅12/25=2.88\hat\theta_W = 6 \cdot 12 / 25 = 2.88. If the six sites lie in a region of m=1000m = 1000 bases, the estimate per site is 0.002880.00288.

For the variance, b5=1+1/4+1/9+1/16=1.423611b_5 = 1 + 1/4 + 1/9 + 1/16 = 1.423611. The estimate of θ2\theta^2 is S(S−1)/(a52+b5)=30/5.763889=5.204819S(S - 1)/(a_5^2 + b_5) = 30 / 5.763889 = 5.204819, and the formula above gives Var⁡^=2.88/2.083333+1.423611⋅5.204819/4.340278=3.0896\widehat{\operatorname{Var}} = 2.88/2.083333 + 1.423611 \cdot 5.204819 / 4.340278 = 3.0896. So the standard error is about 1.761.76: six segregating sites say little about θ\theta.

The nucleotide diversity of the same sample is 33.

Correctness

The loop of lines L2 and L3 adds one for each segregating site and nothing for the other sites, so after it SS is the number of segregating sites. Line L5 returns S/anS / a_n.

The estimator is unbiased under the model. Given the coalescent tree with total branch length LL (in units of 2N2N generations), each mutation on the tree makes one new segregating site, and the mutations form a Poisson process of rate θ/2\theta/2 on the branches. So E[S∣L]=θL/2E[S \mid L] = \theta L / 2. While kk lineages exist, kk branches grow for a time TkT_k with mean 2/(k(k−1))2/(k(k-1)), so E[L]=∑k=2nk⋅2/(k(k−1))=2anE[L] = \sum_{k=2}^{n} k \cdot 2/(k(k-1)) = 2 a_n. So E[S]=θanE[S] = \theta a_n and E[θ^W]=θE[\hat\theta_W] = \theta. The same computation with the variance of the TkT_k gives Var⁡[S]=θan+θ2bn\operatorname{Var}[S] = \theta a_n + \theta^2 b_n, so

Var⁡[θ^W]=θan+θ2bnan2,\operatorname{Var}[\hat\theta_W] = \frac{\theta}{a_n} + \frac{\theta^2 b_n}{a_n^2},

and E[S(S−1)]=θ2(an2+bn)E[S(S - 1)] = \theta^2 (a_n^2 + b_n), 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 n≥2n \ge 2 sequences comes from the neutral infinite sites model: the genealogy is a Kingman coalescent tree, time is in units of 2N2N generations, and given the tree, mutations fall on the branches as a Poisson process of rate θ/2\theta/2 per unit of branch length. While kk lineages exist, the time TkT_k is exponential with rate (k2)\binom{k}{2}, and T2,…,TnT_2, \ldots, T_n are independent. Write an=∑i=1n−11/ia_n = \sum_{i=1}^{n-1} 1/i and bn=∑i=1n−11/i2b_n = \sum_{i=1}^{n-1} 1/i^2.

Lemma 1. WATTERSON returns S/anS / a_n, where SS is the number of segregating sites.

Proof. Before line L2, S=0S = 0. The loop visits each site jj once, and line L3 adds one exactly when column jj has two different non-missing characters, which is the definition of a segregating site. So after the loop SS is the number of segregating sites. Line L4 sets a=ana = a_n, and line L5 returns S/anS / a_n. □\square

Lemma 2. Let L=∑k=2nkTkL = \sum_{k=2}^{n} k T_k be the total branch length. Then E[L]=2anE[L] = 2 a_n and Var⁡[L]=4bn\operatorname{Var}[L] = 4 b_n.

Proof. While kk lineages exist, kk branches each grow by TkT_k, so the total branch length is ∑kkTk\sum_k k T_k. An exponential time with rate λ\lambda has mean 1/λ1/\lambda and variance 1/λ21/\lambda^2. With λ=k(k−1)/2\lambda = k(k-1)/2,

E[kTk]=2k−1,Var⁡[kTk]=4(k−1)2.E[k T_k] = \frac{2}{k - 1}, \qquad \operatorname{Var}[k T_k] = \frac{4}{(k - 1)^2}.

Summing over k=2,…,nk = 2, \ldots, n and using the independence of the TkT_k for the variance, E[L]=2∑i=1n−11/i=2anE[L] = 2 \sum_{i=1}^{n-1} 1/i = 2 a_n and Var⁡[L]=4∑i=1n−11/i2=4bn\operatorname{Var}[L] = 4 \sum_{i=1}^{n-1} 1/i^2 = 4 b_n. □\square

Lemma 3. E[S]=θanE[S] = \theta a_n, Var⁡[S]=θan+θ2bn\operatorname{Var}[S] = \theta a_n + \theta^2 b_n, and E[S(S−1)]=θ2(an2+bn)E[S(S-1)] = \theta^2 (a_n^2 + b_n).

Proof. Under the infinite sites model each mutation creates a new segregating site, and every segregating site comes from one mutation. So SS is the number of mutations on the tree, and given LL it is Poisson with mean θL/2\theta L / 2. By the laws of total expectation and total variance and Lemma 2,

E[S]=E ⁣[θL2]=θan,E[S] = E\!\left[\frac{\theta L}{2}\right] = \theta a_n,
Var⁡[S]=E ⁣[θL2]+Var⁡ ⁣[θL2]=θan+θ24⋅4bn=θan+θ2bn.\operatorname{Var}[S] = E\!\left[\frac{\theta L}{2}\right] + \operatorname{Var}\!\left[\frac{\theta L}{2}\right] = \theta a_n + \frac{\theta^2}{4} \cdot 4 b_n = \theta a_n + \theta^2 b_n.

Then E[S(S−1)]=Var⁡[S]+E[S]2−E[S]=θ2bn+θ2an2E[S(S - 1)] = \operatorname{Var}[S] + E[S]^2 - E[S] = \theta^2 b_n + \theta^2 a_n^2. □\square

Theorem. Under the model, E[θ^W]=θE[\hat\theta_W] = \theta and Var⁡[θ^W]=θ/an+θ2bn/an2\operatorname{Var}[\hat\theta_W] = \theta / a_n + \theta^2 b_n / a_n^2. The estimate

V=θ^Wan+bnan2⋅S(S−1)an2+bnV = \frac{\hat\theta_W}{a_n} + \frac{b_n}{a_n^2} \cdot \frac{S(S - 1)}{a_n^2 + b_n}

has E[V]=Var⁡[θ^W]E[V] = \operatorname{Var}[\hat\theta_W].

Proof. By Lemma 1, θ^W=S/an\hat\theta_W = S / a_n. By Lemma 3, E[S/an]=θE[S / a_n] = \theta and Var⁡[S/an]=Var⁡[S]/an2=θ/an+θ2bn/an2\operatorname{Var}[S / a_n] = \operatorname{Var}[S] / a_n^2 = \theta / a_n + \theta^2 b_n / a_n^2. For VV, E[θ^W/an]=θ/anE[\hat\theta_W / a_n] = \theta / a_n, and by Lemma 3, E[S(S−1)/(an2+bn)]=θ2E[S(S - 1) / (a_n^2 + b_n)] = \theta^2. By linearity, E[V]=θ/an+θ2bn/an2E[V] = \theta / a_n + \theta^2 b_n / a_n^2. ■\blacksquare

Remarks. The proof of E[S]=θanE[S] = \theta a_n 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 E[S]=θanE[S] = \theta a_n still holds when θ\theta 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 E[θ^W]=θE[\hat\theta_W] = \theta, the variance formula, E[S(S−1)]=θ2(an2+bn)E[S(S-1)] = \theta^2(a_n^2 + b_n) and E[V]=Var⁡[θ^W]E[V] = \operatorname{Var}[\hat\theta_W] on 20000 simulated samples with n=10n = 10 and θ=5\theta = 5.

Complexity

  • Time. Line L3 reads the nn characters of each of the mm columns, so the count takes Θ(nm)\Theta(n m) time in every case. Line L4 takes O(n)O(n) time, or O(1)O(1) with the approximation an≈ln⁡(n−1)+0.5772+1/(2(n−1))a_n \approx \ln(n - 1) + 0.5772 + 1/(2(n - 1)).
  • Space. Besides the input, a counter and the set of alleles of one column, which has at most the size of the alphabet: Θ(1)\Theta(1).
  • From a VCF file. When the input is a list of variant sites with genotypes, SS 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 E[S]E[S] 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 nn, but slowly. Var⁡[θ^W]→0\operatorname{Var}[\hat\theta_W] \to 0 as n→∞n \to \infty, at the rate 1/ln⁡n1/\ln n. Going from n=10n = 10 to n=100n = 100 raises ana_n only from 2.832.83 to 5.185.18. For θ=5\theta = 5, the variance is 6.5776.577 at n=10n = 10 and 3.1413.141 at n=50n = 50. More sequence length (with recombination) helps more than more sequences.
  • Smaller variance than π^\hat\pi. The nucleotide diversity π^\hat\pi is also unbiased, but its variance tends to θ/3+2θ2/9\theta/3 + 2\theta^2/9, not to 0. For θ=5\theta = 5 and n=10n = 10 it is 9.0129.012, against 6.5776.577 for θ^W\hat\theta_W.
  • No outgroup needed. A site is segregating whatever allele is ancestral.
  • Linear in the spectrum. θ^W=∑iξi/an\hat\theta_W = \sum_i \xi_i / a_n, with equal weight on every class of the site frequency spectrum. Because rare variants are the most common class, θ^W\hat\theta_W 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 mm that were sequenced, including the invariant ones. The count of invariant sites is often the hard part with real data.
  • Missing data. If site jj has data for njn_j sequences, ∑j[site j segregates]/anj\sum_j [\text{site } j \text{ segregates}] / a_{n_j} is still unbiased for θ\theta of the region, because each site has its own expectation θjanj\theta_j a_{n_j} to first order in the per-site rate.
  • Number of mutations instead of sites. At a site with kk alleles, count k−1k - 1 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 ∑iwiξi\sum_i w_i \xi_i with ∑iwi/i=1\sum_i w_i / i = 1 is unbiased. With the covariances of the ξi\xi_i (Fu 1995), one can choose the weights of the best linear unbiased estimator under the neutral model, which has a smaller variance than both θ^W\hat\theta_W and π^\hat\pi.
  • Maximum likelihood. Given the whole data and not only SS, the likelihood of θ\theta can be computed by importance sampling or MCMC over genealogies, at a far higher cost. For data with recombination, PSMC and related methods estimate θ\theta and a history of NN 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 θ\theta into an effective population size, divide by 4μ4\mu with an independent estimate of the mutation rate per generation. If the population was not of constant size, θ^W\hat\theta_W estimates a weighted average of past sizes, with more weight on recent times than π^\hat\pi has.

Pitfalls

  • Sequencing errors. An error in one read makes a false singleton. Since θ^W\hat\theta_W weights singletons as much as any other site, errors inflate it more than they inflate π^\hat\pi.
  • Sample size. ana_n uses the number of sequences, which for diploids is twice the number of individuals. Using the number of individuals gives the wrong ana_n.
  • Missing data. With a fixed nn in ana_n, 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 E[S]E[S]. The number is an estimate of θ\theta only under the neutral constant-size model; otherwise it is a summary of the data.
  • Repeat hits. When θ\theta per site is large (some viruses, distant samples), a site may have mutated more than once, and SS 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.

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)
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 θan\theta a_n, the variance θan+θ2bn\theta a_n + \theta^2 b_n, and the estimator S/anS / a_n, 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

  1. 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)
  2. 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)
  3. 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.

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