Algorithm Search⌘K

Techniquecore

Rarefaction

Also called rarefaction curve.

Compare species richness across samples of unequal size by the expected number of species in a random subsample of m individuals.

Rarefaction compares the number of species in samples of different sizes. A larger sample finds more species, so raw counts of species are not comparable. Rarefaction asks a fair question of each sample: if only mm individuals had been taken, how many species would we expect to see? For a sample of nn individuals with nin_i of species ii, a random subsample of mm individuals misses species ii with probability (n−nim)/(nm)\binom{n - n_i}{m} / \binom{n}{m}. By linearity of expectation, the expected number of species is the sum over species of one minus this probability, with no simulation needed. The rarefaction curve plots this value against mm from 1 to nn. Two samples are compared at the size mm of the smaller one. The same template works for any feature that a set of individuals covers, for example the branches of a phylogenetic tree.

In plain words

You count beetles in two forests. In the first forest you caught 500 beetles of 40 kinds. In the second you caught 100 beetles of 25 kinds. The first forest looks richer, but you also caught five times as many beetles there, and more beetles always means more kinds.

To compare fairly, ask how many kinds you would have seen in the first forest if you had caught only 100 beetles. Imagine picking 100 of your 500 beetles at random, many times over, and counting the kinds each time. Rarefaction works out the average of this count exactly, by adding up, kind by kind, the chance that the kind is among the picked beetles.

If the first forest still shows more kinds at 100 beetles, it is richer at that sample size.

When it applies

  • Samples differ in size, and the question is about the number of species or another count of distinct things found by sampling.
  • The individuals of each sample are a random sample of one community, so that a random subsample is a smaller random sample of the same community.
  • The quantity is a sum over features of a weight times "the feature is seen", so that linearity of expectation reduces the subsample average to one probability per feature. This covers species richness, phylogenetic diversity, the number of genes or k-mers found by a set of reads, and the number of distinct values in a data set.
  • A signal that the technique is needed: a plot of the number of species against the sample size that still rises steeply at the largest sample.

The template

  1. RAREFY(units, FEATURES, WEIGHT, CARRIES, m)
  2. 1n ← the number of units in the full sample
  3. 2for each feature f in FEATURES: k_f ← the number of units u with CARRIES(u, f)
  4. 3q_f ← C(n - k_f, m) / C(n, m) the probability that no unit of the subsample carries f
  5. 4E ← the sum over f of WEIGHT(f) (1 - q_f)
  6. 5V ← the sum over f, g of WEIGHT(f) WEIGHT(g) (q_fg - q_f q_g), with q_fg ← C(n - k_f - k_g + k_fg, m) / C(n, m)
  7. 6return (E, V)

The holes are the units, the features, the weights and the relation CARRIES. For species richness, the units are individuals, each feature is a species with weight 1, and an individual carries its own species, so kf=nik_f = n_i and kfg=0k_{fg} = 0 for two different species. Then line L4 is Hurlbert's formula

E[Sm]=∑i(1−(n−nim)(nm)),\mathbb{E}[S_m] = \sum_{i} \left(1 - \frac{\binom{n - n_i}{m}}{\binom{n}{m}}\right),

and line L5 is the variance of Heck, van Belle and Simberloff, ∑iqi(1−qi)+2∑i<j(qij−qiqj)\sum_i q_i (1 - q_i) + 2 \sum_{i < j} (q_{ij} - q_i q_j) with qij=(n−ni−njm)/(nm)q_{ij} = \binom{n - n_i - n_j}{m} / \binom{n}{m}. Line L3 is the probability that a uniform random set of mm of the nn units avoids the kfk_f units that carry ff. Line L4 follows from linearity of expectation, and line L5 from the variance of a sum of indicators. Compute the binomial ratios as products, q=∏j=0m−1(n−k−j)/(n−j)q = \prod_{j=0}^{m-1} (n - k - j) / (n - j), or in log space. (nm)\binom{n}{m} overflows a float for a few thousand individuals.

A theorem behind the use. If the nn individuals are an independent sample from a community with abundances pip_i, then a uniform random subsample of mm of them is an independent sample of size mm. So the rarefied value of line L4 is an unbiased estimate of ∑i(1−(1−pi)m)\sum_i (1 - (1 - p_i)^m), the expected number of species in a new sample of mm individuals from the community.

The example sample (5,3,2)(5, 3, 2). With n=10n = 10:

mm 1 2 3 4 5 6 7 8 9 10
E[Sm]\mathbb{E}[S_m] 1 1.688889 2.158333 2.476190 2.690476 2.833333 2.925 2.977778 3 3

