Algorithm Search⌘K

Algorithmcore

Fisher's method

Also called Fisher's combined probability test.

Combines k independent p-values into minus two times the sum of their logs, which has a chi-squared law with 2k degrees of freedom under the global null.

Time
Θ(k) worst · best
Space
Θ(k) extra
Where
k = the number of p-values combined
Properties
deterministicexactofflineiterative
Origin
Ronald A. Fisher, 1932

Fisher's method combines kk p-values from independent tests into one test of the global null hypothesis, the hypothesis that all kk nulls are true. Its statistic is X=−2∑i=1kln⁡piX = -2\sum_{i=1}^k \ln p_i. When the p-values are independent and each is uniform on (0,1)(0, 1) under its null, XX has the χ2k2\chi^2_{2k} law exactly, and the combined p-value is the upper tail P(χ2k2≥X)P(\chi^2_{2k} \ge X). Because the degrees of freedom are even, this tail is a finite sum, e−X/2∑j<k(X/2)j/j!e^{-X/2}\sum_{j<k}(X/2)^j/j!, so the whole computation is Θ(k)\Theta(k) operations with no special function. The method is not to be confused with Fisher's exact test for 2×22 \times 2 tables.

In plain words

Several independent studies each test the same kind of claim and each reports a p-value. None of them may be small enough on its own, but together they may still be hard to explain by chance. Fisher's method multiplies the p-values. If every claim is false, the product of k random numbers between 0 and 1 has a known distribution, so we can ask how often a product this small happens by chance. That probability is the combined p-value. Taking logs turns the product into a sum, and minus twice that sum follows a chi-squared law. One very small p-value can make the product small by itself, so the method reacts to strong evidence in a single study.

The problem

Model and hypotheses. There are kk tests with p-values p1,…,pkp_1, \dots, p_k, computed from independent data. Test ii has null H0,iH_{0,i}. The global null is H0=H0,1∩⋯∩H0,kH_0 = H_{0,1} \cap \dots \cap H_{0,k}. The alternative is that at least one H0,iH_{0,i} is false. Each pip_i is uniform on (0,1)(0, 1) under H0,iH_{0,i}, as it is for a test with a continuous statistic and a simple null.

Statistic. X=−2∑i=1kln⁡pi=−2ln⁡∏ipiX = -2\sum_{i=1}^k \ln p_i = -2\ln\prod_i p_i. Small p-values give a large XX.

Null distribution. Exact. If UU is uniform on (0,1)(0, 1), then P(−2ln⁡U≥x)=P(U≤e−x/2)=e−x/2P(-2\ln U \ge x) = P(U \le e^{-x/2}) = e^{-x/2}, which is the χ22\chi^2_2 law. A sum of kk independent χ22\chi^2_2 variables is χ2k2\chi^2_{2k}. So under H0H_0, X∼χ2k2X \sim \chi^2_{2k}, with mean 2k2k and variance 4k4k.

Rejection rule and size. Reject at level α\alpha when X≥χ2k,1−α2X \ge \chi^2_{2k, 1-\alpha}, equivalently when P≤αP \le \alpha. Under the stated conditions the size is exactly α\alpha. If some pip_i are only valid, P(pi≤u)≤uP(p_i \le u) \le u, as for discrete tests, the size is at most α\alpha, because XX is then stochastically smaller than χ2k2\chi^2_{2k}.

p-value. With h=X/2=−∑iln⁡pih = X/2 = -\sum_i \ln p_i,

P=P(χ2k2≥X)=e−h∑j=0k−1hjj!.P = P(\chi^2_{2k} \ge X) = e^{-h}\sum_{j=0}^{k-1}\frac{h^j}{j!}.

This is P(N≤k−1)P(N \le k - 1) for NN a Poisson variable with mean hh. For k=1k = 1, P=p1P = p_1. For k=2k = 2, with q=p1p2q = p_1p_2, P=q(1−ln⁡q)P = q(1 - \ln q).

Sensitivity and power. The test rejects when the product of the p-values is small. It has good power when one or a few studies show strong evidence, and when all show moderate evidence. It has less power than Stouffer's method when every study shows the same weak effect, and less power than Tippett's minimum when exactly one study is far from its null and the others are close to theirs. No combination method is most powerful against every alternative (Birnbaum 1954). As the sample sizes of the studies grow, Fisher's method is optimal in Bahadur's sense (Littell and Folks 1971).

The algorithm

  1. FISHER-METHOD(p₁, …, p_k) ▷ independent p-values in [0, 1], k ≥ 1
  2. 1if some pᵢ = 0 then return (∞, 0)
  3. 2h ← −Σ ln pᵢ ▷ compensated sum of logs; never form Π pᵢ
  4. 3X ← 2h
  5. 4tⱼ ← exp(−h + j ln h − ln j!) for j = 0, …, k − 1
  6. 5P ← Σ tⱼ
  7. 6return (X, min(P, 1))

When all pi=1p_i = 1, h=0h = 0, and the implementation returns (0,1)(0, 1) before line L4, which would need ln⁡0\ln 0.

Example

Four studies. Four independent studies of the same treatment report p=0.08,0.12,0.06,0.20p = 0.08, 0.12, 0.06, 0.20. None is significant at 5%.

