Algorithm Search⌘K

Definitionintro

Simpson diversity index

Also called Simpson's index.

The probability that two individuals drawn at random with replacement from a community belong to the same species, or one minus it.

The Simpson index of a community is λ=∑ipi2\lambda = \sum_i p_i^2, the probability that two individuals drawn at random with replacement belong to the same species. It is a measure of concentration: it is 1 when one species makes up the whole community and small when many species share it evenly. Three forms are in use, and papers often call each of them "Simpson's index": the concentration λ\lambda itself, the Gini-Simpson index 1−λ1 - \lambda (the probability that the two individuals differ), and the inverse Simpson index 1/λ1 / \lambda (the effective number of species of order 2). From a sample, Simpson's form without replacement, ∑ni(ni−1)/(n(n−1))\sum n_i (n_i - 1) / (n (n - 1)), is an unbiased estimate of λ\lambda. Always say which form you report.

Definition

Let a community have SS species with relative abundances p1,…,pS≥0p_1, \ldots, p_S \ge 0 and ∑ipi=1\sum_i p_i = 1. The Simpson concentration is

λ=∑i=1Spi2.\lambda = \sum_{i=1}^{S} p_i^2.

If two individuals are drawn independently, each of species ii with probability pip_i (that is, with replacement), then λ\lambda is the probability that they are of the same species. The Gini-Simpson index is 1−λ1 - \lambda, and the inverse Simpson index is D2=1/λD_2 = 1 / \lambda.

For a sample of n≥2n \ge 2 individuals with nin_i of species ii, the plug-in value is λ^=∑i(ni/n)2\hat\lambda = \sum_i (n_i / n)^2, and the form without replacement is

λ^u=∑ini(ni−1)n(n−1),\hat\lambda_u = \sum_i \frac{n_i (n_i - 1)}{n (n - 1)},

the probability that two different individuals drawn from the sample are of the same species.

Properties that follow from the definition (theorems):

  • 1/S≤λ≤11 / S \le \lambda \le 1 for SS species with pi>0p_i > 0. λ=1/S\lambda = 1 / S if and only if all pi=1/Sp_i = 1/S, and λ=1\lambda = 1 if and only if S=1S = 1. So 1≤D2≤S1 \le D_2 \le S.
  • Unbiasedness. Under multinomial sampling of nn individuals, nin_i is binomial with E[ni(ni−1)]=n(n−1)pi2\mathbb{E}[n_i (n_i - 1)] = n (n - 1) p_i^2. By linearity of expectation, E[λ^u]=λ\mathbb{E}[\hat\lambda_u] = \lambda. The plug-in value has E[λ^]=λ+(1−λ)/n\mathbb{E}[\hat\lambda] = \lambda + (1 - \lambda)/n, so it is too high.
  • 1/λ^u1 / \hat\lambda_u is not an unbiased estimate of 1/λ1/\lambda, because the reciprocal is not linear.
  • Order 2 of Hill's family. D2D_2 is the Hill number (∑piq)1/(1−q)(\sum p_i^q)^{1/(1 - q)} for q=2q = 2. It counts common species more than the Shannon index does, which is the order 1 member eHe^H. So D2≤eH≤SD_2 \le e^H \le S.

