Algorithm Search⌘K

Algorithmcore

Fisher's exact test

Also called Fisher-Irwin test.

Tests independence in a 2 x 2 table exactly, from the hypergeometric distribution of one cell given the margins. It stays valid for small counts.

Time
Θ(n) worstΘ(m) best
Space
Θ(m) extra
Where
m = the number of tables with the observed margins (at most n + 1); n = the total count
Properties
deterministicexactofflineiterative
Origin
Ronald A. Fisher, J. O. Irwin, Frank Yates, 1935

Fisher's exact test checks whether two binary variables are independent, or whether two groups have the same success probability, from the four counts of a 2×22 \times 2 table. It conditions on both row totals and both column totals. Given these margins, the whole table is fixed by its top-left cell, and under the null hypothesis that cell has a hypergeometric law that contains no unknown parameter. The p-value is a tail sum of that law, so the test is valid for every sample size, however small the counts. The code computes the hypergeometric weights as exact integers, so the p-values have no rounding error before the final division.

In plain words

A lady says she can tell whether milk or tea went into the cup first. You give her 8 cups, 4 of each kind, and she must pick the 4 with milk first. If she is only guessing, every choice of 4 cups out of 8 is equally likely, and there are 70 such choices. Only one of them is fully correct. So if she gets all 4 right, the chance of doing that well by luck is 1/701/70. Fisher's test does this counting for any 2×22 \times 2 table: keep the row and column totals fixed, count how many ways each table can arise, and add up the share of tables that are at least as extreme as the one you saw.

The problem

Model. A 2×22 \times 2 table of counts

column 1 column 2 total
row 1 aa bb r1r_1
row 2 cc dd r2r_2
total c1c_1 c2c_2 nn

arises from two independent binomial rows (r1r_1 and r2r_2 fixed), from one multinomial sample (nn fixed), or from a design with both margins fixed.

Hypotheses. H0H_0: the rows have the same probability of column 1 (equivalently, the two variables are independent, or the odds ratio ψ=p1/(1−p1)p2/(1−p2)\psi = \frac{p_1/(1 - p_1)}{p_2/(1 - p_2)} equals 1). Alternatives: ψ>1\psi > 1 ("greater", large aa), ψ<1\psi < 1 ("less") or ψ≠1\psi \neq 1 (two-sided).

Statistic. The top-left count aa.

Null distribution. Conditional and exact. Given all margins, AA takes the values kk from klo=max⁡(0,c1−r2)k_{lo} = \max(0, c_1 - r_2) to khi=min⁡(r1,c1)k_{hi} = \min(r_1, c_1) with

P(A=k∣margins)=w(k)(nc1),w(k)=(r1k)(r2c1−k),P(A = k \mid \text{margins}) = \frac{w(k)}{\binom{n}{c_1}}, \qquad w(k) = \binom{r_1}{k}\binom{r_2}{c_1 - k},

the hypergeometric law. The common success probability cancels, as the correctness proof shows.

Rejection rule and size. Reject when p≤αp \le \alpha. The conditional size is at most α\alpha for every set of margins, so the unconditional size is also at most α\alpha. Because the conditional law is discrete, the size is usually well below α\alpha; see Properties.

P-values. Phi=P(A≥a)P_{hi} = P(A \ge a) for "greater", Plo=P(A≤a)P_{lo} = P(A \le a) for "less", and for the two-sided test the minimum-likelihood rule pml=∑k:w(k)≤w(a)w(k)/(nc1)p_{ml} = \sum_{k : w(k) \le w(a)} w(k)/\binom{n}{c_1}, the total probability of the tables that are at most as likely as the observed one. This is the rule of R's fisher.test and of the code. Doubling the smaller tail is the other common rule; it can differ.

Sensitivity and power. Under the alternative the conditional law is w(k)ψk/∑jw(j)ψjw(k)\psi^k/\sum_j w(j)\psi^j, which depends only on the odds ratio. The one-sided test is the uniformly most powerful conditional test, but the conditioning costs power against the unconditional alternatives; see Properties.

The algorithm

  1. FISHER-EXACT(a, b, c, d, alternative)
  2. 1r1 ← a + b; r2 ← c + d; c1 ← a + c; lo ← max(0, c1 - r2); hi ← min(r1, c1)
  3. 2w[lo] ← C(r1, lo) · C(r2, c1 - lo)
  4. 3for k ← lo to hi - 1
  5. 4w[k + 1] ← w[k] · (r1 - k)(c1 - k) / ((k + 1)(r2 - c1 + k + 1)) ▷ exact integer division
  6. 5N ← w[lo] + ... + w[hi] ▷ equals C(n, c1)
  7. 6if alternative = greater then return (w[a] + ... + w[hi]) / N
  8. 7if alternative = less then return (w[lo] + ... + w[a]) / N
  9. 8return (sum of w[k] over all k with w[k] ≤ w[a]) / N

