Algorithm Search⌘K

Algorithmcore

Benjamini-Hochberg procedure

Also called BH procedure, linear step-up procedure.

Sort the p-values and reject the k smallest, for the largest k with p_(k) <= k q / m. With independent null p-values the FDR is exactly (m_0/m) q, so at most q.

Time
Θ(m log m) worst · best
Space
Θ(m) extra
Where
m = the number of hypotheses
Properties
deterministicnot exactofflineiterative
Origin
Yoav Benjamini, Yosef Hochberg, 1995

The Benjamini-Hochberg procedure (BH) tests mm hypotheses and controls the false discovery rate, the expected proportion of false rejections among the rejections. It sorts the p-values, p(1)≤⋯≤p(m)p_{(1)} \le \dots \le p_{(m)}, finds the largest kk with p(k)≤kq/mp_{(k)} \le kq/m, and rejects H(1),…,H(k)H_{(1)}, \dots, H_{(k)}. When the null p-values are independent of each other and of the non-null ones, its FDR is at most (m0/m)q(m_0/m)q, and exactly (m0/m)q(m_0/m)q when the null p-values are uniform, whatever the false nulls are. Here m0m_0 is the number of true nulls. The thresholds kq/mkq/m grow linearly from q/mq/m, the Bonferroni level, to qq, so BH rejects far more than the FWER methods when many effects are real. It is the most used multiple testing method in genomics and other large-scale screening.

In plain words

You have many tests and expect some real effects among them. Instead of asking that no false alarm ever happens, you ask that false alarms make up only a small share of what you report, on average. Sort the results from the most convincing to the least. The most convincing one must pass a very strict bar, the second a bar twice as easy, the third three times as easy, and so on. Then find the last result in the list that passes its own bar, and report it and everything above it, even the ones above it that missed their own bar. The more results look convincing, the more lenient the method gets. This is what makes it powerful when there are many real effects.

The problem

Input. P-values p1,…,pmp_1, \dots, p_m for hypotheses H1,…,HmH_1, \dots, H_m, and a target FDR level q∈(0,1]q \in (0, 1]. The set of true nulls is I0I_0, with m0m_0 elements.

Output. The rejected set {i:pi≤kq/m}\{i : p_i \le kq/m\} for the kk above, and the adjusted p-values p~i\tilde p_i, with HiH_i rejected exactly when p~i≤q\tilde p_i \le q.

Error rate controlled. The false discovery rate E[V/max⁡(R,1)]E[V/\max(R, 1)], where VV is the number of rejected true nulls and RR the number of rejections. Control is strong, over every configuration of true and false nulls.

Dependence and level.

  • Independent null p-values, independent of the non-null p-values: FDR≤(m0/m)q\text{FDR} \le (m_0/m)q in finite samples, with equality when each null p-value is exactly uniform. This is proved below.
  • Positive regression dependence on the subset of true nulls (PRDS), as for one-sided tests on normal vectors with nonnegative correlations: FDR≤(m0/m)q\text{FDR} \le (m_0/m)q (Benjamini and Yekutieli 2001). This is cited, not proved here.
  • Arbitrary dependence: FDR≤(m0/m)q∑i=1m1/i\text{FDR} \le (m_0/m)q\sum_{i=1}^m 1/i, and this bound can be attained when m0=mm_0 = m and q∑i=1m1/i≤1q\sum_{i=1}^m 1/i \le 1. The Benjamini-Yekutieli procedure runs BH at q/∑i=1m1/iq/\sum_{i=1}^m 1/i for this case.

FWER. Under the global null BH is the Simes test, so it controls the FWER weakly at qq for independent p-values. It does not control the FWER strongly.

The algorithm

  1. BH(p₁, …, p_m, q) ▷ p-values in [0, 1], FDR level q
  2. 1sort the indices so that p_(1) ≤ … ≤ p_(m)
  3. 2k ← m; while k ≥ 1 and m · p_(k) > k · q do
  4. 3k ← k − 1 ▷ step up: from the largest p-value down
  5. 4reject H_(1), …, H_(k)
  6. 5run ← 1; for r ← m down to 1 do ▷ adjusted p-values
  7. 6run ← min(run, m · p_(r) / r)
  8. 7p̃_(r) ← run
  9. 8return (rejected set, p̃)

Lines L2 and L3 look for the last p-value below its line, starting from the largest one. All hypotheses before it are rejected at line L4, even those whose own p-value lies above its own threshold. That is the step-up rule. The test at line L2 multiplies, mp(k)>kqm p_{(k)} > kq, instead of dividing, so that the decisions do not change with rounding and agree with the adjusted p-values. Ties do not matter: the rejected set is {i:pi≤kq/m}\{i : p_i \le kq/m\}, which does not depend on how the sort orders tied values.