At m=5m = 5, q=((55),(75),(85))/(105)=(1,21,56)/252q = (\binom{5}{5}, \binom{7}{5}, \binom{8}{5}) / \binom{10}{5} = (1, 21, 56)/252, so E[S5]=3−78/252=113/42=2.690476\mathbb{E}[S_5] = 3 - 78/252 = 113/42 = 2.690476, and line L5 gives Var(S5)=391/1764=0.221655\mathrm{Var}(S_5) = 391/1764 = 0.221655. At m=2m = 2, E[S2]−1=0.688889\mathbb{E}[S_2] - 1 = 0.688889, which is the Gini-Simpson index without replacement of the Simpson diversity index page.

Classic examples

  • Species richness of a sample. The template with species as features, as above. It is the standard way to compare SobsS_{obs} across samples of different sizes, and to show how close a sample is to its asymptote.
  • The Simpson index as a point on the curve. For m=2m = 2, the expected number of species minus 1 is the probability that two different individuals belong to different species, Hurlbert's probability of an interspecific encounter. See the Simpson diversity index.
  • Phylogenetic diversity. Take the branches of a phylogenetic tree as features, each with its length as the weight, and let an individual carry every branch on the path from the root to its species. Then line L4 is the expected phylogenetic diversity of a subsample. For the tree ((A:1,B:1):2,C:3)((A{:}1, B{:}1){:}2, C{:}3) and the counts A=5A = 5, B=3B = 3, C=2C = 2, the full sample has a diversity of 7, and a subsample of 5 individuals has expected diversity 787/126=6.246787/126 = 6.246.
  • Sampling with replacement. If the subsample is drawn with replacement, qf=(1−kf/n)mq_f = (1 - k_f / n)^m. With equal abundances this is the coupon collector problem: the expected number of distinct coupons after mm draws.
  • Sequencing depth. With reads as units and genes, k-mers or positions as features, the curve shows how many features a smaller run would find. This is the logic of saturation curves for sequencing coverage and library complexity.

Variations

  • Sample-based rarefaction. When the data are the presence or absence of species in sampling units (plots, traps, nights), use the units in the template and let a unit carry every species found in it. Gotelli and Colwell (2001) recommend this form when individuals are not independent, for example when they occur in clumps.
  • Extrapolation. Beyond m=nm = n the curve cannot be computed by subsampling. Estimators of the unseen species such as the Chao1 estimator extend the curve to larger mm and give its asymptote.
  • Coverage-based rarefaction. Compare samples at the same estimated coverage, the fraction of the community abundance that belongs to observed species, in place of the same mm. The Good-Turing estimate 1−f1/n1 - f_1 / n is the usual coverage estimate.
  • Rarefaction of other indices. Any index that is a sum of feature indicators works with the template. The Shannon index is not of this form, so its rarefied mean needs simulation or a separate formula.
  • Random subsampling. Drawing one random subsample per sample, often called rarefying, gives a single random value in place of the mean of line L4. It adds noise and discards data.

Pitfalls

  • Overflow in line L3. (nm)\binom{n}{m} for n=5000n = 5000 does not fit in a float. Compute qq as the product of ratios, or with the log-gamma function, not as a ratio of two large binomials.
  • The method of Sanders. Sanders' original method scaled the species counts in proportion and overestimates the expected number of species. Use Hurlbert's exact formula of line L4.
  • Comparing at different sizes. Compare curves at a common mm, not the endpoint of one curve with a point on another. Curves can cross: a sample can be richer at small mm and poorer at large mm, if it has a few common species and many rare ones.
  • The variance is about subsampling. Line L5 is the variance over subsamples of the one observed sample. It is zero at m=nm = n. It does not include the variation between new samples from the community, so it is too small for a test between communities.
  • Rarefying count tables for testing. Throwing away reads to reach a common depth before a statistical test of differences between groups loses power. Rarefaction curves are for the description of richness; for testing, a model of the counts is the better tool.

Code

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)
rarefaction.py 88 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/rarefaction/. The authors are listed in prov/5Z889P.jsonl.
"""Rarefaction: the exact mean and variance of a weighted count of covered
features in a uniform random subsample of m of the n units of a sample.

The general template takes, for each feature, its weight and the set of
units that carry it. Species richness is the special case where the units
are individuals and every individual carries only its own species.

All values are exact fractions.Fraction values. The probability that a
subsample of m units avoids k given units is computed as the product
prod_{j < m} (n - k - j) / (n - j), with no large binomial coefficient.
Cost: Theta(F m) for the mean and Theta(F^2 (m + n)) for the variance, for
F features and n units.
"""

from __future__ import annotations

from fractions import Fraction
from typing import Hashable, List, Sequence, Set, Tuple