All values in lines L2 to L8 are exact integers. Line L4 uses the ratio of consecutive terms, so the loop needs one multiplication and one division per table instead of two binomial coefficients. The comparison in line L8 is exact, so two tables with equal probability are always treated as tied; floating-point code needs a tolerance here, as the binomial test does. The code returns the Fraction on request, or the correctly rounded float of it.

Example

The lady tasting tea. Table (4004)\begin{pmatrix} 4 & 0 \\ 0 & 4 \end{pmatrix}: rows are the true kind of cup, columns are her answer. The margins are all 4, so kk runs from 0 to 4 with weights w=(1,16,36,16,1)w = (1, 16, 36, 16, 1), total 70=(84)70 = \binom{8}{4}. Line L4 gives them in turn: w(1)=1⋅4⋅4/(1⋅1)=16w(1) = 1 \cdot 4 \cdot 4/(1 \cdot 1) = 16, w(2)=16⋅3⋅3/(2⋅2)=36w(2) = 16 \cdot 3 \cdot 3/(2 \cdot 2) = 36, and so on. The one-sided p-value is P(A≥4)=1/70=0.0143P(A \ge 4) = 1/70 = 0.0143. The two-sided value is 2/70=1/35=0.02862/70 = 1/35 = 0.0286. With 3 of 4 right, the one-sided value would be 17/70=0.24317/70 = 0.243: the design cannot reach significance unless she is perfect.

Convictions of twins (Fisher 1935). Of 13 monozygotic twins of convicted criminals, 10 had a twin who was also convicted; of 17 dizygotic twins, 2 had. The table is (103215)\begin{pmatrix} 10 & 3 \\ 2 & 15 \end{pmatrix} with r1=13r_1 = 13, r2=17r_2 = 17, c1=12c_1 = 12, n=30n = 30. The weights for k=0,…,12k = 0, \ldots, 12 are

6188, 160888, 1516944, 6952660, 17381650, 25029576, 21237216, 10618608, 3063060, 486200, 38896, 1326, 13,

with total (3012)=86493225\binom{30}{12} = 86493225. So Phi=(38896+1326+13)/86493225=619/1330665=0.000465P_{hi} = (38896 + 1326 + 13)/86493225 = 619/1330665 = 0.000465, which is about 1/21501/2150. The two-sided minimum-likelihood value adds the tables with weight at most 38896, which are k=0k = 0 (6188) on the other side, so pml=46423/86493225=3571/6653325=0.000537p_{ml} = 46423/86493225 = 3571/6653325 = 0.000537. Doubling would give 0.0009300.000930.

A one-sided result that is not two-sided. For (7238)\begin{pmatrix} 7 & 2 \\ 3 & 8 \end{pmatrix}, Phi=293/8398=0.0349P_{hi} = 293/8398 = 0.0349 and pml=293/4199=0.0698p_{ml} = 293/4199 = 0.0698. At α=0.05\alpha = 0.05 only the one-sided test rejects; choose the alternative before seeing the data.

Against the chi-squared test. For (125716)\begin{pmatrix} 12 & 5 \\ 7 & 16 \end{pmatrix}, n=40n = 40, Fisher's two-sided p-value is 0.023840.02384 and the one-sided one is 0.013570.01357. The chi-squared test of independence gives X2=6.3199X^2 = 6.3199 and p=0.01194p = 0.01194; with Yates's continuity correction, X2=4.8123X^2 = 4.8123 and p=0.02826p = 0.02826, closer to Fisher's value.

All the fractions above are computed exactly by the code, and the tests check them.

Correctness