step value
−2ln⁡pi-2\ln p_i 5.0515, 4.2405, 5.6268, 3.2189
L2: h=−∑iln⁡pih = -\sum_i \ln p_i 9.0688
L3: X=2hX = 2h, the sum of the row above 18.1377
L4: t0,t1,t2,t3t_0, t_1, t_2, t_3 0.000115, 0.001045, 0.004737, 0.014320
L5: P=∑jtjP = \sum_j t_j 0.020218

So P=0.0202P = 0.0202 with 8 degrees of freedom. The 5% critical value is χ8,0.952=15.5073<18.1377\chi^2_{8, 0.95} = 15.5073 < 18.1377, and the global null is rejected at 5%. The combined evidence is stronger than the evidence of each study.

Three methods, three patterns. The table compares Fisher's method with Stouffer's method, Z=∑iΦ−1(1−pi)/kZ = \sum_i \Phi^{-1}(1 - p_i)/\sqrt k, and Tippett's method, 1−(1−min⁡ipi)k1 - (1 - \min_i p_i)^k.

p-values Fisher Stouffer Tippett
0.08, 0.12, 0.06, 0.20 0.0202 0.0064 0.2193
0.001, 0.9, 0.9, 0.9 0.0708 0.6470 0.0040
0.2, ten times 0.0413 0.0039 0.8926

With moderate evidence everywhere, Stouffer's method gives the smallest p-value and Tippett's the largest. With one strong study and three weak ones, Tippett's gives the smallest, Stouffer's sees nothing, and Fisher's is in between. In each row Fisher's p-value lies between the other two. This balance is one reason why it is a common default.

Two studies, by hand. For p=0.03p = 0.03 and 0.040.04, q=0.0012q = 0.0012 and P=0.0012(1−ln⁡0.0012)=0.0012⋅7.7255=0.009271P = 0.0012(1 - \ln 0.0012) = 0.0012 \cdot 7.7255 = 0.009271.

Correctness

Under H0H_0, each −2ln⁡pi-2\ln p_i has the χ22\chi^2_2 law, by the computation in the problem section, and they are independent, so X∼χ2k2X \sim \chi^2_{2k}. The density of χ2k2\chi^2_{2k} at xx is the Gamma density with shape kk and scale 2, and integrating by parts k−1k - 1 times gives the upper tail e−x/2∑j<k(x/2)j/j!e^{-x/2}\sum_{j<k}(x/2)^j/j!. Lines L2 to L5 compute exactly this sum. Since the tail function is continuous and strictly decreasing, PP is uniform under H0H_0, and rejecting when P≤αP \le \alpha has size exactly α\alpha. This is proved, with no approximation. What depends on the data is the assumption of independent, uniform p-values; when it fails, the size is wrong, as the pitfalls show. The correctness proof gives each step.

Proof: Fisher's statistic has the chi-squared law with 2k degrees of freedom, and the finite Poisson sum is its exact upper tailfull

We prove that, when p1,…,pkp_1, \dots, p_k are independent and uniform on (0,1)(0, 1), the statistic X=−2∑iln⁡piX = -2\sum_i \ln p_i has the χ2k2\chi^2_{2k} law, that FISHER-METHOD returns P=P(χ2k2≥X)P = P(\chi^2_{2k} \ge X) through the finite sum e−h∑j<khj/j!e^{-h}\sum_{j<k}h^j/j! with h=X/2h = X/2, and that rejecting when P≤αP \le \alpha has size exactly α\alpha. We also prove that the test stays valid, with size at most α\alpha, when the p-values are independent and only satisfy P(pi≤u)≤uP(p_i \le u) \le u. Nothing on the page about the method itself is only measured; the sizes under dependence are computed from a closed form, and the tests check them by simulation.

Lemma 1 (one p-value). If UU is uniform on (0,1)(0, 1), then Y=−2ln⁡UY = -2\ln U has the χ22\chi^2_2 law, the exponential law with mean 2.

Proof. For y≥0y \ge 0, P(Y≥y)=P(ln⁡U≤−y/2)=P(U≤e−y/2)=e−y/2P(Y \ge y) = P(\ln U \le -y/2) = P(U \le e^{-y/2}) = e^{-y/2}. This is the upper tail of the exponential law with mean 2. The χ22\chi^2_2 density is 121Γ(1)y0e−y/2=12e−y/2\frac{1}{2^{1}\Gamma(1)}y^{0}e^{-y/2} = \frac12e^{-y/2}, whose upper tail is also e−y/2e^{-y/2}. □\square

For k=1k = 1 this already gives the result: P=P(χ22≥−2ln⁡p1)=eln⁡p1=p1P = P(\chi^2_2 \ge -2\ln p_1) = e^{\ln p_1} = p_1. The combined p-value of one p-value is itself, exactly.

Lemma 2 (sums). If Y1,…,YkY_1, \dots, Y_k are independent and each is χ22\chi^2_2, then ∑iYi\sum_i Y_i is χ2k2\chi^2_{2k}, with density fk(x)=xk−1e−x/22k(k−1)!f_k(x) = \dfrac{x^{k-1}e^{-x/2}}{2^k(k - 1)!} for x>0x > 0.

Proof. By induction on kk. For k=1k = 1, f1(x)=12e−x/2f_1(x) = \frac12e^{-x/2} is the density of Lemma 1. If ∑i<kYi\sum_{i<k}Y_i has density fk−1f_{k-1}, then the density of the sum with YkY_k is the convolution