def avoid_probability(n: int, k: int, m: int) -> Fraction:
    """C(n - k, m) / C(n, m): the chance that m of n units avoid k of them."""
    if not (0 <= k <= n and 0 <= m <= n):
        raise ValueError("need 0 <= k <= n and 0 <= m <= n")
    q = Fraction(1)
    for j in range(m):
        if n - k - j <= 0:
            return Fraction(0)
        q *= Fraction(n - k - j, n - j)
    return q


def rarefy(n: int, features: Sequence[Tuple[Fraction, Set[Hashable]]], m: int,
           with_variance: bool = True) -> Tuple[Fraction, Fraction]:
    """The mean and variance of the weighted number of covered features.

    n: the number of units in the full sample; features: pairs
    (weight, set of the units that carry the feature); m: the subsample size.
    The variance is Fraction(0) when with_variance is False.
    """
    if not 0 <= m <= n:  # @line L1
        raise ValueError("need 0 <= m <= n")
    carriers: List[Set[Hashable]] = [set(units) for _, units in features]
    weights = [Fraction(w) for w, _ in features]
    k = [len(units) for units in carriers]  # @line L2
    q = [avoid_probability(n, kf, m) for kf in k]  # @line L3
    mean = sum((w * (1 - qf) for w, qf in zip(weights, q)), Fraction(0))  # @line L4
    var = Fraction(0)
    if with_variance:
        for f in range(len(features)):
            for g in range(len(features)):
                union = k[f] + k[g] - len(carriers[f] & carriers[g])
                q_fg = avoid_probability(n, union, m)
                var += weights[f] * weights[g] * (q_fg - q[f] * q[g])  # @line L5
    return mean, var  # @line L6


def species_features(counts: Sequence[int]) -> Tuple[int, List[Tuple[Fraction, Set[int]]]]:
    """The template input for species counts: unit ids 0..n-1, one feature per species."""
    if any(c < 0 for c in counts):
        raise ValueError("counts must be >= 0")
    features = []
    start = 0
    for c in counts:
        if c > 0:
            features.append((Fraction(1), set(range(start, start + c))))
        start += c
    return start, features


def expected_species(counts: Sequence[int], m: int) -> Fraction:
    """Hurlbert's E[S_m] = sum over species of 1 - C(n - n_i, m) / C(n, m)."""
    n = sum(counts)
    return sum((1 - avoid_probability(n, c, m) for c in counts if c > 0), Fraction(0))


def species_variance(counts: Sequence[int], m: int) -> Fraction:
    """The variance of S_m of Heck, van Belle and Simberloff."""
    n, features = species_features(counts)
    return rarefy(n, features, m)[1]


def rarefaction_curve(counts: Sequence[int]) -> List[Fraction]:
    """E[S_m] for m = 1, ..., n."""
    n = sum(counts)
    return [expected_species(counts, m) for m in range(1, n + 1)]
test_rarefaction.py 110 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/rarefaction/. The authors are listed in prov/5Z889P.jsonl.
"""Tests of rarefaction against the page values, enumeration of all
subsamples, the unbiasedness theorem, and a simulation with a fixed seed."""

import itertools
import random
from fractions import Fraction
from math import comb

import pytest

from biostoch import check_mean, mean_var
from rarefaction import (
    avoid_probability,
    expected_species,
    rarefaction_curve,
    rarefy,
    species_features,
    species_variance,
)

PAGE_CURVE = [Fraction(1), Fraction(76, 45), Fraction(259, 120), Fraction(52, 21),
              Fraction(113, 42), Fraction(17, 6), Fraction(117, 40), Fraction(134, 45),
              Fraction(3), Fraction(3)]


def enumerate_subsamples(counts, m):
    """Exact mean and variance of S_m over all C(n, m) subsets."""
    labels = [i for i, c in enumerate(counts) for _ in range(c)]
    total = comb(len(labels), m)
    s1 = s2 = 0
    for sub in itertools.combinations(range(len(labels)), m):
        s = len({labels[u] for u in sub})
        s1 += s
        s2 += s * s
    mean = Fraction(s1, total)
    return mean, Fraction(s2, total) - mean * mean


def test_page_curve_and_variance():
    assert rarefaction_curve([5, 3, 2]) == PAGE_CURVE
    assert abs(float(expected_species([5, 3, 2], 5)) - 2.690476) < 1e-6
    assert species_variance([5, 3, 2], 5) == Fraction(391, 1764)
    assert expected_species([5, 3, 2], 2) - 1 == 1 - Fraction(28, 90)


def test_phylogenetic_example():
    # Tree ((A:1, B:1):2, C:3) with A = 5, B = 3, C = 2 individuals.
    a, b, c = set(range(0, 5)), set(range(5, 8)), set(range(8, 10))
    branches = [(1, a), (1, b), (2, a | b), (3, c)]
    assert rarefy(10, branches, 10)[0] == 7
    assert rarefy(10, branches, 1)[0] == 3
    assert rarefy(10, branches, 5, with_variance=False)[0] == Fraction(787, 126)


