Algorithm Search⌘K

Algorithmcore

Chao1 estimator

Also called Chao1 species richness estimator.

Estimate the number of species including unseen ones as the observed count plus f1^2 / (2 f2), from singletons and doubletons.

Time
Θ(n log s) worstΘ(n) average · best
Space
Θ(s) extra
Where
n = the number of individuals in the sample; s = the number of observed species
Properties
deterministicnot exactonlineiterative
Origin
Anne Chao, 1984

The Chao1 estimator gives a lower estimate of the number of species SS in a community from one sample of nn individuals. Rare species are the ones that a sample misses, and the sample shows how many rare species there are: f1f_1 species have one individual in the sample (singletons) and f2f_2 species have two (doubletons). Chao's estimate is S^=Sobs+f12/(2f2)\hat S = S_{obs} + f_1^2 / (2 f_2). When f1f_1 is large compared with f2f_2, many species are still unseen. When f1=0f_1 = 0, the sample has probably found all species. The formula is not a guess at the shape of the species abundance distribution. It comes from an inequality that holds for every community, so its expected value is a lower bound of the true richness, up to the error of replacing expected counts with observed ones.

In plain words

You walk through a forest and write down the species of every bird you see. At the end you have a list of species and how many birds of each one you saw.

Some species you saw many times. Some you saw only once, and some only twice. The species you saw only once are a warning: if there are many of them, there must be other rare species that you did not see at all. If almost every species turned up at least twice, you probably saw nearly all of them.

The method adds to the number of species you saw a correction that is large when once-seen species are common and twice-seen species are few. The answer is a careful lower guess, not the exact number.

The problem

Input. A sample of nn individuals, given as the list of their species labels.

Model. The community has SS species with relative abundances p1,…,pS>0p_1, \ldots, p_S > 0 that sum to 1. The nn individuals are drawn independently, and each one belongs to species ii with probability pip_i (multinomial sampling). Let XiX_i be the number of individuals of species ii in the sample, and fkf_k the number of species with Xi=kX_i = k. Then Sobs=S−f0S_{obs} = S - f_0, and f0f_0, the number of unseen species, is what the estimate must supply.

Output. nn, SobsS_{obs}, f1f_1, f2f_2, the classic estimate Sobs+f12/(2f2)S_{obs} + f_1^2 / (2 f_2) (no value when f2=0f_2 = 0), the bias-corrected estimate Sobs+f1(f1−1)/(2(f2+1))S_{obs} + f_1 (f_1 - 1)/(2 (f_2 + 1)), and Chao's variance estimate of the classic form.

The algorithm

  1. CHAO1(sample)
  2. 1count ← an empty map; for each label x in sample: count[x] ← count[x] + 1
  3. 2n ← the length of sample; S_obs ← the number of keys of count
  4. 3f1 ← the number of species with count 1; f2 ← the number of species with count 2
  5. 4S_bc ← S_obs + f1 (f1 - 1) / (2 (f2 + 1))
  6. 5if f2 = 0 then S_classic ← no value; V ← no value
  7. 6else q ← f1 / f2; S_classic ← S_obs + q f1 / 2; V ← f2 (q^4 / 4 + q^3 + q^2 / 2)
  8. 7return (n, S_obs, f1, f2, S_classic, S_bc, V)

Line L1 counts the individuals of each species. Lines L2 and L3 reduce the counts to the frequency counts that the estimate uses: the number of species, the singletons and the doubletons. Line L4 is the bias-corrected form, which has a value for every sample. Line L6 is the classic form, since qf1/2=f12/(2f2)q f_1 / 2 = f_1^2 / (2 f_2), and Chao's (1987) variance estimate. Line L5 skips both when there are no doubletons.

Example

A sample of n=16n = 16 birds has 5 of species A, 3 of B, 2 each of C and D, and 1 each of E, F, G and H.

line what it computes value
L1 counts A 5, B 3, C 2, D 2, E 1, F 1, G 1, H 1 8 keys
L2 the sample size and the observed species n=16n = 16, Sobs=8S_{obs} = 8
L3 singletons E, F, G, H; doubletons C, D f1=4f_1 = 4, f2=2f_2 = 2
L4 8+4⋅3/(2⋅3)8 + 4 \cdot 3 / (2 \cdot 3) Sbc=10S_{bc} = 10
L6 q=2q = 2, 8+2⋅4/28 + 2 \cdot 4 / 2, 2(4+8+2)2 (4 + 8 + 2) Sclassic=12S_{classic} = 12, V=28V = 28