Examples and non-examples

  • The abundances (5,3,2)(5, 3, 2) give p=(0.5,0.3,0.2)p = (0.5, 0.3, 0.2) and λ=0.25+0.09+0.04=0.38\lambda = 0.25 + 0.09 + 0.04 = 0.38, so the Gini-Simpson index is 0.620.62 and the inverse Simpson index is 1/0.38=2.6315791 / 0.38 = 2.631579. This is less than eH=2.800094e^H = 2.800094 for the same community.
  • As a sample of n=10n = 10, the form without replacement is λ^u=(20+6+2)/90=28/90=0.311111\hat\lambda_u = (20 + 6 + 2) / 90 = 28/90 = 0.311111, so 1−λ^u=0.6888891 - \hat\lambda_u = 0.688889 and 1/λ^u=3.2142861 / \hat\lambda_u = 3.214286.
  • The counts (10,6,4)(10, 6, 4) have the same proportions and the same λ=0.38\lambda = 0.38, but λ^u=(90+30+12)/380=0.347368\hat\lambda_u = (90 + 30 + 12) / 380 = 0.347368. The two forms get closer as nn grows.
  • Four species with equal abundance give λ=0.25\lambda = 0.25 and D2=4D_2 = 4. The counts (97,1,1,1)(97, 1, 1, 1) give λ=0.9412\lambda = 0.9412 and D2=1.062473D_2 = 1.062473: one species dominates.
  • Non-example: a sample of singletons. Five individuals of five species give λ^u=0\hat\lambda_u = 0, and 1/λ^u1 / \hat\lambda_u has no value. The sample shows only that no two individuals share a species.
  • Non-example: the index of a large and a small sample. The plug-in λ^\hat\lambda of a small sample is too high by (1−λ)/n(1 - \lambda)/n, so a small sample looks less diverse. Use λ^u\hat\lambda_u to compare samples of different sizes.
  • Non-example: "higher is more diverse". For λ\lambda a higher value means less diversity, and for 1−λ1 - \lambda and 1/λ1 / \lambda it means more. A value without its form is ambiguous.

The pseudocode below computes all forms from a list of counts.

  1. SIMPSON(counts)
  2. 1n ← the sum of the counts
  3. 2λ ← the sum of (c / n)^2 over the counts c
  4. 3λ_u ← the sum of c (c - 1) over the counts, divided by n (n - 1), if n ≥ 2
  5. 4return (λ, 1 - λ, 1 / λ, λ_u, 1 - λ_u)
  • Gini impurity of a node of a decision tree is the Gini-Simpson index of its class proportions.
  • The Shannon diversity index is the order 1 member of Hill's family, and it gives rare species more weight. Shannon entropy and the Rényi entropy of order 2, −ln⁡λ-\ln \lambda, are the information measures behind the two indices.
  • Hurlbert's probability of an interspecific encounter, 1−λ^u1 - \hat\lambda_u, is also the expected number of species in a random subsample of 2 individuals, minus 1. So it is the first nontrivial point of the rarefaction curve: for the sample (5,3,2)(5, 3, 2), E[S2]−1=0.688889\mathbb{E}[S_2] - 1 = 0.688889.
  • The Chao1 estimator estimates the number of species, the diversity of order 0, which depends most on the rare species.

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.

simpson_diversity_index.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/simpson-diversity-index/. The authors are listed in prov/2B5Z97.jsonl.
"""The forms of the Simpson index of a list of integer species counts.

Input: counts n_i >= 0 with a positive sum n. Output, as exact fractions:
the concentration lambda = sum (n_i / n)^2, the Gini-Simpson index
1 - lambda, the inverse Simpson index 1 / lambda, and the form without
replacement lambda_u = sum n_i (n_i - 1) / (n (n - 1)) with 1 - lambda_u
(both None when n < 2). Cost: Theta(k) arithmetic operations for k counts.
"""

from __future__ import annotations

from dataclasses import dataclass
from fractions import Fraction
from typing import Optional, Sequence


@dataclass(frozen=True)
class Simpson:
    concentration: Fraction
    gini_simpson: Fraction
    inverse: Fraction
    unbiased: Optional[Fraction]
    gini_simpson_unbiased: Optional[Fraction]


def simpson(counts: Sequence[int]) -> Simpson:
    """Compute the Simpson forms from the counts."""
    if any(c < 0 for c in counts):
        raise ValueError("counts must be >= 0")
    n = sum(counts)  # @line L1
    if n <= 0:
        raise ValueError("counts must have a positive sum")
    lam = sum((Fraction(c, n) ** 2 for c in counts), Fraction(0))  # @line L2
    if n >= 2:
        lam_u = Fraction(sum(c * (c - 1) for c in counts), n * (n - 1))  # @line L3
        gs_u = 1 - lam_u
    else:
        lam_u = None
        gs_u = None
    return Simpson(lam, 1 - lam, 1 / lam, lam_u, gs_u)  # @line L4