The full proof is in proofs/correctness.md. In each sampling model, the joint law of the table under H0H_0 is w(k)w(k) times a factor that depends only on the margins, so conditioning on the margins leaves w(k)/(nc1)w(k)/\binom{n}{c_1} (Vandermonde's identity gives the total). Line L4 is exact because w(k)(r1−k)(c1−k)=w(k+1)(k+1)(r2−c1+k+1)w(k)(r_1 - k)(c_1 - k) = w(k + 1)(k + 1)(r_2 - c_1 + k + 1) is an identity of integers. Each p-value is a tail P(T(A)≥T(a))P(T(A) \ge T(a)) of a finite law, so the lemma on the binomial test page gives conditional validity, and averaging over the margins gives unconditional validity.

Proof: Given the margins the top-left cell is hypergeometric, the recurrence gives its exact weights, and each p-value is validfull

Write the table as (abcd)\begin{pmatrix} a & b \\ c & d \end{pmatrix} with row totals r1=a+br_1 = a + b, r2=c+dr_2 = c + d, first column total c1=a+cc_1 = a + c and n=r1+r2n = r_1 + r_2. Let klo=max⁡(0,c1−r2)k_{lo} = \max(0, c_1 - r_2) and khi=min⁡(r1,c1)k_{hi} = \min(r_1, c_1) be the smallest and largest values of the top-left cell that the margins allow, and w(k)=(r1k)(r2c1−k)w(k) = \binom{r_1}{k}\binom{r_2}{c_1 - k} for klo≤k≤khik_{lo} \le k \le k_{hi}.

Claim 1 (the null law given the margins). In each of these three sampling models, under the null hypothesis, the conditional law of the top-left cell AA given all four margins is

P(A=k∣margins)=w(k)(nc1),klo≤k≤khi,P(A = k \mid \text{margins}) = \frac{w(k)}{\binom{n}{c_1}}, \qquad k_{lo} \le k \le k_{hi},

and it does not depend on any unknown parameter.

  • Two independent binomial rows (fixed r1r_1, r2r_2): A∼Binomial(r1,p1)A \sim \text{Binomial}(r_1, p_1) and C∼Binomial(r2,p2)C \sim \text{Binomial}(r_2, p_2), independent, with H0:p1=p2=pH_0: p_1 = p_2 = p.
  • One multinomial sample (fixed nn): the four cells are multinomial with probabilities πij\pi_{ij}, and H0H_0 is independence, πij=πi⋅π⋅j\pi_{ij} = \pi_{i\cdot}\pi_{\cdot j}.
  • Both margins fixed by design, as in the tea experiment, with the c1c_1 "first column" labels assigned to the nn units at random: every set of c1c_1 units is equally likely.

Proof. Binomial rows: for kk in range,

P(A=k,C=c1−k)=(r1k)(r2c1−k)pc1(1−p)n−c1=w(k) pc1(1−p)n−c1.P(A = k, C = c_1 - k) = \binom{r_1}{k}\binom{r_2}{c_1 - k} p^{c_1}(1 - p)^{n - c_1} = w(k)\, p^{c_1}(1 - p)^{n - c_1}.

Summing over kk and using Vandermonde's identity ∑k(r1k)(r2c1−k)=(nc1)\sum_k \binom{r_1}{k}\binom{r_2}{c_1 - k} = \binom{n}{c_1} gives P(A+C=c1)=(nc1)pc1(1−p)n−c1P(A + C = c_1) = \binom{n}{c_1} p^{c_1}(1 - p)^{n - c_1}. Dividing, the factor with pp cancels. Multinomial: given the row totals, the two rows are independent binomials with success probabilities π11/π1⋅\pi_{11}/\pi_{1\cdot} and π21/π2⋅\pi_{21}/\pi_{2\cdot}, which under independence both equal π⋅1\pi_{\cdot 1}; so the first case applies. Fixed margins: of the (nc1)\binom{n}{c_1} equally likely sets, exactly w(k)w(k) put kk of the chosen units in row 1 and c1−kc_1 - k in row 2. □\square

Claim 2 (lines L2 to L5 compute the weights exactly). Line L2 sets w(klo)w(k_{lo}) by its definition. For klo≤k<khik_{lo} \le k < k_{hi},

w(k+1)w(k)=(r1k+1)(r1k)⋅(r2c1−k−1)(r2c1−k)=r1−kk+1⋅c1−kr2−c1+k+1.\frac{w(k + 1)}{w(k)} = \frac{\binom{r_1}{k + 1}}{\binom{r_1}{k}} \cdot \frac{\binom{r_2}{c_1 - k - 1}}{\binom{r_2}{c_1 - k}} = \frac{r_1 - k}{k + 1} \cdot \frac{c_1 - k}{r_2 - c_1 + k + 1}.

All four factors are positive in this range: k<r1k < r_1, k<c1k < c_1, and r2−c1+k+1≥1r_2 - c_1 + k + 1 \ge 1 because k≥c1−r2k \ge c_1 - r_2. So w(k)(r1−k)(c1−k)=w(k+1)(k+1)(r2−c1+k+1)w(k)(r_1 - k)(c_1 - k) = w(k + 1)(k + 1)(r_2 - c_1 + k + 1), an identity of integers. The left side is therefore a multiple of (k+1)(r2−c1+k+1)(k + 1)(r_2 - c_1 + k + 1), and the integer division in line L4 is exact. By induction on kk, line L4 produces w(k)w(k) for every kk in range. Line L5 forms N=∑kw(k)=(nc1)N = \sum_k w(k) = \binom{n}{c_1} by Vandermonde's identity. No rounding happens anywhere. □\square

Claim 3 (lines L6 to L8 return the p-values). With i=a−kloi = a - k_{lo} the index of the observed table, the three sums are

Phi=∑k≥aw(k)N,Plo=∑k≤aw(k)N,pml=∑k:w(k)≤w(a)w(k)N,P_{hi} = \frac{\sum_{k \ge a} w(k)}{N}, \qquad P_{lo} = \frac{\sum_{k \le a} w(k)}{N}, \qquad p_{ml} = \frac{\sum_{k : w(k) \le w(a)} w(k)}{N},

which are P(A≥a)P(A \ge a), P(A≤a)P(A \le a) and P(w(A)≤w(a))P(w(A) \le w(a)) under the law of Claim 1. Because w(k)w(k) and w(a)w(a) are exact integers, the comparison in line L8 decides ties correctly; no tolerance is needed. The float result is num/N\text{num}/N with Python's correctly rounded integer division. □\square

Claim 4 (conditional and unconditional validity). For every α∈[0,1]\alpha \in [0, 1] and each of the three p-values, P(p(A)≤α∣margins)≤αP(p(A) \le \alpha \mid \text{margins}) \le \alpha under H0H_0, and hence P(p≤α)≤αP(p \le \alpha) \le \alpha without conditioning.

Proof. Given the margins, AA takes finitely many values with the law of Claim 1, and each p-value has the form P(T(A)≥T(a))P(T(A) \ge T(a)) with T(k)=kT(k) = k, T(k)=−kT(k) = -k or T(k)=−w(k)T(k) = -w(k). The lemma on the binomial test correctness page (a tail p-value over a finite space is valid) gives the conditional bound. Taking the expectation over the margins gives P(p≤α)=E[P(p≤α∣margins)]≤αP(p \le \alpha) = \mathbb{E}[P(p \le \alpha \mid \text{margins})] \le \alpha. □\square

The unconditional size is usually well below α\alpha, because the conditional size is below α\alpha for every set of margins. The page measures it for two rows of 10.

Claim 5 (the one-sided test is the right conditional test). In the binomial-rows model with p1p_1, p2p_2 arbitrary, let ψ=p1/(1−p1)p2/(1−p2)\psi = \frac{p_1/(1 - p_1)}{p_2/(1 - p_2)} be the odds ratio. Then

P(A=k∣margins)=w(k)ψk∑jw(j)ψj,P(A = k \mid \text{margins}) = \frac{w(k)\psi^k}{\sum_j w(j)\psi^j},

which depends only on ψ\psi. For ψ′>ψ\psi' > \psi the likelihood ratio (ψ′/ψ)k(\psi'/\psi)^k times a constant is increasing in kk. So the conditional family has a monotone likelihood ratio in AA, and by the Karlin-Rubin theorem the test that rejects for large AA is uniformly most powerful for H0:ψ≤1H_0: \psi \le 1 against ψ>1\psi > 1, among the tests whose conditional size is at most its own conditional size. (Exact size α\alpha needs randomization at the boundary value, as for the binomial test.)