The form with the factor (n−1)/n(n - 1)/n (see "Variants and improvements") gives 8+(15/16)⋅4=11.758 + (15/16) \cdot 4 = 11.75. For a larger sample with Sobs=20S_{obs} = 20, f1=6f_1 = 6 and f2=3f_2 = 3, the classic form gives 20+36/6=2620 + 36 / 6 = 26, the bias-corrected form gives 20+30/8=23.7520 + 30 / 8 = 23.75, and the variance estimate is 3(4+8+2)=423 (4 + 8 + 2) = 42.

Correctness

Lines L1 to L3 compute nn, SobsS_{obs}, f1f_1 and f2f_2 exactly. The statistical claim is a theorem about expected values. For multinomial sampling of nn individuals,

E[f0]≥n−1n⋅E[f1]22 E[f2],\mathbb{E}[f_0] \ge \frac{n - 1}{n} \cdot \frac{\mathbb{E}[f_1]^2}{2\, \mathbb{E}[f_2]},

with equality if and only if all SS species have the same abundance. Under Poisson sampling the same bound holds without the factor (n−1)/n(n - 1)/n. The proof is the Cauchy-Schwarz inequality on ∑ipi(1−pi)n−1\sum_i p_i (1 - p_i)^{n - 1}. Line L6 puts the observed f1f_1 and f2f_2 in place of their expected values. So the estimate targets a lower bound of SS, and the step from expected to observed counts is a plug-in, not a theorem. The full proof is in proofs/correctness.md.

Proof: The frequency counts, and the Cauchy-Schwarz lower bound behind Chao1full

Setting. A community has S≥2S \ge 2 species with abundances p1,…,pSp_1, \ldots, p_S, all in (0,1)(0, 1), with ∑ipi=1\sum_i p_i = 1. A sample of n≥2n \ge 2 individuals is drawn by multinomial sampling: each individual is of species ii with probability pip_i, independently of the others. Let XiX_i be the number of individuals of species ii, and fk=∣{i:Xi=k}∣f_k = |\{i : X_i = k\}|.

Claim 1 (the counts). Lines L1 to L3 return nn, Sobs=∣{i:Xi≥1}∣S_{obs} = |\{i : X_i \ge 1\}|, f1f_1 and f2f_2.

Proof. Line L1 adds 1 to the count of the label of each individual, once per individual. So after line L1, each label that occurs in the sample is a key, and its value is the number of individuals with that label, which is XiX_i for species ii. Labels that do not occur are not keys. Line L2 returns the length of the sample, nn, and the number of keys, SobsS_{obs}. Line L3 counts the keys with value 1 and with value 2, which are f1f_1 and f2f_2. □\square

Claim 2 (the expected frequency counts). E[fk]=∑i=1S(nk)pik(1−pi)n−k\mathbb{E}[f_k] = \sum_{i=1}^{S} \binom{n}{k} p_i^k (1 - p_i)^{n - k} for 0≤k≤n0 \le k \le n, and S=E[Sobs]+E[f0]S = \mathbb{E}[S_{obs}] + \mathbb{E}[f_0].

Proof. XiX_i has the binomial law with parameters nn and pip_i, so Pr⁡(Xi=k)=(nk)pik(1−pi)n−k\Pr(X_i = k) = \binom{n}{k} p_i^k (1 - p_i)^{n - k}. Write fk=∑i1[Xi=k]f_k = \sum_i \mathbf{1}[X_i = k] and use linearity of expectation. Every species has either Xi=0X_i = 0 or Xi≥1X_i \ge 1, so S=f0+SobsS = f_0 + S_{obs} for every sample, and the second statement follows by taking expectations. □\square

Claim 3 (the lower bound). E[f2]>0\mathbb{E}[f_2] > 0, and