Equivalent descriptions.

  • Graph. Plot p(k)p_{(k)} against kk, draw the line through the origin with slope q/mq/m, and reject everything up to the last point on or below the line.
  • Counting. With N(t)=#{i:pi≤t}N(t) = \#\{i : p_i \le t\}, the number of rejections is R=max⁡{k:N(kq/m)≥k}R = \max\{k : N(kq/m) \ge k\}. So t=Rq/mt = Rq/m is the largest threshold with mt/N(t)≤qmt/N(t) \le q, where mt/N(t)mt/N(t) is the estimate of the FDR of the rule "reject pi≤tp_i \le t" when all mm nulls are counted as true.
  • Self-consistency. The rejected set is the largest set SS such that pi≤∣S∣q/mp_i \le |S|q/m for every i∈Si \in S.

Example

The 15 p-values of Benjamini and Hochberg (1995). The p-values are 0.0001, 0.0004, 0.0019, 0.0095, 0.0201, 0.0278, 0.0298, 0.0344, 0.0459, 0.3240, 0.4262, 0.5719, 0.6528, 0.7590 and 1.000, at q=0.05q = 0.05, so the thresholds are k/300k/300.

kk p(k)p_{(k)} kq/mkq/m p(k)≤kq/mp_{(k)} \le kq/m adjusted p~(k)\tilde p_{(k)}
1 0.0001 0.0033 yes 0.0015
2 0.0004 0.0067 yes 0.003
3 0.0019 0.01 yes 0.0095
4 0.0095 0.0133 yes 0.0356
5 0.0201 0.0167 no 0.0603
6 0.0278 0.02 no 0.0639
7 0.0298 0.0233 no 0.0639
8 0.0344 0.0267 no 0.0645
9 0.0459 0.03 no 0.0765
10 0.3240 0.0333 no 0.486

The last row that passes is k=4k = 4, so BH rejects four hypotheses. Bonferroni, Holm and Hochberg at α=0.05\alpha = 0.05 reject three. The adjusted value at k=6k = 6 is a running minimum: 15⋅0.0278/6=0.069515 \cdot 0.0278/6 = 0.0695 is lowered to 15⋅0.0298/7=0.063915 \cdot 0.0298/7 = 0.0639 by line L6.

Step-up at work. For p=(0.01,0.03,0.028,0.04)p = (0.01, 0.03, 0.028, 0.04) at q=0.1q = 0.1, the thresholds are 0.025, 0.05, 0.075 and 0.1, and every sorted p-value passes, so all four are rejected. For p=(0.03,0.03,0.9)p = (0.03, 0.03, 0.9) at q=0.05q = 0.05, the row k=2k = 2 passes, 0.03≤2⋅0.05/3=0.03330.03 \le 2 \cdot 0.05/3 = 0.0333, so both 0.03 values are rejected although each is above the first threshold 0.05/30.05/3.

The level by hand. Take m=2m = 2, H2H_2 false with p2=0p_2 = 0, and H1H_1 true with p1p_1 uniform. BH rejects H2H_2 always, since 0≤q/20 \le q/2, and rejects H1H_1 exactly when p1≤2q/2=qp_1 \le 2q/2 = q, with R=2R = 2. So V/R=1/2V/R = 1/2 with probability qq and 0 otherwise, and FDR=q/2=(m0/m)q\text{FDR} = q/2 = (m_0/m)q.

Correctness

The proof shows that FDR=(m0/m)q\text{FDR} = (m_0/m)q for independent uniform null p-values. It is a leave-one-out argument. Fix a true null HiH_i and set pip_i to 0. Let Ck(i)C_k^{(i)} be the event that BH then rejects exactly kk hypotheses. This event depends only on the other p-values. A short lemma shows that HiH_i is rejected with R=kR = k exactly when pi≤kq/mp_i \le kq/m and Ck(i)C_k^{(i)} holds. So

E[1{Hi rejected}max⁡(R,1)]=∑k=1m1kP(pi≤kqm)P(Ck(i))=qm∑k=1mP(Ck(i))=qm,E\left[\frac{\mathbf 1\{H_i \text{ rejected}\}}{\max(R, 1)}\right] = \sum_{k=1}^m \frac1k P\left(p_i \le \frac{kq}{m}\right)P(C_k^{(i)}) = \frac qm\sum_{k=1}^m P(C_k^{(i)}) = \frac qm,

by independence and uniformity, since the events Ck(i)C_k^{(i)} partition the sample space. Summing over the m0m_0 true nulls gives (m0/m)q(m_0/m)q. A valid but not uniform null p-value, P(pi≤u)≤uP(p_i \le u) \le u, turns the second equality into ≤\le.