def test_edge_cases():
    assert expected_species([4], 2) == 1
    assert expected_species([1, 1, 1], 3) == 3
    assert expected_species([2, 2], 0) == 0
    assert species_variance([5, 3, 2], 10) == 0
    assert avoid_probability(5, 5, 1) == 0
    with pytest.raises(ValueError):
        expected_species([2, 2], 5)


def test_random_against_enumeration():
    rng = random.Random(51)
    for _ in range(500):
        counts = [rng.randint(1, 4) for _ in range(rng.randint(1, 4))]
        n = sum(counts)
        m = rng.randint(0, n)
        mean, var = enumerate_subsamples(counts, m)
        assert expected_species(counts, m) == mean
        if _ < 150:
            assert species_variance(counts, m) == var


def test_concave_curve():
    rng = random.Random(52)
    for _ in range(100):
        counts = [rng.randint(1, 9) for _ in range(rng.randint(1, 6))]
        curve = [Fraction(0)] + rarefaction_curve(counts)
        steps = [curve[i + 1] - curve[i] for i in range(len(curve) - 1)]
        assert all(steps[i + 1] <= steps[i] for i in range(len(steps) - 1))


def test_unbiased_for_the_community():
    p = [Fraction(1, 2), Fraction(3, 10), Fraction(1, 5)]
    for n, m in ((4, 2), (5, 3), (6, 5)):
        mean = Fraction(0)
        for seq in itertools.product(range(3), repeat=n):
            prob = Fraction(1)
            for i in seq:
                prob *= p[i]
            mean += prob * expected_species([seq.count(i) for i in range(3)], m)
        assert mean == sum(1 - (1 - q) ** m for q in p)
    assert abs(float(sum(1 - (1 - q) ** 5 for q in p)) - 2.473) < 1e-9


def test_simulated_subsamples():
    counts = [20, 10, 5, 3, 1, 1]
    m = 8
    labels = [i for i, c in enumerate(counts) for _ in range(c)]
    rng = random.Random(53)
    values = [len(set(rng.sample(labels, m))) for _ in range(10000)]
    sample_mean, _ = mean_var(values)
    n, features = species_features(counts)
    mean, var = rarefy(n, features, m)
    assert check_mean(sample_mean, float(mean), float(var), len(values))

Exercises

  1. Show that E[S2]−1=1−∑ini(ni−1)/(n(n−1))\mathbb{E}[S_2] - 1 = 1 - \sum_i n_i (n_i - 1) / (n (n - 1)) for every sample.
  2. Show that the curve is concave: with qi(m)=(n−nim)/(nm)q_i(m) = \binom{n - n_i}{m} / \binom{n}{m}, prove that qi(m)−qi(m+1)=qi(m) ni/(n−m)q_i(m) - q_i(m + 1) = q_i(m)\, n_i / (n - m), and that this difference does not increase with mm when ni≥1n_i \ge 1.
  3. Compute E[S3]\mathbb{E}[S_3] for the sample (5,3,2)(5, 3, 2) and check that it is 259/120259/120.
  4. For a community with abundances (0.5,0.3,0.2)(0.5, 0.3, 0.2), compute the expected number of species in a sample of mm individuals drawn with replacement for m=2m = 2 and m=5m = 5 (the answers are 1.621.62 and 2.4732.473), and compare them with the rarefied values of the sample (5,3,2)(5, 3, 2).
  5. Prove the theorem above: a uniform random mm-subset of an independent sample of nn individuals is an independent sample of mm individuals, so the rarefied value is unbiased for ∑i(1−(1−pi)m)\sum_i (1 - (1 - p_i)^m).

References

  1. Howard L. Sanders, Marine benthic diversity, a comparative study, The American Naturalist 102(925), 1968, pages 243 to 282 (the rarefaction method for comparing samples of different sizes)
  2. Stuart H. Hurlbert, The nonconcept of species diversity, a critique and alternative parameters, Ecology 52(4), 1971, pages 577 to 586 (the exact expected number of species in a subsample, and the overestimate in Sanders' method)
  3. Kenneth L. Heck Jr., Gerald van Belle and Daniel Simberloff, Explicit calculation of the rarefaction diversity measurement and the determination of sufficient sample size, Ecology 56(6), 1975, pages 1459 to 1461 (the variance of the rarefied number of species)
  4. Nicholas J. Gotelli and Robert K. Colwell, Quantifying biodiversity, procedures and pitfalls in the measurement and comparison of species richness, Ecology Letters 4(4), 2001, pages 379 to 391 (individual-based and sample-based rarefaction, and accumulation curves)

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 proofH0 no proof
  • add a proof in proofs/ (06.5)
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)
WritingW3 standard
  • five exercises