∫0xfk−1(s)f1(x−s) ds=∫0xsk−2e−s/22k−1(k−2)!⋅e−(x−s)/22 ds=e−x/22k(k−2)!⋅xk−1k−1=fk(x).\int_0^x f_{k-1}(s)f_1(x - s)\,ds = \int_0^x \frac{s^{k-2}e^{-s/2}}{2^{k-1}(k - 2)!}\cdot\frac{e^{-(x - s)/2}}{2}\,ds = \frac{e^{-x/2}}{2^k(k - 2)!}\cdot\frac{x^{k-1}}{k - 1} = f_k(x).

The function fkf_k is the χ2k2\chi^2_{2k} density, which is xν/2−1e−x/2/(2ν/2Γ(ν/2))x^{\nu/2 - 1}e^{-x/2}/(2^{\nu/2}\Gamma(\nu/2)) with ν=2k\nu = 2k. □\square

Lemma 3 (the tail is a finite Poisson sum). For x≥0x \ge 0 and h=x/2h = x/2, ∫x∞fk(s) ds=e−h∑j=0k−1hj/j!\int_x^\infty f_k(s)\,ds = e^{-h}\sum_{j=0}^{k-1}h^j/j!.

Proof. Let Sk(h)=e−h∑j<khj/j!S_k(h) = e^{-h}\sum_{j<k}h^j/j!. Differentiating,

Sk′(h)=e−h(∑j=1k−1hj−1(j−1)!−∑j=0k−1hjj!)=−e−hhk−1(k−1)!,S_k'(h) = e^{-h}\left(\sum_{j=1}^{k-1}\frac{h^{j-1}}{(j - 1)!} - \sum_{j=0}^{k-1}\frac{h^j}{j!}\right) = -e^{-h}\frac{h^{k-1}}{(k - 1)!},

because the two sums telescope and only the last term of the second remains. With h=x/2h = x/2, ddxSk(x/2)=−12e−x/2(x/2)k−1(k−1)!=−fk(x)\frac{d}{dx}S_k(x/2) = -\frac12e^{-x/2}\frac{(x/2)^{k-1}}{(k - 1)!} = -f_k(x). Also Sk(h)→0S_k(h) \to 0 as h→∞h \to \infty, since e−he^{-h} times a polynomial tends to 0. So Sk(x/2)=∫x∞fk(s) dsS_k(x/2) = \int_x^\infty f_k(s)\,ds. □\square

The tests check the polynomial identity of this proof in exact rational arithmetic for k≤11k \le 11, and the case k=2k = 2 against the direct integral P(U1U2≤q)=q(1−ln⁡q)P(U_1U_2 \le q) = q(1 - \ln q).

Lemma 4 (what the lines compute). If all pi∈(0,1]p_i \in (0, 1] and not all are 1, lines L2 to L6 return X=−2∑iln⁡piX = -2\sum_i \ln p_i and P=Sk(X/2)P = S_k(X/2), which is at most 1. If some pi=0p_i = 0, line L1 returns X=∞X = \infty and P=0P = 0, the limit of both as pi→0p_i \to 0. If all pi=1p_i = 1, the code returns X=0X = 0 and P=1P = 1.

Proof. Line L2 computes h=−∑iln⁡pi>0h = -\sum_i \ln p_i > 0. Line L4 computes tj=exp⁡(−h+jln⁡h−ln⁡j!)=e−hhj/j!t_j = \exp(-h + j\ln h - \ln j!) = e^{-h}h^j/j!, and line L5 adds them, so P=Sk(h)P = S_k(h). Sk(h)S_k(h) is a probability, by Lemma 3, so it is at most 1 in exact arithmetic, and the minimum in line L6 only removes rounding. As pi→0p_i \to 0, h→∞h \to \infty and Sk(h)→0S_k(h) \to 0. When all pi=1p_i = 1, h=0h = 0 and Sk(0)=1S_k(0) = 1, because only the term j=0j = 0 is not 0. □\square

Lemma 5 (exact size). If the pip_i are independent and uniform on (0,1)(0, 1), then PP is uniform on (0,1)(0, 1), and P(P≤α)=αP(P \le \alpha) = \alpha.

Proof. By Lemmas 1 and 2, X∼χ2k2X \sim \chi^2_{2k}. By Lemma 4, P=G(X)P = G(X), where G(x)=∫x∞fkG(x) = \int_x^\infty f_k is continuous and strictly decreasing from 1 to 0 on [0,∞)[0, \infty). So P(G(X)≤α)=P(X≥G−1(α))=G(G−1(α))=αP(G(X) \le \alpha) = P(X \ge G^{-1}(\alpha)) = G(G^{-1}(\alpha)) = \alpha. □\square

Lemma 6 (valid p-values). If the pip_i are independent and P(pi≤u)≤uP(p_i \le u) \le u for all u∈[0,1]u \in [0, 1], then P(P≤α)≤αP(P \le \alpha) \le \alpha.