test_simpson_diversity_index.py 78 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/simpson-diversity-index/. The authors are listed in prov/2B5Z97.jsonl.
"""Tests of the Simpson forms against the page values, a count of pairs of
individuals, and the exact mean of both estimates by enumeration."""

import itertools
import random
from fractions import Fraction

import pytest

from simpson_diversity_index import simpson


def pair_oracle(counts):
    """Count ordered pairs of individuals of the same species directly."""
    labels = [i for i, c in enumerate(counts) for _ in range(c)]
    n = len(labels)
    same_with = sum(1 for a in labels for b in labels if a == b)
    same_without = sum(1 for x in range(n) for y in range(n) if x != y and labels[x] == labels[y])
    return Fraction(same_with, n * n), (Fraction(same_without, n * (n - 1)) if n > 1 else None)


def test_page_values():
    r = simpson([5, 3, 2])
    assert r.concentration == Fraction(38, 100)
    assert r.gini_simpson == Fraction(62, 100)
    assert abs(float(r.inverse) - 2.631579) < 1e-6
    assert r.unbiased == Fraction(28, 90)
    assert abs(float(r.gini_simpson_unbiased) - 0.688889) < 1e-6
    assert abs(float(1 / r.unbiased) - 3.214286) < 1e-6
    assert abs(float(simpson([10, 6, 4]).unbiased) - 0.347368) < 1e-6
    assert simpson([25] * 4).inverse == 4
    assert abs(float(simpson([97, 1, 1, 1]).inverse) - 1.062473) < 1e-6


def test_edge_cases():
    one = simpson([1])
    assert one.concentration == 1 and one.unbiased is None
    assert simpson([1] * 5).unbiased == 0
    assert simpson([0, 6]).concentration == 1
    with pytest.raises(ValueError):
        simpson([0])
    with pytest.raises(ValueError):
        simpson([2, -1])


def test_random_against_pairs():
    rng = random.Random(41)
    for _ in range(500):
        counts = [rng.randint(0, 6) for _ in range(rng.randint(1, 6))]
        if sum(counts) == 0:
            counts[0] = 1
        r = simpson(counts)
        lam, lam_u = pair_oracle(counts)
        assert r.concentration == lam and r.unbiased == lam_u
        s = sum(1 for c in counts if c > 0)
        assert Fraction(1, s) <= r.concentration <= 1


def test_exact_means_by_enumeration():
    rng = random.Random(42)
    for _ in range(20):
        w = [rng.randint(1, 5) for _ in range(rng.randint(2, 3))]
        p = [Fraction(x, sum(w)) for x in w]
        n = rng.randint(2, 6)
        lam = sum(q * q for q in p)
        mean_u = Fraction(0)
        mean_plug = Fraction(0)
        for seq in itertools.product(range(len(p)), repeat=n):
            prob = Fraction(1)
            for i in seq:
                prob *= p[i]
            r = simpson([seq.count(i) for i in range(len(p))])
            mean_u += prob * r.unbiased
            mean_plug += prob * r.concentration
        assert mean_u == lam
        assert mean_plug == lam + (1 - lam) / n

References

  1. E. H. Simpson, Measurement of diversity, Nature 163(4148), 1949, page 688 (the concentration as the probability that two individuals belong to the same group, and its estimate from a sample)
  2. Stuart H. Hurlbert, The nonconcept of species diversity, a critique and alternative parameters, Ecology 52(4), 1971, pages 577 to 586 (the probability of an interspecific encounter, and the expected number of species in a subsample)
  3. M. O. Hill, Diversity and evenness, a unifying notation and its consequences, Ecology 54(2), 1973, pages 427 to 432 (the inverse of the Simpson concentration as the diversity number of order 2)
  4. Anne E. Magurran, Measuring Biological Diversity, Blackwell, 2004, the chapter on diversity indices (Simpson's index, its forms and its sampling properties)

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 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)
WritingW4 complete
  • a review of the text: no review record reviews/2B5Z97/text.yaml