Algorithmintro
Lincoln-Petersen estimator
Also called capture-recapture estimator, Lincoln index.
Estimate a closed population size as M C / R, from M marked animals, C caught later and R of those that were marked.
- Time
- Θ((M + C) log M) worstΘ(M + C) average · best
- Space
- Θ(M) extra
- Where
- C = the number of animals in the second sample; M = the number of animals in the first sample
- Model
- Real RAM
- Properties
- deterministicnot exactofflineiterative
- Evidence
- Proof sketchCode in 1 languages
- Origin
- C. G. Johannes Petersen, Frederick C. Lincoln, Douglas G. Chapman, 1896
The Lincoln-Petersen estimator gives the size of a closed animal population from two samples. Catch animals, mark them and release them. Later, catch animals and count the among them that carry a mark. If the marked fraction of the second sample is the same as the marked fraction of the population, then , so . The estimate has no value when , and its expected value is too high when is small. Chapman's form is always defined, and it is exactly unbiased when . This page computes both forms and a variance estimate from the two lists of animal identifiers.
In plain words
You want to know how many fish live in a pond, but you cannot count them all. Catch some fish, put a tag on each, and let them go. Wait until the tagged fish mix with the others. Then catch fish again and look at how many of them have a tag.
If one fish in five of the second catch has a tag, then you guess that one fish in five of the whole pond has a tag. You know how many fish you tagged, so the whole pond holds about five times that number.
This works only if the pond is the same between the two catches, the tags stay on, and a tagged fish is as easy to catch as any other fish. When very few tagged fish come back, the guess is unstable, so a small correction is used.
The problem
Input. Two lists of animal identifiers. The first list holds the distinct animals of the first sample, which were marked and released. The second list holds the distinct animals of the second sample.
Model. The population is closed: the same animals are present at both samples, with no births, deaths or movement in or out. Marks are not lost and are read correctly. The second sample is a simple random sample: every set of animals has the same probability, whatever the marks are. Then the number of marked animals in the second sample has the hypergeometric distribution
Output. The counts , and , the Lincoln-Petersen estimate (no value when ), Chapman's estimate and the variance estimate of .
The algorithm
LINCOLN-PETERSEN(first, second)- 1
marked ← the set of identifiers in first; M ← |marked| - 2
C ← the number of identifiers in second - 3
R ← the number of identifiers in second that are in marked - 4
N_C ← (M + 1)(C + 1) / (R + 1) - 1 - 5
V_C ← (M + 1)(C + 1)(M - R)(C - R) / ((R + 1)^2 (R + 2)) - 6
if R = 0 then N_LP ← no value else N_LP ← M C / R - 7
return (M, C, R, N_LP, N_C, V_C)
Lines L1 to L3 reduce the two lists to the three counts. Line L1 builds a set, so that line L3 tests each animal of the second sample in expected constant time. Line L4 is Chapman's estimate. It equals the Lincoln-Petersen estimate of a population with one extra animal that is in both samples, minus that animal. Line L5 is the variance estimate of that Seber gives. Line L6 is the classic estimate, the value of that makes equal to the observed .
Example
The first sample holds the animals 3, 7, 12, 18, 25 and 31. The second sample holds the animals 2, 7, 9, 18, 22, 25, 30 and 33.
| line | what it computes | value |
|---|---|---|
| L1 | marked = {3, 7, 12, 18, 25, 31} | |
| L2 | the size of the second sample | |
| L3 | 7, 18 and 25 are marked | |
| L4 | ||
| L5 | ||
| L6 |
The two samples hold distinct animals, so in any case. The standard error of is about .
With larger samples, , and give , and , so the standard error is about . A normal interval is about . It is only a rough guide, because has a skewed distribution.
Correctness
Lines L1 to L3 count , and exactly, because both samples are lists of distinct identifiers. The statistical claims hold in the model of "The problem". Line L6 is the moment estimate: , and solves for . For , the maximum likelihood estimate of the integer is , the classic estimate rounded down. Chapman's estimate of line L4 has the exact mean
and exactly when . The full proof is in proofs/correctness.md.
Proof: The counts, the moment and likelihood estimates, and the exact mean of Chapman's estimatefull
Setting. A closed population has animals. The first sample marks a set of distinct animals. The second sample is a set of distinct animals, drawn so that every set of animals has probability , independently of . Let . We use when or .
Claim 1 (the counts). Lines L1 to L3 return , and .
Proof. Line L1 puts the distinct identifiers of the first list into a set, so the set has size . Line L2 counts the distinct identifiers of the second list. Line L3 adds 1 for each element of that is in and 0 for every other element. Each element of is seen once, so the sum is .
Claim 2 (the law of and the moment estimate). and . For , the value of line L6 is the unique solution of .
Proof. A set with is a choice of marked and unmarked animals, and there are such sets, each with probability . For the mean, write . Each animal is in with probability , so by linearity of expectation . The map is strictly decreasing on when , so the equation has one solution. If then , and line L6 returns no value.
Claim 3 (the likelihood estimate). Let and for the integers , the values for which . Then is largest at , and is the largest maximizer.
Proof. For , both and are positive, and the factorials cancel to give
The ratio is if and only if . Expand both sides: , that is, , with equality of the two sides exactly when . So increases strictly while , takes the same value at and when is an integer, and decreases strictly for . Hence the maximizers are the integers in that are , and the largest one is . This value is allowed, because and is an integer.
Claim 4 (the exact mean of Chapman's estimate). Let , the value of line L4. Then
So when , and when .
Proof. Step 1. For every integer , . So
Step 2. By Vandermonde's identity, the sum over all is . The term is . So the sum over is .
Step 3. , because . Subtract 1 to get the formula for .
Step 4. If , then and . If , then , and by Claim 2. Substitute to get .
Claim 5 (the classic estimate has no finite mean when ). If , then , because . On this event line L6 has no value, so is not a finite random variable, and any convention that assigns it the value gives an infinite mean. Chapman's estimate is finite for every , and Claim 4 bounds its bias.
The variance estimate of line L5 is a formula from the literature (Seber 1982). Lines L5 and L7 compute it and return all values, and no claim on its accuracy is proved here.
Claims 1 to 5 together show that the algorithm returns the exact counts, the moment estimate, the value whose floor is the likelihood estimate, and an estimate whose exact mean is given by Claim 4.
Complexity
Time. Line L1 inserts identifiers into a set, and line L3 makes membership tests. With a hash table this is expected time. With a balanced search tree, or with a sorted array and binary search, it is in the worst case. Lines L4 to L6 do a fixed number of arithmetic operations on the counts. When the three counts are given directly, the whole estimate costs .
Space. The set of line L1 holds identifiers, so the extra space is .
Properties
- Moment estimate (theorem). by linearity of expectation: each of the animals of the second sample is marked with probability . Line L6 sets equal to this mean.
- Likelihood (theorem). For , the hypergeometric likelihood of increases while and decreases after that. So is the largest maximizer. When is an integer, has the same likelihood.
- Bias of the classic estimate (theorem). If , then , and has no finite mean. Given its mean is finite, but it can be much larger than : for , and it is (an exact sum over the hypergeometric law). This is the reason for Chapman's form.
- Bias of Chapman's form (theorem). The bias is , which is very small when is not small. For , and , and .
- Variance (known result). of line L5 is the variance estimate in Seber's book, and it is approximately unbiased in the hypergeometric model. For , and , the exact standard deviation of is .
- Not exact. The arithmetic is exact in rational numbers, but the output is an estimate. Its error comes from the sampling and from any failure of the model.
Variants and improvements
- Chapman's form. Line L4. It is the standard choice for one release and one recapture.
- Sampling with replacement. If the second sample can see the same animal more than once (camera traps, or a sample that is returned at once), is binomial. Bailey's form is the corresponding bias-corrected estimate.
- Horvitz-Thompson view. estimates the probability that an animal is in the second sample, and divided by that probability is . This is a Horvitz-Thompson estimator with an estimated inclusion probability.
- Many samples. The Schnabel census combines a sequence of samples into one estimate. Models for open populations, such as Jolly-Seber, also estimate survival and recruitment.
- Unequal catchability. If some animals are easier to catch, is too low. Chao (1987) gives a lower bound for from the numbers of animals caught once and twice in many samples, the same idea as the Chao1 estimator of species richness.
- Interval estimates. The delta method on , the profile likelihood, or a parametric bootstrap from the hypergeometric model give better confidence intervals than the normal interval when is small.
When to use it
Use it for a closed population with two samples close in time, and with marks that stay on. It needs only three counts and no model fit. Design the study so that the expected is at least about 10. With fewer recaptures the estimate is very unstable, and the normal interval is not useful. When there are three or more samples, or when catchability varies between animals or over time, use a model that estimates this variation, for example the Chao (1987) bound or the models in Seber's book. For counts of species instead of animals, use the Chao1 estimator.
Pitfalls
- No recaptures. When , the division at line L6 is not defined. Return no value at line L6 and report Chapman's estimate of line L4, which is in this case and is a rough guess, not a reliable value.
- Counting the same animal twice. Line L3 must count distinct marked animals. If an animal can appear twice in the second list (it was photographed twice), and are both too large. Remove the repeats before line L2, or use a model for sampling with replacement.
- Trap response. Animals that learn to avoid the trap make too small, and too large at line L6. Animals that come back for the bait do the opposite. No line of the algorithm can find this from one pair of samples.
- Mark loss and an open population. Lost marks make too small and too large. Deaths of marked animals between the samples have the same effect. Births and immigration between the samples add unmarked animals, and the estimate then refers to the second sample time.
- Normal intervals. from line L5 can go below , the number of animals seen. Use an interval on the log scale or a profile likelihood interval when is small.
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)
lincoln_petersen_estimator.py 85 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/lincoln-petersen-estimator/. The authors are listed in prov/XD1A1J.jsonl.
"""The Lincoln-Petersen estimator of a closed population size.
Model: a closed population of N animals. The first sample marks M distinct
animals. The second sample is a simple random sample of C distinct animals,
and R of them are marked, so R is hypergeometric with mean M C / N.
All estimates are exact fractions.Fraction values. Cost: Theta(M + C)
expected time with the hash set of line L1, and Theta(M) extra space.
"""
from __future__ import annotations
from dataclasses import dataclass
from fractions import Fraction
from typing import Hashable, Iterable, Optional
@dataclass(frozen=True)
class Estimate:
"""The counts and the estimates of one marking study."""
marked: int
caught: int
recaptured: int
lincoln_petersen: Optional[Fraction]
chapman: Fraction
chapman_variance: Fraction
def _check_counts(m: int, c: int, r: int) -> None:
if m < 0 or c < 0 or r < 0 or r > m or r > c:
raise ValueError("need 0 <= R <= min(M, C)")
def chapman(m: int, c: int, r: int) -> Fraction:
"""Chapman's estimate (M + 1)(C + 1)/(R + 1) - 1."""
_check_counts(m, c, r)
return Fraction((m + 1) * (c + 1), r + 1) - 1
def chapman_variance(m: int, c: int, r: int) -> Fraction:
"""The variance estimate (M + 1)(C + 1)(M - R)(C - R)/((R + 1)^2 (R + 2))."""
_check_counts(m, c, r)
return Fraction((m + 1) * (c + 1) * (m - r) * (c - r), (r + 1) ** 2 * (r + 2))
def lincoln_petersen_counts(m: int, c: int, r: int) -> Optional[Fraction]:
"""The classic estimate M C / R, or None when R = 0."""
_check_counts(m, c, r)
if r == 0:
return None
return Fraction(m * c, r)
def hypergeometric_mle(m: int, c: int, r: int) -> int:
"""The largest integer N that maximizes the hypergeometric likelihood of
R = r, which is floor(M C / R). Requires R >= 1."""
_check_counts(m, c, r)
if r == 0:
raise ValueError("the likelihood has no maximum when R = 0")
return (m * c) // r
def lincoln_petersen(first: Iterable[Hashable], second: Iterable[Hashable]) -> Estimate:
"""Estimate the population size from two lists of animal identifiers.
Precondition: the identifiers in each list are distinct. The first list
holds the marked animals, the second list the animals of the recapture.
"""
first = list(first)
second = list(second)
marked = set(first) # @line L1
if len(marked) != len(first):
raise ValueError("the first sample has a repeated identifier")
if len(set(second)) != len(second):
raise ValueError("the second sample has a repeated identifier")
m = len(marked)
c = len(second) # @line L2
r = sum(1 for animal in second if animal in marked) # @line L3
n_c = chapman(m, c, r) # @line L4
v_c = chapman_variance(m, c, r) # @line L5
n_lp = lincoln_petersen_counts(m, c, r) # @line L6
return Estimate(m, c, r, n_lp, n_c, v_c) # @line L7
test_lincoln_petersen_estimator.py 141 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/lincoln-petersen-estimator/. The authors are listed in prov/XD1A1J.jsonl.
"""Tests of the Lincoln-Petersen and Chapman estimates.
The oracles are exact sums over the hypergeometric law with math.comb and
Fraction, a brute force search of the likelihood, and simulations of the
second sample with random.Random.sample and a fixed seed.
"""
import random
from fractions import Fraction
from math import comb
import pytest
from biostoch import check_mean, hypergeom_pmf, mean_var
from lincoln_petersen_estimator import (
chapman,
chapman_variance,
hypergeometric_mle,
lincoln_petersen,
lincoln_petersen_counts,
)
def law(n, m, c):
"""The exact law of R as a dict r -> Fraction."""
total = comb(n, c)
return {r: Fraction(comb(m, r) * comb(n - m, c - r), total)
for r in range(0, min(m, c) + 1) if comb(n - m, c - r) > 0}
def chapman_moments(n, m, c):
p = law(n, m, c)
mean = sum(q * chapman(m, c, r) for r, q in p.items())
second = sum(q * chapman(m, c, r) ** 2 for r, q in p.items())
return mean, second - mean * mean
def test_check_values():
assert lincoln_petersen_counts(50, 40, 10) == 200
assert chapman(50, 40, 10) == Fraction(2080, 11)
assert abs(float(chapman(50, 40, 10)) - 189.091) < 5e-4
assert chapman_variance(50, 40, 10) == Fraction(209100, 121)
def test_page_example():
est = lincoln_petersen([3, 7, 12, 18, 25, 31], [2, 7, 9, 18, 22, 25, 30, 33])
assert (est.marked, est.caught, est.recaptured) == (6, 8, 3)
assert est.lincoln_petersen == 16
assert est.chapman == Fraction(59, 4)
assert est.chapman_variance == Fraction(189, 16)
assert hypergeometric_mle(6, 8, 3) == 16
def test_no_recaptures():
est = lincoln_petersen(["a", "b"], ["c", "d", "e"])
assert est.recaptured == 0
assert est.lincoln_petersen is None
assert est.chapman == 3 * 4 - 1
with pytest.raises(ValueError):
hypergeometric_mle(2, 3, 0)
def test_all_recaptured_and_empty():
est = lincoln_petersen(range(5), range(5))
assert est.lincoln_petersen == 5 and est.chapman == 5
assert est.chapman_variance == 0
empty = lincoln_petersen([], [])
assert empty.lincoln_petersen is None and empty.chapman == 0
def test_rejects_bad_input():
with pytest.raises(ValueError):
lincoln_petersen([1, 1], [1])
with pytest.raises(ValueError):
lincoln_petersen([1], [2, 2])
with pytest.raises(ValueError):
chapman(3, 4, 5)
def test_counts_against_set_intersection():
rng = random.Random(11)
for _ in range(500):
pop = list(range(rng.randint(1, 40)))
first = rng.sample(pop, rng.randint(0, len(pop)))
second = rng.sample(pop, rng.randint(0, len(pop)))
est = lincoln_petersen(first, second)
r = len(set(first) & set(second))
assert (est.marked, est.caught, est.recaptured) == (len(first), len(second), r)
if r:
assert est.lincoln_petersen * r == len(first) * len(second)
def test_mle_against_brute_force():
rng = random.Random(12)
for _ in range(500):
m = rng.randint(1, 15)
c = rng.randint(1, 15)
r = rng.randint(1, min(m, c))
lo = m + c - r
best_n, best = None, Fraction(-1)
# The search goes well past M C / R; the likelihood falls after its peak.
for n in range(lo, 3 * lo + 2 * m * c // r + 10):
like = Fraction(comb(m, r) * comb(n - m, c - r), comb(n, c))
if like >= best:
best_n, best = n, like
assert hypergeometric_mle(m, c, r) == best_n
def test_chapman_exact_mean_formula():
rng = random.Random(13)
for _ in range(300):
n = rng.randint(1, 30)
m = rng.randint(0, n)
c = rng.randint(0, n)
mean, _ = chapman_moments(n, m, c)
p0 = law(n, m, c).get(0, Fraction(0))
if n <= m + c:
assert mean == n
else:
assert mean == n - (n - m - c) * p0
def test_law_matches_helper():
for r, q in law(60, 20, 15).items():
assert abs(float(q) - hypergeom_pmf(r, 60, 20, 15)) < 1e-12
def test_simulated_chapman_mean():
n, m, c = 200, 50, 40
mean, var = chapman_moments(n, m, c)
rng = random.Random(14)
first = list(range(m))
values = []
for _ in range(10000):
second = rng.sample(range(n), c)
values.append(float(lincoln_petersen(first, second).chapman))
sample_mean, _ = mean_var(values)
assert abs(float(mean) - 199.99976) < 1e-5
assert check_mean(sample_mean, float(mean), float(var), len(values))
History
Petersen marked young plaice in the Limfjord in Denmark in the 1890s, and in 1896 he used the fraction of marked fish in later catches to estimate the stock. Lincoln used the returns of bands from ducks shot by hunters to estimate the number of waterfowl in North America in 1930, and the ratio became known as the Lincoln index. Laplace used the same ratio to estimate the population of France at the end of the eighteenth century, with registered births in place of marks. Chapman worked out the hypergeometric model of the second sample in 1951 and proposed the form with . Seber's book of 1973, with a second edition in 1982, collected the theory of capture-recapture for closed and open populations.
References
- George A. F. Seber, The Estimation of Animal Abundance and Related Parameters, second edition, Griffin, 1982, the chapter on closed populations with a single release of marked animals (the Petersen estimate, Chapman's form, its variance and the assumptions)
- Petersen 1896, the use of marked plaice to estimate the size of the stock
- Lincoln 1930, the ratio of banded birds among the birds shot as an estimate of the total number
- Chapman 1951, the hypergeometric model of the second sample and the modified estimate (M + 1)(C + 1)/(R + 1) - 1
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 XD1A1J Edit this page History Report an error Markdown