Proof. Each Yi=−2ln⁡piY_i = -2\ln p_i satisfies P(Yi≥y)=P(pi≤e−y/2)≤e−y/2P(Y_i \ge y) = P(p_i \le e^{-y/2}) \le e^{-y/2}, so YiY_i is stochastically smaller than a χ22\chi^2_2 variable Yi∗Y_i^*. By the quantile coupling, there are independent Yi∗∼χ22Y_i^* \sim \chi^2_2 with Yi≤Yi∗Y_i \le Y_i^* for every ii, so X≤X∗=∑iYi∗∼χ2k2X \le X^* = \sum_i Y_i^* \sim \chi^2_{2k}. Since GG is decreasing, P(G(X)≤α)≤P(G(X∗)≤α)=αP(G(X) \le \alpha) \le P(G(X^*) \le \alpha) = \alpha, by Lemma 5. □\square

What fails under dependence. Lemma 2 needs independence. If p1=⋯=pk=Up_1 = \dots = p_k = U, then X=−2kln⁡UX = -2k\ln U and P(X≥c)=P(U≤e−c/(2k))=e−c/(2k)P(X \ge c) = P(U \le e^{-c/(2k)}) = e^{-c/(2k)}. With c=χ2k,0.952c = \chi^2_{2k, 0.95} this is 0.0933 for k=2k = 2, so the nominal 5% test has size above 9%. This is a computation, and the tests confirm it by simulation.

Termination. Line L1 checks kk values. Line L2 takes kk logarithms and a compensated sum of kk numbers. Lines L4 and L5 compute and add kk terms. Every loop has kk steps, so the algorithm stops after Θ(k)\Theta(k) operations.

Theorem. For independent p-values p1,…,pkp_1, \dots, p_k in [0,1][0, 1], FISHER-METHOD returns X=−2∑iln⁡piX = -2\sum_i \ln p_i and P=P(χ2k2≥X)=e−X/2∑j<k(X/2)j/j!P = P(\chi^2_{2k} \ge X) = e^{-X/2}\sum_{j<k}(X/2)^j/j!. If the p-values are uniform under H0H_0, then X∼χ2k2X \sim \chi^2_{2k} exactly and the test that rejects when P≤αP \le \alpha has size exactly α\alpha; if they are only valid, the size is at most α\alpha.

Proof. Lemmas 1 to 6. ■\blacksquare

Complexity

On a real RAM with ln⁡\ln and exp⁡\exp as unit-cost operations, line L2 takes kk logarithms and line L4 kk terms, so the time is Θ(k)\Theta(k). The list of terms takes Θ(k)\Theta(k) extra space; a plain running sum would take Θ(1)\Theta(1).

Numerical stability. The product ∏ipi\prod_i p_i underflows quickly: 300 p-values of 0.1 give 10−30010^{-300}, and 324 give 0. Line L2 sums logarithms instead, with a compensated sum, so XX is accurate for any kk. Each term in line L4 is computed as one exponential of a log, so the code never forms e−he^{-h} alone, which underflows for h>745h > 745, or hj/j!h^j/j! alone, which can overflow. All terms are positive, so the sum in line L5 has no cancellation, and PP has a small relative error even when it is tiny. Below about 10−30810^{-308} it falls in the subnormal range and loses relative accuracy, and it underflows to 0 only when the true PP is below about 5×10−3245 \times 10^{-324}. Computing PP as 1−P(χ2k2≤X)1 - P(\chi^2_{2k} \le X) would lose all accuracy for small PP.

Properties

  • Exact. Under independence and uniform p-values, X∼χ2k2X \sim \chi^2_{2k} with no approximation, for every kk.
  • Symmetric and monotone. PP does not depend on the order of the p-values, and it decreases when any pip_i decreases.
  • Dominated by one small p-value. A single pi→0p_i \to 0 sends X→∞X \to \infty and P→0P \to 0, whatever the other values. A single pi=0p_i = 0 gives P=0P = 0.
  • Not dominated by one large p-value. pi=1p_i = 1 adds 0 to XX but 2 to the degrees of freedom, so it weakens the evidence without cancelling it.
  • Optimal for large studies. Among monotone combination methods, it has the largest exact Bahadur slope as the sample sizes grow (Littell and Folks 1971).
  • Valid for discrete p-values. With p-values that satisfy P(pi≤u)≤uP(p_i \le u) \le u, the test stays valid but is conservative.

Variants and improvements

  • Stouffer's method. Z=∑iΦ−1(1−pi)/kZ = \sum_i \Phi^{-1}(1 - p_i)/\sqrt k, which is N(0,1)N(0, 1) under H0H_0. With weights wiw_i, Z=∑iwiΦ−1(1−pi)/∑iwi2Z = \sum_i w_i\Phi^{-1}(1 - p_i)/\sqrt{\sum_i w_i^2}; weights ni\sqrt{n_i} give the most power when all studies estimate the same effect. It needs one-sided p-values in a common direction.
  • Tippett's method. Use min⁡ipi\min_i p_i, with P=1−(1−min⁡ipi)kP = 1 - (1 - \min_i p_i)^k. This is the Šidák adjustment of the smallest p-value, and it is close to the Bonferroni correction kmin⁡ipik\min_i p_i used as a global test.
  • Pearson's method. −2∑iln⁡(1−pi)-2\sum_i \ln(1 - p_i) is also χ2k2\chi^2_{2k} under H0H_0, and it is large when the p-values are near 1. Pearson (1933) proposed this variant along with the product statistic.
  • Lancaster's weighted method. Replace each −2ln⁡pi-2\ln p_i by the χdi2\chi^2_{d_i} quantile of 1−pi1 - p_i, so that larger studies get more degrees of freedom. The sum is χ∑di2\chi^2_{\sum d_i}.
  • Brown's method. For dependent tests, Brown (1975) approximates XX by cχf2c\chi^2_f, with cc and ff chosen to match the mean 2k2k and the variance 4k+2∑i<jCov⁡(−2ln⁡pi,−2ln⁡pj)4k + 2\sum_{i<j}\operatorname{Cov}(-2\ln p_i, -2\ln p_j): f=2E[X]2/Var⁡(X)f = 2E[X]^2/\operatorname{Var}(X) and c=Var⁡(X)/(2E[X])c = \operatorname{Var}(X)/(2E[X]). For tests built from correlated normal statistics, Brown gives the covariances as a function of the correlation.
  • Permutation calibration. When the dependence is unknown but the raw data are available, compute XX on permuted data and take the p-value from the permutation test distribution.
  • Closed testing. Fisher's method used for every intersection of nulls, inside the closed testing principle, gives tests of the single nulls with strong family-wise error control.
  • e-values. Products of independent e-variables are e-variables, which gives a combination rule that also works under optional continuation, where Fisher's method does not.