The tests check this identity exactly. With m=4m = 4 and q=2/5q = 2/5, every threshold kq/m=k/10kq/m = k/10 is a point of the grid {1/10,…,1}\{1/10, \dots, 1\}, so a null p-value uniform on that grid satisfies P(pi≤kq/m)=kq/mP(p_i \le kq/m) = kq/m exactly. Summing over all 10m010^{m_0} values of the null p-values in rational arithmetic gives an FDR of exactly m0/10m_0/10 for each m0=1,…,4m_0 = 1, \dots, 4 and each choice of the non-null p-values. The tests also compare BH with a brute force over all subsets, using the self-consistency description, and measure the FDR by Monte Carlo for independent and for equicorrelated normal statistics. The equicorrelated case is PRDS, so the measured FDR is checked against (m0/m)q(m_0/m)q there too, but that bound is only measured, not proved.

Proof: The Benjamini-Hochberg procedure has FDR exactly (m_0/m) q for independent uniform null p-valuesfull

We prove that BH rejects the set described on the page (Lemma 1), that this set is the largest self-consistent set (Proposition 2), and that its false discovery rate is at most (m0/m)q(m_0/m)q when every null p-value is valid and independent of all the other p-values, with equality when the null p-values are uniform on the thresholds (Theorem 4). As a corollary, the Simes global test has size exactly qq. Control under positive dependence (PRDS) is due to Benjamini and Yekutieli (2001) and is only cited here; the tests measure it by Monte Carlo in one PRDS model.

Setting. P-values p1,…,pm∈[0,1]p_1, \dots, p_m \in [0, 1] and a level q∈(0,1]q \in (0, 1]. For t≥0t \ge 0 let N(t)=#{j:pj≤t}N(t) = \#\{j : p_j \le t\}, and write tk=kq/mt_k = kq/m. I0I_0 is the set of true nulls, m0=∣I0∣m_0 = |I_0|, VV is the number of rejected true nulls and RR the number of rejections.

Lemma 1 (what the lines compute). Let R=max⁡{k∈{1,…,m}:N(tk)≥k}R = \max\{k \in \{1, \dots, m\} : N(t_k) \ge k\}, or R=0R = 0 if there is no such kk. Then lines L2 and L3 end with k=Rk = R, line L4 rejects exactly the set {i:pi≤tR}\{i : p_i \le t_R\}, and this set has exactly RR elements. (For R=0R = 0 the set is empty.)

Proof. For any kk and tt, p(k)≤tp_{(k)} \le t if and only if at least kk of the p-values are at most tt, that is, N(t)≥kN(t) \ge k. So the test at line L2 fails, mp(k)≤kqmp_{(k)} \le kq, exactly when N(tk)≥kN(t_k) \ge k. The loop starts at k=mk = m and goes down while the test holds, so it stops at the largest kk with N(tk)≥kN(t_k) \ge k, or at 0. Next, N(tR)=RN(t_R) = R: if N(tR)=n>RN(t_R) = n > R, then n≤mn \le m and N(tn)≥N(tR)=nN(t_n) \ge N(t_R) = n, because tn>tRt_n > t_R, which contradicts the choice of RR. So exactly RR p-values are at most tRt_R. They are the RR smallest, so they are the hypotheses of ranks 1,…,R1, \dots, R for any order of ties, which is what line L4 rejects. □\square

Proposition 2 (self-consistency). Call a set SS self-consistent if pi≤∣S∣q/mp_i \le |S|q/m for all i∈Si \in S. The BH set S∗={i:pi≤tR}S^* = \{i : p_i \le t_R\} is self-consistent, and it contains every self-consistent set. So it is the largest one.

Proof. ∣S∗∣=R|S^*| = R by Lemma 1, so S∗S^* is self-consistent. If SS is self-consistent with s=∣S∣≥1s = |S| \ge 1, then S⊆{i:pi≤ts}S \subseteq \{i : p_i \le t_s\}, so N(ts)≥sN(t_s) \ge s and s≤Rs \le R. Then S⊆{i:pi≤ts}⊆{i:pi≤tR}=S∗S \subseteq \{i : p_i \le t_s\} \subseteq \{i : p_i \le t_R\} = S^*. □\square

The test file uses Proposition 2 as a brute force: it searches all subsets for the largest self-consistent one, for m≤8m \le 8, and compares the result with BH.

Lemma 3 (leave one out). Fix ii. Let p(i)p^{(i)} be the vector pp with pip_i replaced by 0, and let R(i)≥1R^{(i)} \ge 1 be the number of rejections of BH on p(i)p^{(i)}. Then for each k∈{1,…,m}k \in \{1, \dots, m\},

{Hi rejected and R=k}={pi≤tk}∩{R(i)=k}.\{H_i \text{ rejected and } R = k\} = \{p_i \le t_k\} \cap \{R^{(i)} = k\}.

