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
- Model
- Real RAM
- Properties
- deterministicnot exactonlineiterative
- Evidence
- Proof sketchCode in 1 languages
- Origin
- Anne Chao, 1984
The Chao1 estimator gives a lower estimate of the number of species in a community from one sample of individuals. Rare species are the ones that a sample misses, and the sample shows how many rare species there are: species have one individual in the sample (singletons) and species have two (doubletons). Chao's estimate is . When is large compared with , many species are still unseen. When , 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 individuals, given as the list of their species labels.
Model. The community has species with relative abundances that sum to 1. The individuals are drawn independently, and each one belongs to species with probability (multinomial sampling). Let be the number of individuals of species in the sample, and the number of species with . Then , and , the number of unseen species, is what the estimate must supply.
Output. , , , , the classic estimate (no value when ), the bias-corrected estimate , and Chao's variance estimate of the classic form.
The algorithm
CHAO1(sample)- 1
count ← an empty map; for each label x in sample: count[x] ← count[x] + 1 - 2
n ← the length of sample; S_obs ← the number of keys of count - 3
f1 ← the number of species with count 1; f2 ← the number of species with count 2 - 4
S_bc ← S_obs + f1 (f1 - 1) / (2 (f2 + 1)) - 5
if f2 = 0 then S_classic ← no value; V ← no value - 6
else q ← f1 / f2; S_classic ← S_obs + q f1 / 2; V ← f2 (q^4 / 4 + q^3 + q^2 / 2) - 7
return (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 , and Chao's (1987) variance estimate. Line L5 skips both when there are no doubletons.
Example
A sample of 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 | , |
| L3 | singletons E, F, G, H; doubletons C, D | , |
| L4 | ||
| L6 | , , | , |
The form with the factor (see "Variants and improvements") gives . For a larger sample with , and , the classic form gives , the bias-corrected form gives , and the variance estimate is .
Correctness
Lines L1 to L3 compute , , and exactly. The statistical claim is a theorem about expected values. For multinomial sampling of individuals,
with equality if and only if all species have the same abundance. Under Poisson sampling the same bound holds without the factor . The proof is the Cauchy-Schwarz inequality on . Line L6 puts the observed and in place of their expected values. So the estimate targets a lower bound of , 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 species with abundances , all in , with . A sample of individuals is drawn by multinomial sampling: each individual is of species with probability , independently of the others. Let be the number of individuals of species , and .
Claim 1 (the counts). Lines L1 to L3 return , , and .
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 for species . Labels that do not occur are not keys. Line L2 returns the length of the sample, , and the number of keys, . Line L3 counts the keys with value 1 and with value 2, which are and .
Claim 2 (the expected frequency counts). for , and .
Proof. has the binomial law with parameters and , so . Write and use linearity of expectation. Every species has either or , so for every sample, and the second statement follows by taking expectations.
Claim 3 (the lower bound). , and
with equality if and only if .
Proof. Step 1. Each term of in Claim 2 is positive, because and . So .
Step 2. Let and . Both are positive. Then , and . By Claim 2,
Step 3. The Cauchy-Schwarz inequality gives , so
Multiply by to get the claim.
Step 4. Equality holds in Cauchy-Schwarz if and only if the vectors and are proportional. Since , this means that is the same for all . The map is strictly increasing on , so this holds if and only if all are equal.
Claim 4 (Poisson sampling). If instead the are independent with Poisson laws of means , then , with equality if and only if all are equal.
Proof. Now . Take and . Then , and , and Cauchy-Schwarz gives the bound. Equality holds if and only if is constant.
Claim 5 (what lines L4 to L6 compute). Line L6 returns when , and Chao's variance formula with . Line L4 returns for every sample. Both are . If and , the value of line L4 is less than the value of line L6.
Proof. Line L6 computes , so the first statement holds, and the variance is the formula as written. Both corrections are products and quotients of numbers , so both estimates are . If and , then and , so .
Conclusion. By Claims 2 and 3, for every community. Line L6 evaluates the same expression with the observed , and in place of their expected values (and without the factor , 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 , and this lower bound is equal to 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.
Complexity
Time. Line L1 does map updates. With a hash map this is expected time, and with a balanced search tree it is in the worst case, for keys. Line L3 reads the counts once, in time. Lines L4 to L6 do a fixed number of arithmetic operations.
Space. The map holds keys and their counts, so the extra space is . 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 for every community, by the inequality above. It is equal to only when all abundances are equal. A community with many very rare species can have far more species than any estimate from and shows.
- Never below the observed count (theorem). Both forms are at least , and both are equal to when . The bias-corrected form is smaller than the classic form when and , because and .
- When . The classic form has no value. The bias-corrected form gives , which is a large correction. A sample with no doubletons is too small for a reliable estimate.
- Behavior in a simulation (measurement). Take species with proportional to and . The exact values are and a lower bound of from the inequality. In 2000 samples drawn with Python's
random.Random(5).choices, the bias-corrected form had mean , the classic form had mean over the 1999 samples with , and had mean . - Variance (known result). 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 , so that the lower end is not below .
Variants and improvements
- The factor . Under multinomial sampling of individuals the bound is . The factor matters only for small .
- Bias-corrected form. Line L4 is the form in Gotelli and Colwell (2011), and it has a value when . With the factor it is .
- iChao1. Chiu, Wang, Walther and Chao (2014) add a term from and that makes the bound sharper.
- Chao2. For incidence data (the presence or absence of each species in each of several sampling units), replace and 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 and 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 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 , , , 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 . When , 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 at line L3, and the estimate grows by about 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 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.
# 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 for the total probability of unseen species. Anne Chao gave the nonparametric lower bound 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
- Chao 1984, the lower bound for the number of classes from the numbers of classes seen once and twice
- 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)
- 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)
- 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.
| 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 A0Z4WE Edit this page History Report an error Markdown