E[f0]≥n−1n⋅E[f1]22 E[f2],\mathbb{E}[f_0] \ge \frac{n - 1}{n} \cdot \frac{\mathbb{E}[f_1]^2}{2\, \mathbb{E}[f_2]},

with equality if and only if p1=p2=⋯=pSp_1 = p_2 = \cdots = p_S.

Proof. Step 1. Each term of E[f2]\mathbb{E}[f_2] in Claim 2 is positive, because 0<pi<10 < p_i < 1 and n≥2n \ge 2. So E[f2]>0\mathbb{E}[f_2] > 0.

Step 2. Let ai=(1−pi)n/2a_i = (1 - p_i)^{n/2} and bi=pi(1−pi)n/2−1b_i = p_i (1 - p_i)^{n/2 - 1}. Both are positive. Then ai2=(1−pi)na_i^2 = (1 - p_i)^n, aibi=pi(1−pi)n−1a_i b_i = p_i (1 - p_i)^{n - 1} and bi2=pi2(1−pi)n−2b_i^2 = p_i^2 (1 - p_i)^{n - 2}. By Claim 2,

∑iai2=E[f0],∑iaibi=E[f1]n,∑ibi2=2 E[f2]n(n−1).\sum_i a_i^2 = \mathbb{E}[f_0], \qquad \sum_i a_i b_i = \frac{\mathbb{E}[f_1]}{n}, \qquad \sum_i b_i^2 = \frac{2\, \mathbb{E}[f_2]}{n (n - 1)}.

Step 3. The Cauchy-Schwarz inequality gives (∑iaibi)2≤∑iai2∑ibi2\left(\sum_i a_i b_i\right)^2 \le \sum_i a_i^2 \sum_i b_i^2, so

E[f1]2n2≤E[f0]⋅2 E[f2]n(n−1).\frac{\mathbb{E}[f_1]^2}{n^2} \le \mathbb{E}[f_0] \cdot \frac{2\, \mathbb{E}[f_2]}{n (n - 1)}.

Multiply by n(n−1)/(2 E[f2])>0n (n - 1) / (2\, \mathbb{E}[f_2]) > 0 to get the claim.

Step 4. Equality holds in Cauchy-Schwarz if and only if the vectors (ai)(a_i) and (bi)(b_i) are proportional. Since ai>0a_i > 0, this means that bi/ai=pi/(1−pi)b_i / a_i = p_i / (1 - p_i) is the same for all ii. The map p↦p/(1−p)p \mapsto p / (1 - p) is strictly increasing on (0,1)(0, 1), so this holds if and only if all pip_i are equal. □\square

Claim 4 (Poisson sampling). If instead the XiX_i are independent with Poisson laws of means λi>0\lambda_i > 0, then E[f0]≥E[f1]2/(2 E[f2])\mathbb{E}[f_0] \ge \mathbb{E}[f_1]^2 / (2\, \mathbb{E}[f_2]), with equality if and only if all λi\lambda_i are equal.

Proof. Now E[fk]=∑ie−λiλik/k!\mathbb{E}[f_k] = \sum_i e^{-\lambda_i} \lambda_i^k / k!. Take ai=e−λi/2a_i = e^{-\lambda_i / 2} and bi=λie−λi/2b_i = \lambda_i e^{-\lambda_i / 2}. Then ∑ai2=E[f0]\sum a_i^2 = \mathbb{E}[f_0], ∑aibi=E[f1]\sum a_i b_i = \mathbb{E}[f_1] and ∑bi2=2 E[f2]\sum b_i^2 = 2\, \mathbb{E}[f_2], and Cauchy-Schwarz gives the bound. Equality holds if and only if bi/ai=λib_i / a_i = \lambda_i is constant. □\square

Claim 5 (what lines L4 to L6 compute). Line L6 returns Sobs+f12/(2f2)S_{obs} + f_1^2 / (2 f_2) when f2≥1f_2 \ge 1, and Chao's variance formula f2(q4/4+q3+q2/2)f_2 (q^4/4 + q^3 + q^2/2) with q=f1/f2q = f_1 / f_2. Line L4 returns Sobs+f1(f1−1)/(2(f2+1))S_{obs} + f_1 (f_1 - 1)/(2 (f_2 + 1)) for every sample. Both are ≥Sobs\ge S_{obs}. If f1≥1f_1 \ge 1 and f2≥1f_2 \ge 1, the value of line L4 is less than the value of line L6.