When to use it

Use Fisher's method to ask whether there is any signal at all in a set of independent tests, for example in a meta-analysis of studies that report only p-values, or to combine tests of one hypothesis on independent subsets of data. It answers "is at least one null false", not "which one", and not "how large is the effect". To find which nulls are false, use a multiple testing procedure such as Holm's or Benjamini-Hochberg. When the studies report effects and standard errors, a weighted meta-analysis of the effects is better than any combination of p-values. When the tests are dependent, use Brown's method or permutations instead.

Pitfalls

  • Dependent p-values. If all kk p-values are the same uniform value UU, then X=−2kln⁡UX = -2k\ln U and the size of the nominal 5% test is e−χ2k,0.952/(2k)e^{-\chi^2_{2k, 0.95}/(2k)}: 0.093 for k=2k = 2, 0.144 for k=4k = 4 and 0.208 for k=10k = 10. Positive dependence makes the test anti-conservative.
  • Two-sided p-values. Combining two-sided p-values from studies with effects in opposite directions gives evidence against the global null that does not support any single direction. Use one-sided p-values when the direction matters.
  • A p-value of 0. Software that rounds a tiny p-value to 0 makes XX infinite and P=0P = 0. Keep the p-values to full precision.
  • Selected p-values. Combining only the published studies, or only the significant subgroups, makes the p-values non-uniform under the null, and the combined p-value is far too small.
  • Rejecting H0H_0 is weak information. It says that at least one null is false. It does not say that most are false, or that the effect is consistent.

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_core.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/fisher-combined-probability-test/. The authors are listed in prov/SR875B.jsonl.
"""Fisher's method for combining independent p-values.

X = -2 sum ln p_i. When the k p-values are independent and uniform on (0, 1)
under the global null, X has the chi-squared law with 2k degrees of freedom
exactly, and the combined p-value is its upper tail. For even degrees of
freedom the tail is a finite Poisson sum,
    P(chi2_2k >= x) = exp(-x/2) sum_{j < k} (x/2)^j / j!,
which the code evaluates term by term in log space, so that neither the
product of the p-values nor exp(-x/2) underflows.
The code is in this file and not in fisher_combined_probability_test.py,
because tools treat a file whose name ends in _test.py as a test file.
"""

import math
from collections.abc import Sequence


def fisher_method(p: Sequence[float]) -> tuple[float, float]:
    """Combine independent p-values; returns (X, P) with X = -2 sum ln p_i and P = P(chi2_2k >= X)."""
    k = len(p)
    if k == 0:
        raise ValueError("need at least one p-value")
    if any(not 0.0 <= v <= 1.0 for v in p):  # also rejects NaN
        raise ValueError("p-values must lie in [0, 1]")
    if any(v == 0.0 for v in p):  # @line L1
        return math.inf, 0.0
    h = -math.fsum(math.log(v) for v in p)  # @line L2
    x = 2.0 * h  # @line L3
    if h == 0.0:  # all p-values are 1
        return 0.0, 1.0
    log_h = math.log(h)  # @line L4
    terms = [math.exp(-h + j * log_h - math.lgamma(j + 1)) for j in range(k)]
    total = math.fsum(terms)  # @line L5
    return x, min(total, 1.0)  # @line L6
stdist.py 238 lines
# SPDX-License-Identifier: MIT
# Shared helper of the pe1 statistics pages of https://algorithm.tamnd.com/. The authors are listed in prov/.
"""Normal, chi-square, t and F distribution functions in the standard library.

The incomplete gamma and beta functions return a lower tail and an upper
tail, and each tail is computed directly where it is small, so an upper tail
such as chi2_sf(200, 3) does not come from 1 - cdf and does not cancel.
Quantiles use a safeguarded bisection on the CDF (lower half) or on the upper
tail (upper half); the bracket shrinks until floating point stops it, so the
probability error is that of the CDF, below 1e-12 for moderate parameters.
"""

import math
from statistics import NormalDist

_STD = NormalDist()
_EPS = 1e-16
_TINY = 1e-300
_MAXIT = 10000


def norm_cdf(x: float) -> float:
    """P(Z <= x) for a standard normal Z."""
    return 0.5 * math.erfc(-x / math.sqrt(2.0))