Proof. R(i)≥1R^{(i)} \ge 1 because the replaced value 0 is at most t1t_1. Write N(i)N^{(i)} for the count on p(i)p^{(i)}, so N(i)(t)=N(t)+1{pi>t}N^{(i)}(t) = N(t) + \mathbf 1\{p_i > t\}, and let k0=R(i)k_0 = R^{(i)}.

Case pi≤tk0p_i \le t_{k_0}. For every k≥k0k \ge k_0, pi≤tkp_i \le t_k, so N(tk)=N(i)(tk)N(t_k) = N^{(i)}(t_k). Hence N(tk0)=N(i)(tk0)≥k0N(t_{k_0}) = N^{(i)}(t_{k_0}) \ge k_0, and N(tk)=N(i)(tk)<kN(t_k) = N^{(i)}(t_k) < k for k>k0k > k_0. By Lemma 1, R=k0R = k_0, and HiH_i is rejected since pi≤tk0=tRp_i \le t_{k_0} = t_R.

Case pi>tk0p_i > t_{k_0}. Since N(t)≤N(i)(t)N(t) \le N^{(i)}(t) for all tt, every kk with N(tk)≥kN(t_k) \ge k also has N(i)(tk)≥kN^{(i)}(t_k) \ge k, so R≤k0R \le k_0. Then pi>tk0≥tRp_i > t_{k_0} \ge t_R, and HiH_i is not rejected.

So HiH_i is rejected exactly when pi≤tR(i)p_i \le t_{R^{(i)}}, and then R=R(i)R = R^{(i)}. For a fixed kk, the event "HiH_i rejected and R=kR = k" is therefore the event "R(i)=kR^{(i)} = k and pi≤tkp_i \le t_k". □\square

The point of Lemma 3 is that R(i)R^{(i)} is a function of the other m−1m - 1 p-values only.

Theorem 4 (FDR of BH). Suppose that for each i∈I0i \in I_0, pip_i is independent of (pj)j≠i(p_j)_{j \ne i} and P(pi≤tk)≤tkP(p_i \le t_k) \le t_k for k=1,…,mk = 1, \dots, m. Then

FDR=E[Vmax⁡(R,1)]≤m0mq.\text{FDR} = E\left[\frac{V}{\max(R, 1)}\right] \le \frac{m_0}{m}q.

If moreover P(pi≤tk)=tkP(p_i \le t_k) = t_k for all i∈I0i \in I_0 and all kk, as for continuous uniform null p-values, then FDR=(m0/m)q\text{FDR} = (m_0/m)q exactly, for every law of the non-null p-values.

Proof. Pointwise, V/max⁡(R,1)=∑i∈I01{Hi rejected}/max⁡(R,1)V/\max(R, 1) = \sum_{i \in I_0}\mathbf 1\{H_i \text{ rejected}\}/\max(R, 1). When HiH_i is rejected, R≥1R \ge 1, so by Lemma 3

1{Hi rejected}max⁡(R,1)=∑k=1m1k1{pi≤tk}1{R(i)=k}.\frac{\mathbf 1\{H_i \text{ rejected}\}}{\max(R, 1)} = \sum_{k=1}^m \frac1k\mathbf 1\{p_i \le t_k\}\mathbf 1\{R^{(i)} = k\}.

Take expectations. Since R(i)R^{(i)} depends only on (pj)j≠i(p_j)_{j \ne i}, which is independent of pip_i,

E[1{Hi rejected}max⁡(R,1)]=∑k=1m1kP(pi≤tk)P(R(i)=k)≤∑k=1m1k⋅kqmP(R(i)=k)=qm∑k=1mP(R(i)=k)=qm.E\left[\frac{\mathbf 1\{H_i \text{ rejected}\}}{\max(R, 1)}\right] = \sum_{k=1}^m \frac1k P(p_i \le t_k)P(R^{(i)} = k) \le \sum_{k=1}^m \frac1k\cdot\frac{kq}{m}P(R^{(i)} = k) = \frac qm\sum_{k=1}^m P(R^{(i)} = k) = \frac qm.

The last step holds because R(i)R^{(i)} takes a value in {1,…,m}\{1, \dots, m\}. With P(pi≤tk)=tkP(p_i \le t_k) = t_k the inequality is an equality. Summing over the m0m_0 true nulls gives the claim. □\square