Proof. P(A=k,C=c1−k)=w(k) p1k(1−p1)r1−kp2c1−k(1−p2)r2−c1+kP(A = k, C = c_1 - k) = w(k)\, p_1^k(1 - p_1)^{r_1 - k} p_2^{c_1 - k}(1 - p_2)^{r_2 - c_1 + k}. Taking out the factors that do not depend on kk leaves w(k)(p11−p1)k(1−p2p2)k=w(k)ψkw(k)\big(\frac{p_1}{1 - p_1}\big)^k\big(\frac{1 - p_2}{p_2}\big)^k = w(k)\psi^k, and conditioning divides by the sum over kk. □\square

Cost. Line L2 computes two binomial coefficients with O(n)O(n) arithmetic operations. Lines L3 and L4 do m−1m - 1 steps, where m=khi−klo+1≤n+1m = k_{hi} - k_{lo} + 1 \le n + 1, each with a fixed number of operations. Lines L5 to L8 are sums over at most mm terms. So the code does O(n)O(n) operations on integers and Θ(m)\Theta(m) integers are stored. Each weight is at most (nc1)<2n\binom{n}{c_1} < 2^n, so it has at most nn bits, and an operation of an nn-bit integer with a small one costs O(n)O(n) bit operations; in bit operations the time is O(n2)O(n^2). □\square