def norm_sf(x: float) -> float:
    """P(Z > x), computed with erfc, so it is accurate for large x."""
    return 0.5 * math.erfc(x / math.sqrt(2.0))


def norm_ppf(p: float) -> float:
    """The lower p-quantile z_p of the standard normal, 0 < p < 1."""
    if not 0.0 < p < 1.0:
        raise ValueError("p must be in (0, 1)")
    return _STD.inv_cdf(p)


def _gamma_tails(a: float, x: float) -> tuple[float, float]:
    """(P(a, x), Q(a, x)), the regularized lower and upper incomplete gamma."""
    if a <= 0.0 or x < 0.0:
        raise ValueError("need a > 0 and x >= 0")
    if x == 0.0:
        return 0.0, 1.0
    if math.isinf(x):
        return 1.0, 0.0
    front = math.exp(-x + a * math.log(x) - math.lgamma(a))
    if x < a + 1.0:
        # Series: P = front * sum_{j >= 0} x^j / (a (a + 1) ... (a + j)).
        ap, term = a, 1.0 / a
        total = term
        for _ in range(_MAXIT):
            ap += 1.0
            term *= x / ap
            total += term
            if abs(term) < abs(total) * _EPS:
                break
        p = front * total
        return p, 1.0 - p
    # Continued fraction for Q, modified Lentz.
    b = x + 1.0 - a
    c = 1.0 / _TINY
    d = 1.0 / b
    h = d
    for i in range(1, _MAXIT):
        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
        step = d * c
        h *= step
        if abs(step - 1.0) < _EPS:
            break
    q = front * h
    return 1.0 - q, q


def gamma_p(a: float, x: float) -> float:
    """Regularized lower incomplete gamma P(a, x)."""
    return _gamma_tails(a, x)[0]


def gamma_q(a: float, x: float) -> float:
    """Regularized upper incomplete gamma Q(a, x) = 1 - P(a, x)."""
    return _gamma_tails(a, x)[1]


def _beta_cf(a: float, b: float, x: float) -> float:
    """The continued fraction of I_x(a, b), modified Lentz."""
    qab, qap, qam = a + b, a + 1.0, a - 1.0
    c = 1.0
    d = 1.0 - qab * x / qap
    if abs(d) < _TINY:
        d = _TINY
    d = 1.0 / d
    h = d
    for m in range(1, _MAXIT):
        m2 = 2 * m
        aa = m * (b - m) * x / ((qam + m2) * (a + m2))
        d = 1.0 + aa * d
        if abs(d) < _TINY:
            d = _TINY
        c = 1.0 + aa / c
        if abs(c) < _TINY:
            c = _TINY
        d = 1.0 / d
        h *= d * c
        aa = -(a + m) * (qab + m) * x / ((a + m2) * (qap + m2))
        d = 1.0 + aa * d
        if abs(d) < _TINY:
            d = _TINY
        c = 1.0 + aa / c
        if abs(c) < _TINY:
            c = _TINY
        d = 1.0 / d
        step = d * c
        h *= step
        if abs(step - 1.0) < _EPS:
            break
    return h


def _beta_tails(a: float, b: float, x: float, y: float | None = None) -> tuple[float, float]:
    """(I_x(a, b), 1 - I_x(a, b)), each computed directly where it is small.

    y is 1 - x; pass it when it is known more accurately than 1 - x.
    """
    if a <= 0.0 or b <= 0.0:
        raise ValueError("need a > 0 and b > 0")
    if y is None:
        y = 1.0 - x
    if x <= 0.0:
        return 0.0, 1.0
    if y <= 0.0:
        return 1.0, 0.0
    front = math.exp(
        math.lgamma(a + b) - math.lgamma(a) - math.lgamma(b)
        + a * math.log(x) + b * math.log(y)
    )
    if x < (a + 1.0) / (a + b + 2.0):
        low = front * _beta_cf(a, b, x) / a
        return low, 1.0 - low
    # Symmetry: I_x(a, b) = 1 - I_(1-x)(b, a).
    up = front * _beta_cf(b, a, y) / b
    return 1.0 - up, up


def beta_inc(a: float, b: float, x: float) -> float:
    """Regularized incomplete beta function I_x(a, b)."""
    return _beta_tails(a, b, x)[0]


def chi2_cdf(x: float, k: float) -> float:
    """P(X <= x) for X chi-square with k > 0 degrees of freedom."""
    return 0.0 if x <= 0.0 else gamma_p(k / 2.0, x / 2.0)


def chi2_sf(x: float, k: float) -> float:
    """P(X > x) for X chi-square with k degrees of freedom, without 1 - cdf."""
    return 1.0 if x <= 0.0 else gamma_q(k / 2.0, x / 2.0)


def t_sf(x: float, k: float) -> float:
    """P(T > x) for T Student t with k > 0 degrees of freedom."""
    if math.isfinite(x):
        s = k + x * x
        half = 0.5 * _beta_tails(k / 2.0, 0.5, k / s, x * x / s)[0]  # P(|T| > |x|) / 2
    else:
        half = 0.0
    return half if x >= 0.0 else 1.0 - half


def t_cdf(x: float, k: float) -> float:
    """P(T <= x) for T Student t with k degrees of freedom."""
    return t_sf(-x, k)