Proof. Line L6 computes qf1/2=f12/(2f2)q f_1 / 2 = f_1^2 / (2 f_2), so the first statement holds, and the variance is the formula as written. Both corrections are products and quotients of numbers ≥0\ge 0, so both estimates are ≥Sobs\ge S_{obs}. If f1≥1f_1 \ge 1 and f2≥1f_2 \ge 1, then 0≤f1(f1−1)<f120 \le f_1 (f_1 - 1) < f_1^2 and 2(f2+1)>2f2>02 (f_2 + 1) > 2 f_2 > 0, so f1(f1−1)/(2(f2+1))<f12/(2f2)f_1 (f_1 - 1) / (2 (f_2 + 1)) < f_1^2 / (2 f_2). □\square

Conclusion. By Claims 2 and 3, S=E[Sobs]+E[f0]≥E[Sobs]+n−1nE[f1]2/(2 E[f2])S = \mathbb{E}[S_{obs}] + \mathbb{E}[f_0] \ge \mathbb{E}[S_{obs}] + \frac{n - 1}{n} \mathbb{E}[f_1]^2 / (2\, \mathbb{E}[f_2]) for every community. Line L6 evaluates the same expression with the observed SobsS_{obs}, f1f_1 and f2f_2 in place of their expected values (and without the factor (n−1)/n(n - 1)/n, which is the Poisson form of Claim 4). By Claim 1, the inputs of this expression are computed exactly. So the algorithm returns the plug-in estimate of a lower bound of SS, and this lower bound is equal to SS exactly when all species are equally abundant. The step from expected to observed counts is an estimate, and no claim on its error is made here. ■\blacksquare

Complexity

Time. Line L1 does nn map updates. With a hash map this is Θ(n)\Theta(n) expected time, and with a balanced search tree it is Θ(nlog⁡s)\Theta(n \log s) in the worst case, for s=Sobss = S_{obs} keys. Line L3 reads the ss counts once, in Θ(s)⊆O(n)\Theta(s) \subseteq O(n) time. Lines L4 to L6 do a fixed number of arithmetic operations.

Space. The map holds ss keys and their counts, so the extra space is Θ(s)\Theta(s). The algorithm is online: it can read the sample as a stream and keep only the map, and it can then report the estimate after any prefix.

Properties

  • A lower bound (theorem). The expected-value form is at most SS for every community, by the inequality above. It is equal to SS only when all abundances are equal. A community with many very rare species can have far more species than any estimate from f1f_1 and f2f_2 shows.
  • Never below the observed count (theorem). Both forms are at least SobsS_{obs}, and both are equal to SobsS_{obs} when f1=0f_1 = 0. The bias-corrected form is smaller than the classic form when f1≥1f_1 \ge 1 and f2≥1f_2 \ge 1, because f1−1<f1f_1 - 1 < f_1 and f2+1>f2f_2 + 1 > f_2.
  • When f2=0f_2 = 0. The classic form has no value. The bias-corrected form gives Sobs+f1(f1−1)/2S_{obs} + f_1 (f_1 - 1)/2, which is a large correction. A sample with no doubletons is too small for a reliable estimate.
  • Behavior in a simulation (measurement). Take S=30S = 30 species with pip_i proportional to 1/i1/i and n=100n = 100. The exact values are E[Sobs]=24.12\mathbb{E}[S_{obs}] = 24.12 and a lower bound of 29.1529.15 from the inequality. In 2000 samples drawn with Python's random.Random(5).choices, the bias-corrected form had mean 29.1829.18, the classic form had mean 31.4331.43 over the 1999 samples with f2>0f_2 > 0, and SobsS_{obs} had mean 24.1624.16.
  • Variance (known result). VV of line L6 is the variance estimate of Chao (1987), a large-sample approximation of the same kind as the delta method. Confidence intervals are usually built on the log of S^−Sobs\hat S - S_{obs}, so that the lower end is not below SobsS_{obs}.