The proof needs each null p-value to be independent of all the other p-values, null and non-null, but it puts no condition on the joint law of the non-null p-values among themselves. It uses validity only at the mm points tkt_k. This is why the exact test in the code works: on the grid {1/10,…,1}\{1/10, \dots, 1\} with m=4m = 4 and q=2/5q = 2/5, every tk=k/10t_k = k/10 is a grid point, so a null p-value uniform on the grid has P(pi≤tk)=tkP(p_i \le t_k) = t_k, and Theorem 4 gives FDR=m0/10\text{FDR} = m_0/10 exactly. The test computes this sum over all 10m010^{m_0} null configurations in rational arithmetic and finds equality for m0=1,…,4m_0 = 1, \dots, 4.

Corollary 5 (Simes). If all mm nulls are true and the p-values are independent and uniform, then P(∃j:p(j)≤jq/m)=qP(\exists j : p_{(j)} \le jq/m) = q.

Proof. The event is {R≥1}\{R \ge 1\} by Lemma 1. Under the global null V=RV = R, so V/max⁡(R,1)=1{R≥1}V/\max(R, 1) = \mathbf 1\{R \ge 1\}, and Theorem 4 with m0=mm_0 = m gives P(R≥1)=qP(R \ge 1) = q. □\square

Proposition 6 (monotone). If pj′≤pjp'_j \le p_j for all jj, then BH on p′p' rejects every hypothesis that BH on pp rejects.