Complexity

Line L2 takes O(n)O(n) arithmetic operations, and lines L3 to L8 take Θ(m)\Theta(m), where m=khi−klo+1≤n+1m = k_{hi} - k_{lo} + 1 \le n + 1 is the number of tables with the observed margins. So the count of operations is O(n)O(n) and the extra space is Θ(m)\Theta(m) integers. Each weight is below 2n2^n, so on a machine with fixed-size words every operation on a weight costs O(n)O(n) bit operations, and the total is O(n2)O(n^2) bit operations. For nn in the thousands this is still fast; the tests run a table with n=1000n = 1000 in exact arithmetic. A floating-point version with log⁡\log weights from lgamma⁡\operatorname{lgamma} costs Θ(m)\Theta(m) operations but needs a tolerance in line L8.

Properties

  • Exact and conditional. The size is at most α\alpha given every set of margins. The tests check this in exact arithmetic for all margins with r1,r2≤10r_1, r_2 \le 10.
  • Conservative unconditionally. For two binomial rows of 10 trials with a common pp, the two-sided test at α=0.05\alpha = 0.05 rejects for 34 of the 121 possible tables, and its unconditional size, measured on a grid of pp with step 0.001, is at most 0.012780.01278, reached at p=0.5p = 0.5. The one-sided test rejects 23 tables and has size at most 0.021100.02110. These are measured on the grid, not proved maxima.
  • Power. The one-sided test is uniformly most powerful among conditional tests, by the Karlin-Rubin theorem applied to the conditional family w(k)ψkw(k)\psi^k, and with randomization it is uniformly most powerful unbiased for ψ\psi (Lehmann and Romano, Chapter 4). Against two binomial rows it loses power to unconditional tests. For rows of 10, with p1=0.7p_1 = 0.7 and p2=0.2p_2 = 0.2, the one-sided Fisher test at α=0.05\alpha = 0.05 has power 0.6220.622.
  • Symmetric in the roles of rows and columns. Transposing the table, or swapping both rows and columns, does not change any p-value. Swapping only the rows exchanges "greater" and "less".
  • Inverting the test. The conditional law w(k)ψkw(k)\psi^k also gives an exact confidence interval for the odds ratio, by test-interval duality, and the conditional maximum likelihood estimate of ψ\psi.

Variants and improvements

  • Boschloo's test. Use Fisher's p-value as the statistic, but find the cut-off from the unconditional law, maximized over the common pp (Boschloo 1970). It is never less powerful than Fisher's test. For rows of 10 and the one-sided test at α=0.05\alpha = 0.05, the largest Fisher p-value cut-off whose size stayed below 0.05 on the grid was 0.08490.0849 (size 0.04470.0447), so the test rejects 27 tables instead of 23, and its power at (0.7,0.2)(0.7, 0.2) rises from 0.6220.622 to 0.7330.733; at (0.6,0.3)(0.6, 0.3) it rises from 0.2470.247 to 0.3590.359. These numbers are computed exactly per table and maximized over a grid of pp.
  • Barnard's test. An unconditional test that orders the tables by a statistic such as the pooled z statistic and maximizes the size over the nuisance pp (Barnard 1945). It is more powerful than Fisher's test in many cases, at a higher cost: a search over pp for every candidate table.
  • Mid-p value. P(A>a)+12P(A=a)P(A > a) + \tfrac12 P(A = a). For the twins it is 0.0002400.000240. It is less conservative, but its size can exceed α\alpha.
  • Larger tables. The Freeman-Halton extension sums the multivariate hypergeometric probabilities of all r×cr \times c tables with the observed margins that are at most as likely as the observed one. The number of tables grows fast, and network algorithms or Monte Carlo sampling are used.
  • Stratified tables. Several 2×22 \times 2 tables with a common odds ratio are combined by conditioning on the margins of each; the exact conditional test and the Mantel-Haenszel test do this.
  • Paired data. For matched pairs, use the McNemar test instead; Fisher's test assumes independent units.

When to use it

Use it for a 2×22 \times 2 table when some expected counts are small, so that the chi-squared approximation is doubtful, and in designs where both margins are fixed, such as the tea experiment, where it is exactly right. With large counts it agrees with the chi-squared test with continuity correction. When the two rows are independent binomial samples and power matters, an unconditional test such as Boschloo's is a better choice at the same guaranteed level. For an effect size, report the odds ratio with an exact or a likelihood interval.