Variants and improvements

  • The factor (n−1)/n(n - 1)/n. Under multinomial sampling of individuals the bound is Sobs+n−1nf122f2S_{obs} + \frac{n - 1}{n} \frac{f_1^2}{2 f_2}. The factor matters only for small nn.
  • Bias-corrected form. Line L4 is the form in Gotelli and Colwell (2011), and it has a value when f2=0f_2 = 0. With the factor it is Sobs+n−1nf1(f1−1)2(f2+1)S_{obs} + \frac{n - 1}{n} \frac{f_1 (f_1 - 1)}{2 (f_2 + 1)}.
  • iChao1. Chiu, Wang, Walther and Chao (2014) add a term from f3f_3 and f4f_4 that makes the bound sharper.
  • Chao2. For incidence data (the presence or absence of each species in each of several sampling units), replace f1f_1 and f2f_2 with the numbers of species found in one and in two units. The same argument applies.
  • ACE and the jackknife. The abundance-based coverage estimator uses all rare species, not only singletons and doubletons, and the jackknife estimators use f1f_1 and f2f_2 with other weights. They are not lower bounds.
  • Capture-recapture. Chao (1987) uses the same bound for the number of animals in a population with unequal catchability, with the numbers of animals caught once and twice. With equal catchability and two samples, the Lincoln-Petersen estimator is the simpler tool.
  • Other fields. Good-Turing estimation uses the same f1f_1 to estimate the total probability of unseen words, and STADS uses these ideas to estimate how much behavior a fuzzer has not yet found.

When to use it

Use it when you need a minimum number of species, and the sample is a set of individuals (or reads, or words) drawn from one community. It needs only the frequency counts, and it makes no assumption on the shape of the abundance distribution. Report it together with SobsS_{obs}, nn, f1f_1, f2f_2 and an interval. To compare communities sampled with different effort, put the estimate next to the rarefaction curves of the samples. Do not use it as an estimate of the exact richness of a community with a long tail of very rare species: the true value can be much higher.

Pitfalls

  • No doubletons. Line L6 divides by f2f_2. When f2=0f_2 = 0, skip it at line L5 and report the bias-corrected form of line L4, and say that the sample is very small.
  • Counting errors make singletons. A single misidentified individual or a sequencing error creates a false species with count 1. This raises f1f_1 at line L3, and the estimate grows by about f1/f2f_1 / f_2 for each false singleton. In amplicon sequencing data, denoise the reads before line L1, and do not use Chao1 on data from which singletons were removed.
  • Pooled samples. Line L1 assumes one sample from one community. Pooling samples from different habitats mixes communities, and the estimate then refers to no real community.
  • Reading it as an exact count. The theorem gives a lower bound. Do not report SclassicS_{classic} as the true number of species.

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)
chao1_estimator.py 95 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/chao1-estimator/. The authors are listed in prov/A0Z4WE.jsonl.
"""The Chao1 lower estimate of species richness.

Input: the species labels of the n individuals of one sample. The estimate
uses the number of observed species S_obs, the singletons f1 and the
doubletons f2. All estimates are exact fractions.Fraction values.

Cost: Theta(n) expected time with the hash map of line L1, and Theta(s)
extra space for s observed species.
"""

from __future__ import annotations

from dataclasses import dataclass
from fractions import Fraction
from math import comb
from typing import Dict, Hashable, Iterable, Optional, Sequence


@dataclass(frozen=True)
class Chao1Result:
    """The frequency counts and the estimates of one sample."""

    n: int
    s_obs: int
    f1: int
    f2: int
    classic: Optional[Fraction]
    bias_corrected: Fraction
    variance: Optional[Fraction]


def frequency_counts(counts: Iterable[int]) -> Dict[int, int]:
    """Map k -> f_k, the number of species with k individuals (k >= 1)."""
    out: Dict[int, int] = {}
    for k in counts:
        if k < 1:
            raise ValueError("species counts must be >= 1")
        out[k] = out.get(k, 0) + 1
    return out


def chao1_classic(s_obs: int, f1: int, f2: int, n: Optional[int] = None) -> Optional[Fraction]:
    """S_obs + f1^2 / (2 f2), or None when f2 = 0. With n, the factor
    (n - 1) / n of multinomial sampling is applied to the correction."""
    if f2 == 0:
        return None
    extra = Fraction(f1 * f1, 2 * f2)
    if n is not None:
        extra *= Fraction(n - 1, n)
    return s_obs + extra