def f_cdf(x: float, k1: float, k2: float) -> float:
    """P(F <= x) for F with (k1, k2) degrees of freedom."""
    if x <= 0.0:
        return 0.0
    return _beta_tails(k2 / 2.0, k1 / 2.0, k2 / (k2 + k1 * x), k1 * x / (k2 + k1 * x))[1]


def f_sf(x: float, k1: float, k2: float) -> float:
    """P(F > x) = I_(k2 / (k2 + k1 x))(k2 / 2, k1 / 2)."""
    if x <= 0.0:
        return 1.0
    return _beta_tails(k2 / 2.0, k1 / 2.0, k2 / (k2 + k1 * x), k1 * x / (k2 + k1 * x))[0]


def _quantile(cdf, sf, p: float, lo: float, hi: float) -> float:
    """The x with cdf(x) = p, by bisection on cdf (p <= 1/2) or on sf (p > 1/2).

    lo must satisfy cdf(lo) <= p; hi is doubled until cdf(hi) >= p.
    """
    if not 0.0 < p < 1.0:
        raise ValueError("p must be in (0, 1)")
    if p <= 0.5:
        g = lambda x: cdf(x) - p  # increasing in x
    else:
        q = 1.0 - p
        g = lambda x: q - sf(x)  # increasing in x, and no cancellation in sf
    while g(hi) < 0.0:
        lo, hi = hi, 2.0 * hi if hi > 0.0 else 1.0
    for _ in range(400):
        mid = 0.5 * (lo + hi)
        if mid <= lo or mid >= hi:
            break
        if g(mid) < 0.0:
            lo = mid
        else:
            hi = mid
    return 0.5 * (lo + hi)


def chi2_ppf(p: float, k: float) -> float:
    """The lower p-quantile chi^2_(k, p)."""
    return _quantile(lambda x: chi2_cdf(x, k), lambda x: chi2_sf(x, k), p, 0.0, max(1.0, k))


def t_ppf(p: float, k: float) -> float:
    """The lower p-quantile t_(k, p)."""
    if p == 0.5:
        return 0.0
    if p < 0.5:
        return -t_ppf(1.0 - p, k)
    return _quantile(lambda x: t_cdf(x, k), lambda x: t_sf(x, k), p, 0.0, 1.0)


def f_ppf(p: float, k1: float, k2: float) -> float:
    """The lower p-quantile F_(k1, k2, p)."""
    return _quantile(lambda x: f_cdf(x, k1, k2), lambda x: f_sf(x, k1, k2), p, 0.0, 1.0)
fisher_combined_probability_test.py 8 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/fisher-combined-probability-test/. The authors are listed in prov/SR875B.jsonl.
"""Entry point named after the slug. The code lives in fisher_core.py, because tools treat
a file whose name ends in _test.py as a test file and skip its @line markers."""

from fisher_core import fisher_method

__all__ = ["fisher_method"]
test_fisher_combined_probability_test.py 122 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/fisher-combined-probability-test/. The authors are listed in prov/SR875B.jsonl.

import math
import random
from fractions import Fraction

import pytest

from fisher_combined_probability_test import fisher_method
from stdist import chi2_ppf, chi2_sf


def product_cdf(k: int, q: float, steps: int = 4000) -> float:
    """Brute force: P(U_1 ... U_k <= q) for iid uniforms, by repeated one-dimensional integration.

    F_1(s) = min(s, 1) and F_j(s) = integral_0^1 F_(j-1)(s/u) du. The part u <= s gives s.
    On u in (s, 1) put u = s e^t, so F_j(s) = s + s integral_0^(-ln s) F_(j-1)(e^(-t)) e^t dt
    for s < 1. F_(j-1) is kept on a grid in t, and the integral is cumulated by Simpson's rule.
    """
    if q >= 1.0:
        return 1.0
    big_t = -math.log(q)
    h = big_t / steps
    ts = [h * i for i in range(steps + 1)]
    f = [math.exp(-t) for t in ts]  # F_1(e^(-t)) = e^(-t)
    for _ in range(2, k + 1):
        g = [f[i] * math.exp(ts[i]) for i in range(steps + 1)]
        cum = [0.0] * (steps + 1)
        for i in range(1, steps + 1):  # Simpson pairs for even i, a third-order rule for odd i
            if i % 2 == 0:
                cum[i] = cum[i - 2] + h / 3 * (g[i - 2] + 4 * g[i - 1] + g[i])
            else:
                cum[i] = cum[i - 1] + h / 12 * (5 * g[i - 1] + 8 * g[i] - g[i + 1])
        f = [math.exp(-ts[i]) * (1 + cum[i]) for i in range(steps + 1)]
    return f[-1]


def test_worked_example() -> None:
    x, p = fisher_method([0.08, 0.12, 0.06, 0.20])
    assert x == pytest.approx(18.137682, abs=1e-6)
    assert p == pytest.approx(0.020218, abs=1e-6)
    assert x > chi2_ppf(0.95, 8) == pytest.approx(15.5073, abs=1e-4)


def test_k1_returns_the_p_value_itself() -> None:
    # For k = 1, X = -2 ln p is chi-squared with 2 degrees of freedom and P(chi2_2 >= X) = e^(-X/2) = p.
    rng = random.Random(1)
    for _ in range(200):
        u = rng.random() or 0.5
        x, p = fisher_method([u])
        assert x == pytest.approx(-2 * math.log(u), rel=1e-15)
        assert p == pytest.approx(u, rel=1e-14)