Pitfalls

  • Small size is not a guarantee of good power. Because the test is conservative, a nominal 5% test can have actual size near 1% to 2%, and the sample size needed for a given power is larger than a calculation at size 5% suggests.
  • Which two-sided rule. Software differs: R uses the minimum-likelihood rule with a relative tolerance on the probabilities; some packages double the one-sided value. For the twins the two rules give 0.0005370.000537 and 0.0009300.000930.
  • Floating-point ties. A floating-point implementation can miss ties between tables with equal probability, which changes the two-sided p-value. Exact integer weights, as here, avoid this.
  • Dependence. Paired or clustered units break the hypergeometric law. Use McNemar's test or a model for clusters.
  • The choice of one side after the fact. As the second example shows, picking "greater" after seeing a large aa halves the p-value in effect.

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.

fisher_exact.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/fisher-exact-test/. The authors are listed in prov/PNP35A.jsonl.

import math
from fractions import Fraction


def hypergeometric_weights(r1: int, r2: int, c1: int) -> tuple[int, list[int]]:
    """Return (lo, w) with w[i] = C(r1, lo + i) * C(r2, c1 - lo - i) as exact integers.

    w[i] is the number of ways to choose the c1 items of the first column so
    that lo + i of them fall in the first row. The list covers every possible
    value of the top-left cell, from lo = max(0, c1 - r2) to min(r1, c1). Each
    term comes from the one before by the ratio of consecutive binomial
    coefficients, and the integer division is exact.
    """
    lo, hi = max(0, c1 - r2), min(r1, c1)
    w = [math.comb(r1, lo) * math.comb(r2, c1 - lo)]  # @line L2
    for k in range(lo, hi):  # @line L3
        w.append(w[-1] * (r1 - k) * (c1 - k) // ((k + 1) * (r2 - c1 + k + 1)))  # @line L4
    return lo, w


def fisher_exact(
    a: int,
    b: int,
    c: int,
    d: int,
    alternative: str = "two-sided",
    exact: bool = False,
) -> float | Fraction:
    """P-value of Fisher's exact test for the 2 x 2 table [[a, b], [c, d]].

    Under the null hypothesis of independence (or equal proportions in the
    two rows), the top-left cell has the hypergeometric law given the row and
    column totals. alternative is "greater" (odds ratio > 1, large a), "less"
    (odds ratio < 1, small a) or "two-sided", which sums the probabilities of
    the tables that are at most as likely as the observed one. The weights are
    exact integers, so the two-sided comparison needs no tolerance. With
    exact=True the result is a Fraction; otherwise it is the correctly rounded
    float of that Fraction.
    """
    for v in (a, b, c, d):
        if not isinstance(v, int) or v < 0:
            raise ValueError("table entries must be non-negative integers")
    if alternative not in ("two-sided", "greater", "less"):
        raise ValueError("unknown alternative")
    r1, r2, c1 = a + b, c + d, a + c  # @line L1
    lo, w = hypergeometric_weights(r1, r2, c1)
    total = sum(w)  # @line L5
    i = a - lo
    if alternative == "greater":  # @line L6
        num = sum(w[i:])
    elif alternative == "less":  # @line L7
        num = sum(w[: i + 1])
    else:
        num = sum(v for v in w if v <= w[i])  # @line L8
    return Fraction(num, total) if exact else num / total
fisher_exact_test.py 9 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/fisher-exact-test/. The authors are listed in prov/PNP35A.jsonl.

"""Entry point named after the slug. The code lives in fisher_exact.py, because tools treat
a file whose name ends in _test.py as a test file and skip its @line markers."""

from fisher_exact import fisher_exact, hypergeometric_weights

__all__ = ["fisher_exact", "hypergeometric_weights"]
test_fisher_exact_test.py 172 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/fisher-exact-test/. The authors are listed in prov/PNP35A.jsonl.

import itertools
import math
from fractions import Fraction

import pytest

from fisher_exact_test import fisher_exact, hypergeometric_weights


def test_page_examples() -> None:
    cases = {
        (4, 0, 0, 4): (Fraction(1, 70), Fraction(1), Fraction(1, 35)),
        (10, 3, 2, 15): (Fraction(619, 1330665), None, Fraction(3571, 6653325)),
        (1, 9, 11, 3): (None, Fraction(41, 29716), Fraction(41, 14858)),
        (7, 2, 3, 8): (Fraction(293, 8398), None, Fraction(293, 4199)),
        (12, 5, 7, 16): (Fraction(67703, 4989450), None, Fraction(118933, 4989450)),
    }
    for table, expected in cases.items():
        for alt, want in zip(("greater", "less", "two-sided"), expected):
            if want is not None:
                assert fisher_exact(*table, alt, exact=True) == want
                assert fisher_exact(*table, alt) == float(want)


def test_weights_are_products_of_binomials() -> None:
    for r1 in range(0, 25):
        for r2 in range(0, 25):
            for c1 in range(0, r1 + r2 + 1):
                lo, w = hypergeometric_weights(r1, r2, c1)
                want = [math.comb(r1, k) * math.comb(r2, c1 - k) for k in range(lo, min(r1, c1) + 1)]
                assert w == want
                assert sum(w) == math.comb(r1 + r2, c1)


def brute_force(a: int, b: int, c: int, d: int) -> dict[str, Fraction]:
    # Label n items; the first r1 form row 1. Every choice of the c1 items in
    # column 1 is equally likely under the null. Count the choices.
    r1, n, c1 = a + b, a + b + c + d, a + c
    counts: dict[int, int] = {}
    for chosen in itertools.combinations(range(n), c1):
        k = sum(1 for i in chosen if i < r1)
        counts[k] = counts.get(k, 0) + 1
    total = sum(counts.values())
    return {
        "greater": Fraction(sum(v for k, v in counts.items() if k >= a), total),
        "less": Fraction(sum(v for k, v in counts.items() if k <= a), total),
        "two-sided": Fraction(sum(v for v in counts.values() if v <= counts[a]), total),
    }


def test_against_enumeration_of_labelings() -> None:
    checked = 0
    for n in range(0, 9):
        for a, b, c in itertools.product(range(n + 1), repeat=3):
            d = n - a - b - c
            if d < 0:
                continue
            want = brute_force(a, b, c, d)
            for alt, value in want.items():
                assert fisher_exact(a, b, c, d, alt, exact=True) == value
            checked += 1
    assert checked == 495


def test_conditional_size_at_most_alpha() -> None:
    # For every set of margins with n <= 20, the conditional rejection
    # probability at alpha = 0.05 is at most 0.05, in exact arithmetic.
    alpha = Fraction(1, 20)
    for r1 in range(1, 11):
        for r2 in range(1, 11):
            for c1 in range(1, r1 + r2):
                lo, w = hypergeometric_weights(r1, r2, c1)
                total = sum(w)
                for alt in ("greater", "less", "two-sided"):
                    size = sum(
                        w[i]
                        for i in range(len(w))
                        if fisher_exact(lo + i, r1 - lo - i, c1 - lo - i, r2 - c1 + lo + i, alt, exact=True) <= alpha
                    )
                    assert Fraction(size, total) <= alpha


def unconditional_size(reject: list[tuple[int, int]], p: float) -> float:
    return math.fsum(
        math.comb(10, x1) * math.comb(10, x2) * p ** (x1 + x2) * (1 - p) ** (20 - x1 - x2) for x1, x2 in reject
    )


def test_unconditional_size_is_well_below_alpha() -> None:
    # Two binomial rows with 10 trials each and a common p. Measured on a grid.
    for alt, n_reject, max_size in (("two-sided", 34, 0.0127792), ("greater", 23, 0.0210953)):
        reject = [(x1, x2) for x1 in range(11) for x2 in range(11) if fisher_exact(x1, 10 - x1, x2, 10 - x2, alt) <= 0.05]
        assert len(reject) == n_reject
        sizes = [unconditional_size(reject, k / 1000) for k in range(1, 1000)]
        k = max(range(999), key=sizes.__getitem__)
        assert (k + 1) / 1000 == 0.5
        assert sizes[k] == pytest.approx(max_size, abs=1e-7)
        exact_half = Fraction(sum(math.comb(10, x1) * math.comb(10, x2) for x1, x2 in reject), 2**20)
        assert float(exact_half) == pytest.approx(sizes[k], rel=1e-12)


def rejection_probability(reject: list[tuple[int, int]], p1: float, p2: float) -> float:
    return math.fsum(
        math.comb(10, x1) * p1**x1 * (1 - p1) ** (10 - x1) * math.comb(10, x2) * p2**x2 * (1 - p2) ** (10 - x2)
        for x1, x2 in reject
    )


def test_boschloo_raised_level_and_power() -> None:
    # Boschloo: reject when Fisher's one-sided p <= t, with t the largest
    # attainable value whose unconditional size stays <= 0.05 on the grid.
    pv = {(x1, x2): fisher_exact(x1, 10 - x1, x2, 10 - x2, "greater") for x1 in range(11) for x2 in range(11)}
    grid = [k / 1000 for k in range(1, 1000)]
    best = None
    for t in sorted(set(pv.values())):
        reject = [key for key, v in pv.items() if v <= t]
        if max(rejection_probability(reject, p, p) for p in grid) > 0.05:
            break
        best = t
    assert best == pytest.approx(0.0849012, abs=1e-7)
    fisher = [key for key, v in pv.items() if v <= 0.05]
    boschloo = [key for key, v in pv.items() if v <= best]
    assert (len(fisher), len(boschloo)) == (23, 27) and set(fisher) < set(boschloo)
    assert rejection_probability(fisher, 0.7, 0.2) == pytest.approx(0.62163, abs=1e-5)
    assert rejection_probability(boschloo, 0.7, 0.2) == pytest.approx(0.73345, abs=1e-5)
    assert rejection_probability(fisher, 0.6, 0.3) == pytest.approx(0.24736, abs=1e-5)
    assert rejection_probability(boschloo, 0.6, 0.3) == pytest.approx(0.35856, abs=1e-5)


def test_symmetries() -> None:
    for table in ((3, 7, 9, 1), (5, 5, 2, 8), (0, 4, 6, 2), (12, 5, 7, 16)):
        a, b, c, d = table
        for alt in ("greater", "less", "two-sided"):
            p = fisher_exact(a, b, c, d, alt, exact=True)
            assert fisher_exact(a, c, b, d, alt, exact=True) == p  # transpose
            assert fisher_exact(d, c, b, a, alt, exact=True) == p  # swap rows and columns
        assert fisher_exact(c, d, a, b, "greater", exact=True) == fisher_exact(a, b, c, d, "less", exact=True)
        assert fisher_exact(c, d, a, b, "two-sided", exact=True) == fisher_exact(a, b, c, d, "two-sided", exact=True)


def test_large_table_is_exact() -> None:
    # Equal row totals make the null law symmetric, so the two-sided value is
    # twice the upper tail. A log-space sum gives an independent reference.
    p = fisher_exact(300, 200, 150, 350, exact=True)
    upper = fisher_exact(300, 200, 150, 350, "greater", exact=True)
    assert p == 2 * upper
    log_total = math.lgamma(1001) - math.lgamma(451) - math.lgamma(551)

    def log_w(k: int) -> float:
        return (
            math.lgamma(501) - math.lgamma(k + 1) - math.lgamma(501 - k)
            + math.lgamma(501) - math.lgamma(451 - k) - math.lgamma(51 + k)
        )

    reference = math.fsum(math.exp(log_w(k) - log_total) for k in range(300, 451))
    assert float(upper) == pytest.approx(reference, rel=1e-9)
    assert float(upper) == pytest.approx(6.702494878e-22, rel=1e-9)
    lo, w = hypergeometric_weights(500, 500, 450)
    assert sum(w) == math.comb(1000, 450)
    assert fisher_exact(300, 200, 150, 350) == float(p)


def test_errors() -> None:
    with pytest.raises(ValueError):
        fisher_exact(1, -1, 2, 3)
    with pytest.raises(ValueError):
        fisher_exact(1, 2, 3, 4, "both")
    with pytest.raises(ValueError):
        fisher_exact(1.0, 2, 3, 4)  # type: ignore[arg-type]

History

R. A. Fisher described the test in the fifth edition of Statistical Methods for Research Workers (1934) and in "The logic of inductive inference" (1935), where he analysed J. Lange's data on the convictions of twins of criminals. The lady tasting tea appears in The Design of Experiments (1935). J. O. Irwin (1935) and Frank Yates (1934), who also proposed the continuity correction for the chi-squared test, reached the same test independently. G. A. Barnard (1945) proposed an unconditional alternative and later withdrew his preference for it in favour of conditioning; R. D. Boschloo (1970) gave the raised conditional level that bears his name.

References

  1. R. A. Fisher, The logic of inductive inference, Journal of the Royal Statistical Society 98(1), 1935, pp. 39 to 82 (the exact test for a 2 x 2 table, with the data on convictions of twins)
  2. Alan Agresti, Categorical Data Analysis, third edition, Wiley, 2013, Chapter 3 (inference for two-way contingency tables, with small-sample tests of independence) and Chapter 16 (small-sample exact inference)
  3. E. L. Lehmann and Joseph P. Romano, Testing Statistical Hypotheses, third edition, Springer, 2005, Chapter 4 (unbiased tests, with the comparison of two binomial populations by a conditional test)

Where this leads

About this page

The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.

LadderLevelWhat the next level needs
Human proofH1 sketch
  • a full proof of time.best
  • a full proof of time.worst
  • a full proof of space.extra
LeanL0 no Lean part
  • name a Lean module in the lean field (07)
Code (python)I0 not checked yet
  • the tests did not run in this build
VisualV0 none
  • add viz/scene.ts or a figure (10)
WritingW2 basic
  • a scene preset for the example