def chao1_bias_corrected(s_obs: int, f1: int, f2: int, n: Optional[int] = None) -> Fraction:
    """S_obs + f1 (f1 - 1) / (2 (f2 + 1)), with the optional factor (n - 1) / n."""
    extra = Fraction(f1 * (f1 - 1), 2 * (f2 + 1))
    if n is not None:
        extra *= Fraction(n - 1, n)
    return s_obs + extra


def chao1_variance(f1: int, f2: int) -> Optional[Fraction]:
    """Chao's (1987) variance estimate f2 (q^4 / 4 + q^3 + q^2 / 2) with
    q = f1 / f2, or None when f2 = 0."""
    if f2 == 0:
        return None
    q = Fraction(f1, f2)
    return f2 * (q ** 4 / 4 + q ** 3 + q ** 2 / 2)


def chao1(sample: Sequence[Hashable]) -> Chao1Result:
    """Compute the Chao1 estimates from the species labels of a sample."""
    count: Dict[Hashable, int] = {}
    for x in sample:
        count[x] = count.get(x, 0) + 1  # @line L1
    n = len(sample)  # @line L2
    s_obs = len(count)
    freq = frequency_counts(count.values())
    f1 = freq.get(1, 0)  # @line L3
    f2 = freq.get(2, 0)
    s_bc = chao1_bias_corrected(s_obs, f1, f2)  # @line L4
    if f2 == 0:  # @line L5
        s_classic = None
        v = None
    else:
        s_classic = chao1_classic(s_obs, f1, f2)  # @line L6
        v = chao1_variance(f1, f2)
    return Chao1Result(n, s_obs, f1, f2, s_classic, s_bc, v)  # @line L7


def expected_frequency(p: Sequence[Fraction], n: int, k: int) -> Fraction:
    """E[f_k] = sum over species of C(n, k) p^k (1 - p)^(n - k) for
    multinomial sampling of n individuals with abundances p."""
    return sum((comb(n, k) * q ** k * (1 - q) ** (n - k) for q in p), Fraction(0))
test_chao1_estimator.py 122 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/chao1-estimator/. The authors are listed in prov/A0Z4WE.jsonl.
"""Tests of the Chao1 estimates.

The oracles are run-length counts of a sorted sample, exact enumeration of
all samples of a small community with Fraction, the exact moments of f1, and
a simulation with random.Random and a fixed seed.
"""

import itertools
import random
from fractions import Fraction

from biostoch import check_mean, mean_var
from chao1_estimator import (
    chao1,
    chao1_bias_corrected,
    chao1_classic,
    chao1_variance,
    expected_frequency,
)


def runs(sample):
    """Counts per species by sorting the labels: an oracle for line L1."""
    out = []
    for _, group in itertools.groupby(sorted(sample)):
        out.append(len(list(group)))
    return out


def test_check_values():
    assert chao1_classic(20, 6, 3) == 26
    assert chao1_bias_corrected(20, 6, 3) == Fraction(95, 4)
    assert chao1_variance(6, 3) == 42


def test_page_example():
    sample = list("AAAAABBBCCDDEFGH")
    res = chao1(sample)
    assert (res.n, res.s_obs, res.f1, res.f2) == (16, 8, 4, 2)
    assert res.classic == 12
    assert res.bias_corrected == 10
    assert res.variance == 28
    assert chao1_classic(8, 4, 2, n=16) == Fraction(47, 4)


def test_edge_cases():
    empty = chao1([])
    assert (empty.n, empty.s_obs, empty.classic, empty.bias_corrected) == (0, 0, None, 0)
    one = chao1(["x"])
    assert one.classic is None and one.bias_corrected == 1
    no_doubletons = chao1(list("abcd"))
    assert no_doubletons.classic is None and no_doubletons.variance is None
    assert no_doubletons.bias_corrected == 4 + 6
    all_common = chao1(list("aabbccc"))
    assert all_common.classic == 3 and all_common.bias_corrected == 3