Proof. N′(t)≥N(t)N'(t) \ge N(t) for all tt, so R′≥RR' \ge R by Lemma 1, and tR′≥tRt_{R'} \ge t_R. If pi≤tRp_i \le t_R then pi′≤pi≤tR≤tR′p'_i \le p_i \le t_R \le t_{R'}. □\square

Adjusted p-values. Let p~(r)=min⁡j≥rmin⁡(1,mp(j)/j)\tilde p_{(r)} = \min_{j \ge r}\min(1, mp_{(j)}/j), which lines L5 to L7 compute (the running value starts at 1). For q≤1q \le 1, p~(r)≤q\tilde p_{(r)} \le q if and only if some j≥rj \ge r has mp(j)≤jqmp_{(j)} \le jq, that is, if and only if R≥rR \ge r, which by Lemma 1 is the rejection of rank rr. So HiH_i is rejected at level qq exactly when p~i≤q\tilde p_i \le q, and the adjusted p-values give the decisions at every level at once.

What is cited, not proved. Benjamini and Yekutieli (2001) show that FDR≤(m0/m)q\text{FDR} \le (m_0/m)q when the p-values are PRDS on the subset of true nulls, and that FDR≤(m0/m)q∑i=1m1/i\text{FDR} \le (m_0/m)q\sum_{i=1}^m 1/i under any dependence. The second bound is proved on the Benjamini-Yekutieli page. The first is checked only by simulation in the tests, with equicorrelated one-sided normal statistics.

Complexity

On a real RAM, sorting at line L1 takes Θ(mlog⁡m)\Theta(m\log m) time, which is the sorting problem. Lines L2 to L7 take Θ(m)\Theta(m). So the time is Θ(mlog⁡m)\Theta(m\log m), and the extra space is Θ(m)\Theta(m).

The rejections alone need no sort. Put each pip_i into the bucket bi=⌈mpi/q⌉b_i = \lceil mp_i/q\rceil, the first kk with mpi≤kqmp_i \le kq, with bucket m+1m + 1 for pi>qp_i > q. Then N(kq/m)N(kq/m) is the prefix sum of the bucket counts up to kk, and RR is the largest kk with N(kq/m)≥kN(kq/m) \ge k. This is the idea of counting sort and takes Θ(m)\Theta(m) time. The implementation gives both versions and checks that they agree, including on ties and values that fall exactly on a threshold.

Properties

  • FDR at (m0/m)q(m_0/m)q for independent tests. Exact, in finite samples, for every configuration of the false nulls. The bound is conservative by the factor m0/mm_0/m, which Storey's method estimates and removes.
  • Weak FWER control. Under the global null, V=RV = R, the FDR is the FWER, and BH is the Simes test of size qq.
  • More powerful than FWER methods. The kk-th threshold kq/mkq/m is at least the Holm and Hochberg threshold q/(m−k+1)q/(m - k + 1), because k(m−k+1)≥mk(m - k + 1) \ge m for 1≤k≤m1 \le k \le m. So at the same level BH rejects a superset of what Hochberg's procedure rejects, and so of Holm and Bonferroni.
  • Step-up. It rejects H(1),…,H(k)H_{(1)}, \dots, H_{(k)} for the largest passing kk, so a hypothesis is rejected whenever enough other p-values are small.
  • Monotone. Lowering any p-value never removes a rejection: N(t)N(t) only grows, so RR only grows, and the thresholds with it.
  • Adjusted p-values. p~(r)=min⁡j≥rmin⁡(1,mp(j)/j)\tilde p_{(r)} = \min_{j \ge r}\min(1, mp_{(j)}/j). They are often called BH q-values, but they are not the same as Storey's q-values, which also estimate π0=m0/m\pi_0 = m_0/m.

Variants and improvements

  • Benjamini-Yekutieli. BH at q/∑i=1m1/iq/\sum_{i=1}^m 1/i controls the FDR under any dependence. See Benjamini-Yekutieli procedure.
  • Adaptive BH. Estimate π0=m0/m\pi_0 = m_0/m and run BH at q/π^0q/\hat\pi_0. With a suitable estimator this still controls the FDR at qq under independence; see Storey's q-value.
  • Weighted BH. Use pi/wip_i/w_i with weights that average 1, to give prior favourites a larger threshold. Under independence and fixed weights the FDR is still at most qq.
  • e-BH. For e-values, reject the kk largest for the largest kk with e(k)≥m/(kq)e_{(k)} \ge m/(kq). This controls the FDR at (m0/m)q(m_0/m)q under any dependence (Wang and Ramdas 2022).
  • Knockoffs. In variable selection for regression, the knockoff filter uses a BH-like stopping rule on signed statistics, with an estimate of VV built from fake copies of the variables.
  • Local fdr. The Bayesian view of BH estimates a tail-area false discovery rate; the local false discovery rate gives the posterior probability for each case instead.

When to use it

Use BH when mm is large, when you expect a fair number of real effects, and when a small proportion of false discoveries is acceptable, as in screening for genes, proteins, brain voxels or features for follow-up. The tests should be independent or positively dependent; for one-sided tests on positively correlated normal or tt statistics this is the case. For arbitrary dependence use Benjamini-Yekutieli, at a large cost in power. When many nulls are false, Storey's method gains power by estimating m0m_0. When every single rejection must be right, as for the primary end points of a clinical trial, control the family-wise error rate instead.

Pitfalls

  • Reading the level as a bound for one study. FDR control is a bound on the mean proportion. In one study the proportion of false discoveries can be much larger than qq.
  • Rejecting only the hypotheses below their own threshold. That is a step-down reading of the rule, and it rejects less than BH. In the 15 p-value example both readings give 4, but for (0.03,0.03,0.9)(0.03, 0.03, 0.9) the step-down reading rejects nothing.
  • Two-sided p-values under positive correlation. PRDS holds for one-sided tests on positively correlated normal statistics. It need not hold for two-sided tests, although simulations usually show that BH still works there.
  • Discrete p-values. For discrete tests BH is conservative, because P(pi≤kq/m)P(p_i \le kq/m) is below kq/mkq/m.
  • Choosing qq or the family after seeing the result. As with any error rate, the guarantee holds only when the level and the set of hypotheses are fixed in advance.

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.

benjamini_hochberg_procedure.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/benjamini-hochberg-procedure/. The authors are listed in prov/MA7Z7G.jsonl.
"""The Benjamini-Hochberg linear step-up procedure.

Sort the p-values, p_(1) <= ... <= p_(m), find the largest k with
p_(k) <= k q / m, and reject H_(1), ..., H_(k). For independent null p-values
(independent of each other and of the non-null ones) the false discovery rate is
at most (m_0 / m) q, with equality when the null p-values are uniform. Comparisons
are done as m p <= k q, so that floats and fractions.Fraction give the same
decisions and the adjusted p-values agree with the rejections.

Two implementations: bh sorts (Theta(m log m)); bh_linear counts p-values in m
buckets and needs no sort (Theta(m)).
"""

import math
from collections.abc import Sequence


def _check(p: Sequence, q) -> None:
    if any(not 0 <= v <= 1 for v in p):
        raise ValueError("p-values must lie in [0, 1]")
    if not 0 < q <= 1:
        raise ValueError("q must lie in (0, 1]")


def bh(p: Sequence, q) -> tuple[list[bool], list]:
    """Return (reject, adjusted) in the original order of p."""
    m = len(p)
    if m == 0:
        return [], []
    _check(p, q)
    order = sorted(range(m), key=lambda i: p[i])  # @line L1
    k = m
    while k >= 1 and m * p[order[k - 1]] > k * q:  # @line L2
        k -= 1  # @line L3
    reject = [False] * m
    for r in range(k):  # @line L4
        reject[order[r]] = True
    adjusted = [0] * m
    running = 1
    for r in range(m - 1, -1, -1):  # @line L5
        running = min(running, m * p[order[r]] / (r + 1))  # @line L6
        adjusted[order[r]] = running  # @line L7
    return reject, adjusted  # @line L8


def bh_linear(p: Sequence, q) -> list[bool]:
    """The same rejections as bh, found by counting in Theta(m) time without sorting.

    Bucket b holds the p-values whose smallest k with m p <= k q is b. Then
    #{i : p_i <= k q / m} is the prefix sum up to k, and BH's k is the largest k
    whose prefix sum is at least k.
    """
    m = len(p)
    if m == 0:
        return []
    _check(p, q)
    count = [0] * (m + 2)
    bucket = [0] * m
    for i, v in enumerate(p):
        b = max(1, math.ceil(m * v / q))  # first guess, corrected below for rounding
        while b > 1 and m * v <= (b - 1) * q:
            b -= 1
        while b <= m and m * v > b * q:
            b += 1
        bucket[i] = min(b, m + 1)  # m + 1 means "never at most k q / m"
        count[bucket[i]] += 1
    k, cum = 0, 0
    for j in range(1, m + 1):
        cum += count[j]
        if cum >= j:
            k = j
    return [bucket[i] <= k for i in range(m)]
test_benjamini_hochberg_procedure.py 149 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/benjamini-hochberg-procedure/. The authors are listed in prov/MA7Z7G.jsonl.

import itertools
import math
import random
import statistics
from fractions import Fraction

import pytest

from benjamini_hochberg_procedure import bh, bh_linear

BH95 = [0.0001, 0.0004, 0.0019, 0.0095, 0.0201, 0.0278, 0.0298, 0.0344, 0.0459, 0.3240, 0.4262, 0.5719, 0.6528, 0.7590, 1.000]


def bh_brute_force(p: list, q) -> list[bool]:
    """Brute force from the self-consistency characterization: the largest set S with m p_i <= |S| q for all i in S.

    For each size s from m down to 1, S must be {i : m p_i <= s q}; it works when it has at least s elements.
    The answer is checked against every subset for small m in a separate test.
    """
    m = len(p)
    for s in range(m, 0, -1):
        chosen = [m * v <= s * q for v in p]
        if sum(chosen) >= s:
            return chosen
    return [False] * m


def test_worked_example_by_hand() -> None:
    reject, adjusted = bh(BH95, 0.05)
    # k q / m = k / 300: 0.0095 <= 4/300 = 0.01333, but 0.0201 > 5/300, 0.0278 > 6/300, ..., 0.0459 > 9/300.
    assert [i for i, r in enumerate(reject) if r] == [0, 1, 2, 3]
    assert adjusted[:6] == pytest.approx([0.0015, 0.003, 0.0095, 0.035625, 0.0603, 15 * 0.0298 / 7], abs=1e-9)
    # The sixth adjusted value is a running minimum: 15 * 0.0278 / 6 = 0.0695 is larger than 15 * 0.0298 / 7.
    assert bh_linear(BH95, 0.05) == reject


def test_step_up_rejects_p_values_above_their_own_threshold() -> None:
    p = [Fraction(1, 100), Fraction(3, 100), Fraction(28, 1000), Fraction(4, 100)]
    reject, _ = bh(p, Fraction(1, 10))
    # Thresholds k/40: 0.025, 0.05, 0.075, 0.1. Sorted 0.01, 0.028, 0.03, 0.04: k = 4 passes.
    assert reject == [True, True, True, True]
    reject, _ = bh([Fraction(3, 100), Fraction(3, 100), Fraction(9, 10)], Fraction(1, 20))
    # 0.9 > 0.05; 0.03 <= 2 * 0.05 / 3 = 0.0333, so both 0.03 are rejected, though 0.03 > 0.05/3.
    assert reject == [True, True, False]


def test_self_consistency_by_subset_enumeration() -> None:
    rng = random.Random(95)
    for _ in range(200):
        m = rng.randint(1, 8)
        p = [Fraction(rng.randint(0, 40), 40) for _ in range(m)]
        q = Fraction(rng.randint(1, 10), 20)
        best: tuple = ()
        for size in range(m, 0, -1):
            for s in itertools.combinations(range(m), size):
                if all(m * p[i] <= size * q for i in s):
                    best = s
                    break
            if best:
                break
        expected = [i in best for i in range(m)]
        assert bh(p, q)[0] == expected == bh_brute_force(p, q) == bh_linear(p, q)


def test_linear_version_matches_sorting_version_on_floats() -> None:
    rng = random.Random(6)
    for _ in range(3000):
        m = rng.randint(1, 40)
        p = [rng.random() ** rng.choice([1, 3, 6]) for _ in range(m)]
        if rng.random() < 0.3:  # exact ties and values on the thresholds
            p = [round(v * 20) / 20 for v in p]
        q = rng.choice([0.05, 0.1, 0.2])
        assert bh_linear(p, q) == bh(p, q)[0] == bh_brute_force(p, q)


def test_adjusted_p_values_match_rejections() -> None:
    rng = random.Random(7)
    for _ in range(300):
        m = rng.randint(1, 10)
        p = [Fraction(rng.randint(0, 100), 100) for _ in range(m)]
        _, adjusted = bh(p, Fraction(1, 10))
        for q in [Fraction(k, 100) for k in range(1, 100, 4)]:
            assert bh(p, q)[0] == [a <= q for a in adjusted]


def test_invalid_input() -> None:
    assert bh([], 0.1) == ([], [])
    assert bh_linear([], 0.1) == []
    with pytest.raises(ValueError):
        bh([0.5], 0)
    with pytest.raises(ValueError):
        bh_linear([1.5], 0.1)


def exact_fdr_on_grid(m: int, m0: int, q: Fraction, false_p: list) -> Fraction:
    """FDR by summing over all 10^m0 values of independent null p-values, each uniform on {1/10, ..., 1}."""
    grid = [Fraction(k, 10) for k in range(1, 11)]
    total = Fraction(0)
    for nulls in itertools.product(grid, repeat=m0):
        p = list(nulls) + false_p
        reject, _ = bh(p, q)
        r = sum(reject)
        v = sum(reject[:m0])
        if r:
            total += Fraction(v, r)
    return total / 10**m0


def test_fdr_equals_m0_over_m_times_q_exactly() -> None:
    """m = 4 and q = 2/5, so every threshold k q / m = k / 10 is a grid point and P(p_i <= k q / m) = k q / m exactly."""
    m, q = 4, Fraction(2, 5)
    rng = random.Random(2001)
    for m0 in range(1, m + 1):
        for _ in range(2 if m0 < m else 1):
            false_p = [Fraction(rng.randint(0, 1000), 1000) for _ in range(m - m0)]
            assert exact_fdr_on_grid(m, m0, q, false_p) == Fraction(m0, m) * q


def test_monte_carlo_fdr_independent_normals() -> None:
    rng = random.Random(1995)
    nd = statistics.NormalDist()
    m, m0, q, reps = 20, 15, 0.1, 6000
    total = 0.0
    for _ in range(reps):
        z = [rng.gauss(0, 1) + (2.5 if i >= m0 else 0.0) for i in range(m)]
        reject = bh_linear([nd.cdf(-v) for v in z], q)
        r = sum(reject)
        total += sum(reject[:m0]) / r if r else 0.0
    # Exact value (m0/m) q = 0.075. The standard deviation of the false discovery proportion is below 0.25,
    # so four standard errors are below 0.013.
    assert abs(total / reps - m0 / m * q) < 0.013


def test_monte_carlo_fdr_under_positive_dependence() -> None:
    """One-sided tests on equicorrelated normals (rho = 0.5) are PRDS: the FDR is at most (m0/m) q."""
    rng = random.Random(29)
    nd = statistics.NormalDist()
    m, m0, q, reps = 20, 15, 0.1, 6000
    total = 0.0
    for _ in range(reps):
        shared = rng.gauss(0, 1)
        z = [math.sqrt(0.5) * shared + math.sqrt(0.5) * rng.gauss(0, 1) + (2.5 if i >= m0 else 0.0) for i in range(m)]
        reject, _ = bh([nd.cdf(-v) for v in z], q)
        r = sum(reject)
        total += sum(reject[:m0]) / r if r else 0.0
    assert total / reps <= m0 / m * q + 0.013

History

Simes (1986) proposed the rule "reject the global null if p(j)≤jα/mp_{(j)} \le j\alpha/m for some jj" as a global test, and noted that it does not control the FWER for single hypotheses. Benjamini and Hochberg (1995) introduced the false discovery rate and showed that the same rule, applied to single hypotheses, controls this new error rate for independent test statistics. Benjamini and Yekutieli (2001) proved control under positive dependence and gave the correction for arbitrary dependence. Storey (2002) and Storey, Taylor and Siegmund (2004) gave the adaptive version, the q-value and a martingale proof of the control.

References

  1. Yoav Benjamini and Yosef Hochberg, Controlling the false discovery rate, a practical and powerful approach to multiple testing, Journal of the Royal Statistical Society, Series B 57(1) (1995), pages 289 to 300, the linear step-up procedure, the proof that it controls the FDR at (m_0/m) q for independent test statistics, and the example with 15 p-values
  2. Yoav Benjamini and Daniel Yekutieli, The control of the false discovery rate in multiple testing under dependency, The Annals of Statistics 29(4) (2001), pages 1165 to 1188, FDR control at (m_0/m) q under positive regression dependence on the subset of true nulls (PRDS), and the bound for arbitrary dependence
  3. R. J. Simes, An improved Bonferroni procedure for multiple tests of significance, Biometrika 73(3) (1986), pages 751 to 754, the global test that rejects when p_(j) <= j alpha / n for some j, which is the Benjamini-Hochberg rule under the global null

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