def test_poisson_sum_identity_exactly() -> None:
    # S_k(h) = e^(-h) sum_(j<k) h^j/j! has S_k(0) = 1 and S_k'(h) = -e^(-h) h^(k-1)/(k-1)!, the
    # negative chi-squared(2k) density in h = x/2. The polynomial part of S_k' is checked in Fractions.
    for k in range(1, 12):
        for h in (Fraction(0), Fraction(1, 3), Fraction(5, 2), Fraction(17)):
            poly = sum(h ** j / math.factorial(j) for j in range(k))
            dpoly = sum(j * h ** (j - 1) / math.factorial(j) for j in range(1, k))
            assert dpoly - poly == -(h ** (k - 1)) / math.factorial(k - 1)
        assert sum(Fraction(0) ** j / math.factorial(j) for j in range(k)) == 1


def test_k2_closed_form() -> None:
    for a, b in ((0.03, 0.04), (0.5, 0.5), (0.9, 1e-6), (0.2, 0.7)):
        q = a * b
        assert fisher_method([a, b])[1] == pytest.approx(q * (1 - math.log(q)), rel=1e-13)


def test_against_incomplete_gamma_and_product_integral() -> None:
    rng = random.Random(2)
    for _ in range(100):
        k = rng.randint(1, 40)
        p = [rng.random() ** rng.choice((1, 2, 4)) or 0.5 for _ in range(k)]
        x, pc = fisher_method(p)
        assert pc == pytest.approx(chi2_sf(x, 2 * k), rel=1e-9, abs=1e-300)
    for k in (2, 3, 4):
        for p in ([0.3] * k, [0.01, 0.5, 0.9, 0.2][:k], [0.08, 0.12, 0.06, 0.20][:k]):
            assert fisher_method(p)[1] == pytest.approx(product_cdf(k, math.prod(p)), rel=1e-7)


def test_null_uniformity_by_monte_carlo() -> None:
    rng = random.Random(3)
    reps = 20000
    for k in (1, 3, 8):
        ps = [fisher_method([1.0 - rng.random() for _ in range(k)])[1] for _ in range(reps)]
        for u in (0.01, 0.05, 0.25, 0.5, 0.9):
            assert abs(sum(v <= u for v in ps) / reps - u) < 0.012


def test_perfect_dependence_inflates_the_size() -> None:
    # If all k p-values are the same uniform U, X = -2k ln U and the size is exp(-c/(2k)).
    for k, size in ((2, 0.0933003), (4, 0.1439320), (10, 0.2079367)):
        assert math.exp(-chi2_ppf(0.95, 2 * k) / (2 * k)) == pytest.approx(size, abs=1e-6)
    rng = random.Random(4)
    reps = 20000
    hits = 0
    for _ in range(reps):
        u = 1.0 - rng.random()
        hits += fisher_method([u, u])[1] <= 0.05
    assert abs(hits / reps - 0.0933) < 0.008


def test_order_monotonicity_and_edges() -> None:
    p = [0.3, 0.01, 0.7, 0.2]
    assert fisher_method(p) == fisher_method(sorted(p))
    assert fisher_method([0.3, 0.01, 0.7, 0.19])[1] < fisher_method(p)[1]
    assert fisher_method([1.0, 1.0]) == (0.0, 1.0)
    assert fisher_method([0.0, 0.5]) == (math.inf, 0.0)
    x, pc = fisher_method([1e-100] * 3)  # the product 1e-300 is near underflow; P is not
    assert pc == pytest.approx(chi2_sf(x, 6), rel=1e-9) and pc > 0.0
    x, pc = fisher_method([math.exp(-1.0)] * 2000)  # X = 4000 = degrees of freedom
    assert pc == pytest.approx(chi2_sf(x, 4000), rel=1e-9)


def test_rejects_bad_input() -> None:
    for bad in ([], [0.5, 1.5], [-0.1], [float("nan")]):
        with pytest.raises(ValueError):
            fisher_method(bad)

History

Fisher described the method in the fourth edition of Statistical Methods for Research Workers (1932), in the section on combining the probabilities of independent tests, in which he gave the χ2k2\chi^2_{2k} law of −2ln⁡∏ipi-2\ln\prod_i p_i. Tippett had proposed the minimum p-value in 1931, and Karl Pearson published the same product statistic, with a variant for p-values near 1, in 1933. Stouffer and his coauthors used the normal combination in The American Soldier (1949). Birnbaum (1954) proved that no combination method is best against every alternative, and Littell and Folks (1971) proved that Fisher's method is asymptotically optimal in Bahadur's sense. Brown (1975) gave the scaled chi-squared correction for dependent tests that is still in common use.

References

  1. Allan Birnbaum, Combining independent tests of significance, Journal of the American Statistical Association 49(267) (1954), pages 559 to 574, no method of combining independent tests is optimal in general; optimal properties of the methods of Fisher and Tippett
  2. Ramon C. Littell and J. Leroy Folks, Asymptotic optimality of Fisher's method of combining independent tests, Journal of the American Statistical Association 66(336) (1971), pages 802 to 806, Fisher's method has the largest exact Bahadur slope among monotone methods of combination
  3. Morton B. Brown, A method for combining non-independent, one-sided tests of significance, Biometrics 31(4) (1975), pages 987 to 992, the scaled chi-squared approximation of the null law of Fisher's statistic for dependent tests

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