def test_counts_against_sorting():
    rng = random.Random(21)
    for _ in range(500):
        k = rng.randint(1, 12)
        sample = [rng.randrange(k) for _ in range(rng.randint(0, 40))]
        res = chao1(sample)
        c = runs(sample)
        assert res.n == len(sample)
        assert res.s_obs == len(c)
        assert res.f1 == c.count(1) and res.f2 == c.count(2)
        assert res.bias_corrected >= res.s_obs
        if res.classic is not None:
            assert res.classic >= res.bias_corrected >= res.s_obs


def test_expected_frequency_by_enumeration():
    p = [Fraction(1, 2), Fraction(1, 3), Fraction(1, 6)]
    n = 4
    exact = [Fraction(0)] * (n + 1)
    for seq in itertools.product(range(3), repeat=n):
        prob = Fraction(1)
        for i in seq:
            prob *= p[i]
        c = [seq.count(i) for i in range(3)]
        for k in range(n + 1):
            exact[k] += prob * c.count(k)
    for k in range(n + 1):
        assert expected_frequency(p, n, k) == exact[k]


def test_lower_bound_inequality():
    rng = random.Random(22)
    for _ in range(300):
        # Two or more species, so that E[f2] > 0.
        w = [rng.randint(1, 9) for _ in range(rng.randint(2, 6))]
        p = [Fraction(x, sum(w)) for x in w]
        n = rng.randint(2, 15)
        e0, e1, e2 = (expected_frequency(p, n, k) for k in range(3))
        bound = Fraction(n - 1, n) * e1 * e1 / (2 * e2)
        assert e0 >= bound
        if len(set(p)) == 1:
            assert e0 == bound
        else:
            assert e0 > bound


def test_simulated_singletons():
    s, n = 30, 100
    w = [1.0 / (i + 1) for i in range(s)]
    p = [x / sum(w) for x in w]
    mean_f1 = sum(n * q * (1 - q) ** (n - 1) for q in p)
    second = mean_f1
    for i in range(s):
        for j in range(s):
            if i != j:
                second += n * (n - 1) * p[i] * p[j] * (1 - p[i] - p[j]) ** (n - 2)
    var_f1 = second - mean_f1 ** 2
    rng = random.Random(23)
    f1s = []
    for _ in range(2000):
        f1s.append(chao1(rng.choices(range(s), weights=p, k=n)).f1)
    m, _ = mean_var(f1s)
    assert check_mean(m, mean_f1, var_f1, len(f1s))

History

Fisher, Corbet and Williams fitted a log-series distribution to the counts of moths and butterflies in 1943, an early parametric approach to the number of unseen species. In 1953 I. J. Good published the frequency formulas that he had worked out with Alan Turing during the war, with the estimate f1/nf_1 / n for the total probability of unseen species. Anne Chao gave the nonparametric lower bound Sobs+f12/(2f2)S_{obs} + f_1^2 / (2 f_2) for the number of classes in 1984, and in 1987 she applied it to capture-recapture data with unequal catchability. The bias-corrected form came later from Chao's group, and Chiu, Wang, Walther and Chao gave the sharper bound iChao1 in 2014. Chao1 became a standard tool in ecology through programs such as EstimateS, and in microbiology through amplicon sequencing.

References

  1. Chao 1984, the lower bound for the number of classes from the numbers of classes seen once and twice
  2. Anne Chao, Estimating the population size for capture-recapture data with unequal catchability, Biometrics 43(4), 1987, pages 783 to 791 (the estimate from the animals caught once and twice, and its variance)
  3. Nicholas J. Gotelli and Robert K. Colwell, Estimating species richness, Chapter 4 of Anne E. Magurran and Brian J. McGill (editors), Biological Diversity, Frontiers in Measurement and Assessment, Oxford University Press, 2011, Chapter 4 (the classic and the bias-corrected forms of Chao1, and their use with rarefaction curves)
  4. Chun-Huo Chiu, Yi-Ting Wang, Bruno A. Walther and Anne Chao, An improved nonparametric lower bound of species richness via a modified Good-Turing frequency formula, Biometrics 70(3), 2014, pages 671 to 682 (the factor (n - 1)/n under sampling of individuals, and the improved bound iChao1 from f3 and f4)

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