Algorithm Search⌘K

Algorithmadvanced

Westfall-Young procedure

Also called maxT procedure, permutation step-down procedure.

Compare each statistic, largest first, with the permutation law of the maximum over the hypotheses not yet rejected. This controls the FWER strongly and gains power from the dependence.

Time
Θ(B m n + m log m) worstΘ(B m + m log m) table_given
Space
Θ(m) extra
Where
B = the number of permutations used; m = the number of hypotheses; n = the number of units
Properties
deterministicnot exactofflineiterative
Origin
Peter H. Westfall, S. Stanley Young, 1993

The Westfall-Young procedure controls the family-wise error rate for mm tests computed on the same data, and it uses the dependence between the tests instead of a worst-case bound. Each test has a statistic tjt_j, large when HjH_j looks false. Sort them so that t(1)≥⋯≥t(m)t_{(1)} \ge \dots \ge t_{(m)}. Recompute all mm statistics on every relabeling of the data in a permutation test group GG of size BB, the identity included. The hypothesis of rank kk is compared with the permutation law of the maximum of the statistics of ranks k,…,mk, \dots, m, the ones not yet rejected. Its adjusted p-value is

p~(k)=max⁡j≤k#{g∈G:max⁡l≥jT(l)(g)≥t(j)}B.\tilde p_{(k)} = \max_{j \le k}\frac{\#\{g \in G : \max_{l \ge j}T_{(l)}(g) \ge t_{(j)}\}}{B}.

This is the maxT method. When the tests are independent its thresholds are close to those of Holm's method; when they are strongly correlated, the maximum of mm statistics is not much larger than one statistic, and the method rejects nearly as much as unadjusted tests would.

In plain words

When many tests use the same data, they often move together. A Bonferroni-type correction ignores this and assumes the worst case. The Westfall-Young method measures it. It shuffles the group labels many times, and for each shuffle it records the largest test result over all the tests. This shows how large the largest result can be when nothing is real. A result is called real only if it beats that largest value often enough. Then the method removes that result and repeats with the tests that remain, which makes the bar a little lower each time. If the tests move together, the largest result over all of them is not much bigger than a single result, so the bar stays low and more real effects are found.

The problem

Input. Data ZZ, a finite group GG of BB transformations of the data (in the two-sample case, the relabelings of the units into two groups of sizes n1n_1 and n2n_2), and statistics T1,…,TmT_1, \dots, T_m with observed values tj=Tj(Z)t_j = T_j(Z). A level α∈(0,1)\alpha \in (0, 1). The set of true nulls is I0I_0, with m0m_0 elements.

Output. The adjusted p-values p~1,…,p~m\tilde p_1, \dots, \tilde p_m, and the rejected set {j:p~j≤α}\{j : \tilde p_j \le \alpha\}.

Error rate controlled. Strong control of the family-wise error rate: P(V≥1)≤αP(V \ge 1) \le \alpha for every set I0I_0 of true nulls.

Dependence assumption. No assumption on the dependence between the statistics. The assumption is on the data: the joint law of the true-null part of the data is invariant under GG. In the two-sample case this means that the vectors of the null variables of the units are exchangeable across the two groups. It is the randomization hypothesis of the permutation test, applied to all true nulls together. Westfall and Young state a closely related condition, subset pivotality.

Exact or asymptotic. Exact in finite samples, as an inequality, when GG is enumerated or sampled at random with the identity added. With bootstrap resampling instead of permutations the control is only asymptotic.

The algorithm

The input is the table Tj(g)T_j(g), one row per element of GG, the identity among them.

  1. MAXT-STEP-DOWN(t₁, …, t_m, rows T(g) for g ∈ G)
  2. 1sort so that t_(1) ≥ … ≥ t_(m); count[1..m] ← 0
  3. 2for each g ∈ G do u ← -∞
  4. 3for k ← m down to 1 do ▷ successive maxima, from the bottom
  5. 4u ← max(u, T_(k)(g)) ▷ u = max over ranks ≥ k
  6. 5if u ≥ t_(k) then count[k] ← count[k] + 1
  7. 6run ← 0; for k ← 1 to m do
  8. 7run ← max(run, count[k] / B); p̃_(k) ← run
  9. 8return p̃

Line L2 starts each row with u=−∞u = -\infty. One pass from the bottom computes all the maxima over tails at once, so a row costs Θ(m)\Theta(m). The running maximum at line L7 enforces the step-down order: a hypothesis is rejected only if all those with larger statistics are rejected.

The single-step version compares every tjt_j with the maximum over all mm statistics: #{g:max⁡lTl(g)≥tj}/B\#\{g : \max_lT_l(g) \ge t_j\}/B. The step-down version is never larger. The minP version replaces each statistic by its marginal permutation p-value and uses the minimum p-value instead of the maximum statistic. It puts the tests on a common scale, at the cost of a second level of resampling.

Example

A hand example. Eight units, the first four in group 1, and three integer variables:

unit 1 2 3 4 5 6 7 8
variable 1 12 15 11 14 6 8 5 9
variable 2 30 33 29 35 25 27 24 26
variable 3 7 9 2 8 6 4 5 3

The statistic is ∣n2S1−n1S2∣|n_2S_1 - n_1S_2|, where S1S_1 and S2S_2 are the group sums, an integer multiple of the difference of the means. The observed values are t=(96,100,32)t = (96, 100, 32). The group GG is the set of all (84)=70\binom84 = 70 splits. Variables 1 and 2 separate the groups completely, so only the observed split and its mirror reach their observed values, and their marginal permutation p-values are 2/70=0.02862/70 = 0.0286. Variable 3 has marginal p-value 24/7024/70.

rank kk variable t(k)t_{(k)} maximum over count count / 70 p~(k)\tilde p_{(k)}
1 2 100 variables 2, 1, 3 2 0.0286 0.0286
2 1 96 variables 1, 3 2 0.0286 0.0286
3 3 32 variable 3 24 0.343 0.343

At α=0.05\alpha = 0.05 the procedure rejects variables 1 and 2. Holm's method on the marginal permutation p-values compares 2/702/70 with 0.05/3=0.01670.05/3 = 0.0167 and rejects nothing; so does the Bonferroni correction. The single-step maxT p-value of variable 3 is 48/70=0.68648/70 = 0.686, twice its step-down value.

Two copies of one variable. If the data hold the same perfectly separated variable twice, the maximum of the two statistics is the statistic itself, so both adjusted p-values are 2/702/70 and both are rejected at 0.05. Holm gives 4/70=0.0574/70 = 0.057 to both and rejects nothing. This is the extreme case of the gain from dependence.

A small simulation. In the tests, each of 8 units has a common random effect, so four integer variables are correlated about 0.9. Variables 3 and 4 are shifted in group 1, variables 1 and 2 are not. Over 500 data sets, with all 70 splits enumerated in each, the maxT step-down procedure has measured FWER 0.030 at α=0.05\alpha = 0.05 and rejects 28% of the false nulls. Holm on the marginal permutation p-values never rejects, because the smallest possible p-value is 2/702/70 and 4⋅2/70=0.114>0.054 \cdot 2/70 = 0.114 > 0.05. This shows a practical point: with few units, only a method that uses the joint permutation law can reject anything.

Correctness

Two facts carry the proof. First, the maxT step-down procedure is a shortcut of the closed testing principle. For a set II of hypotheses, test the intersection HIH_I with the permutation test of max⁡j∈ITj\max_{j \in I}T_j. If jj is the smallest rank in II, then II is contained in the tail SjS_j of ranks j,…,mj, \dots, m, the maximum of the observed values over II is t(j)t_{(j)}, and so the local p-value of II is at most that of SjS_j. So the largest local p-value over the sets that contain rank kk is attained at a tail, which is the formula above. The tests check this equality, in exact rational arithmetic, against closed testing over all 2m−12^m - 1 subsets.

Second, the error event is a single permutation test. If a true null is rejected, the true null with the largest statistic, at rank k∗k^*, is rejected, and its count is computed over a tail Sk∗S_{k^*} that contains every true null. So the permutation p-value of max⁡j∈I0Tj\max_{j \in I_0}T_j is at most α\alpha. This statistic depends only on the true-null part of the data, and by the exact level of the permutation test (Claim 2 in the proof for the permutation test), it is at most α\alpha with probability at most α\alpha. The behavior of the false nulls under permutation never enters. The correctness proof gives the details.

Proof: The maxT step-down procedure is closed testing with permutation tests of the maximum, and it controls the family-wise error rate strongly under the randomization hypothesis for the true nullsfull

We prove four things about MAXT-STEP-DOWN. First, the lines compute the adjusted p-values of the formula on the page (Lemma 1). Second, these are exactly the adjusted p-values of the closed testing procedure whose local test of HIH_I is the permutation test of max⁡j∈ITj\max_{j \in I}T_j (Theorem 2). Third, the procedure controls the family-wise error rate strongly in finite samples when the joint law of the true-null part of the data is invariant under the group (Theorem 3). Fourth, the step-down adjusted p-values lie between the marginal and the single-step ones (Proposition 4). All four are proved here. The gain in power over Holm is only measured, in the tests.

Setting. Data ZZ take values in a set Z\mathcal Z on which a finite group GG acts, with B=∣G∣B = |G|. Statistics T1,…,Tm:Z→RT_1, \dots, T_m : \mathcal Z \to \mathbb R, with observed values tj=Tj(Z)t_j = T_j(Z). Write Tj(g)=Tj(gZ)T_j(g) = T_j(gZ) for the row of gg; the identity ee gives Tj(e)=tjT_j(e) = t_j. Line L1 sorts so that t(1)≥⋯≥t(m)t_{(1)} \ge \dots \ge t_{(m)}, where (k)(k) is the index of rank kk; ties are broken by the sort and do not affect any statement below. Let Sk={(k),…,(m)}S_k = \{(k), \dots, (m)\} be the tail of ranks kk and later. For a nonempty set II of indices, let MI(g)=max⁡j∈ITj(g)M_I(g) = \max_{j \in I}T_j(g) and define the local p-value

p^I=#{g∈G:MI(g)≥MI(e)}B.\hat p_I = \frac{\#\{g \in G : M_I(g) \ge M_I(e)\}}{B}.

In the two-sample case GG is the symmetric group on the nn units, and the statistics depend on gg only through the set of units it puts in group 1; by Claim 1 in the proof for the permutation test, counting over the (nn1)\binom n{n_1} splits gives the same fractions as counting over GG.

Lemma 1 (what the lines compute). For each kk, the count at line L5 equals #{g:MSk(g)≥t(k)}\#\{g : M_{S_k}(g) \ge t_{(k)}\}, and line L7 returns

p~(k)=max⁡j≤kp^Sj.\tilde p_{(k)} = \max_{j \le k}\hat p_{S_j}.

Proof. For a fixed row gg, the loop at lines L3 to L5 runs kk from mm down to 1 and keeps u=max⁡l≥kT(l)(g)=MSk(g)u = \max_{l \ge k}T_{(l)}(g) = M_{S_k}(g) after line L4, by induction on m−km - k. So line L5 adds 1 to count[k][k] exactly when MSk(g)≥t(k)M_{S_k}(g) \ge t_{(k)}. Since the ranks are sorted by decreasing tt, MSk(e)=max⁡l≥kt(l)=t(k)M_{S_k}(e) = \max_{l \ge k}t_{(l)} = t_{(k)}, so count[k]/B=p^Sk[k]/B = \hat p_{S_k}. Lines L6 and L7 take the running maximum. □\square

Theorem 2 (closed testing). For every ii, p~i=max⁡{p^I:i∈I}\tilde p_i = \max\{\hat p_I : i \in I\}. So rejecting {i:p~i≤α}\{i : \tilde p_i \le \alpha\} is the closed testing procedure with local tests "reject HIH_I when p^I≤α\hat p_I \le \alpha".

Proof. Let ii have rank kk. Each tail SjS_j with j≤kj \le k contains ii, so by Lemma 1, p~i≤max⁡{p^I:i∈I}\tilde p_i \le \max\{\hat p_I : i \in I\}. Conversely, take any II that contains ii, and let jj be the smallest rank in II; then j≤kj \le k and I⊆SjI \subseteq S_j. Since the ranks are sorted by decreasing tt, MI(e)=t(j)=MSj(e)M_I(e) = t_{(j)} = M_{S_j}(e). For every gg, MI(g)≤MSj(g)M_I(g) \le M_{S_j}(g), because I⊆SjI \subseteq S_j. So every gg counted in p^I\hat p_I, with MI(g)≥t(j)M_I(g) \ge t_{(j)}, also has MSj(g)≥t(j)M_{S_j}(g) \ge t_{(j)}, and p^I≤p^Sj≤p~i\hat p_I \le \hat p_{S_j} \le \tilde p_i. Closed testing rejects HiH_i when every HIH_I with i∈Ii \in I is rejected, that is, when max⁡I∋ip^I≤α\max_{I \ni i}\hat p_I \le \alpha. □\square

The assumption. Let I0I_0 be the set of true nulls, m0=∣I0∣≥1m_0 = |I_0| \ge 1. Assume that each TjT_j with j∈I0j \in I_0 is a function Tj(z)=fj(π(z))T_j(z) = f_j(\pi(z)) of a part π(z)\pi(z) of the data, the null part, that the action of GG passes to the null part, π(gz)=gπ(z)\pi(gz) = g\pi(z), and that

gπ(Z) has the same law as π(Z) for every g∈G.(RH)g\pi(Z) \text{ has the same law as } \pi(Z) \text{ for every } g \in G. \tag{RH}

In the two-sample case, π(Z)\pi(Z) is the n×m0n \times m_0 table of the true-null variables, gg permutes its rows, and (RH) holds when these rows are exchangeable; for example when the units are independent and the vector of null variables has the same joint law in the two groups. Nothing is assumed about the other variables or about the dependence between the statistics.

Theorem 3 (strong FWER control). Under (RH), for every α∈(0,1)\alpha \in (0, 1), the procedure that rejects {i:p~i≤α}\{i : \tilde p_i \le \alpha\} has P(V≥1)≤αP(V \ge 1) \le \alpha.

Proof. By Lemma 1 the adjusted p-values are nondecreasing in the rank, so the rejected set is a set of ranks 1,…,r1, \dots, r. Let k∗k^* be the smallest rank of a true null. If any true null is rejected, then rank k∗k^* is rejected, so p^Sk∗≤p~(k∗)≤α\hat p_{S_{k^*}} \le \tilde p_{(k^*)} \le \alpha. All true nulls have rank at least k∗k^*, so I0⊆Sk∗I_0 \subseteq S_{k^*}, and by the argument in the proof of Theorem 2, with I=I0I = I_0 and j=k∗j = k^*, p^I0≤p^Sk∗\hat p_{I_0} \le \hat p_{S_{k^*}}. Hence

{V≥1}⊆{p^I0≤α}.\{V \ge 1\} \subseteq \{\hat p_{I_0} \le \alpha\}.

Now p^I0\hat p_{I_0} is the permutation p-value of the single statistic MI0(z)=max⁡j∈I0fj(π(z))M_{I_0}(z) = \max_{j \in I_0}f_j(\pi(z)), which is a function of the null part only. Under (RH), Claim 2 in the proof for the permutation test, applied to the data π(Z)\pi(Z), the group GG and the statistic max⁡j∈I0fj\max_{j \in I_0}f_j, gives P(p^I0≤α)≤αP(\hat p_{I_0} \le \alpha) \le \alpha. For completeness, the argument is this. Let g0g_0 be uniform on GG and independent of ZZ. By (RH), π(Z)\pi(Z) and g0π(Z)g_0\pi(Z) have the same law, so p^I0\hat p_{I_0} has the same law as the p-value computed from g0π(Z)g_0\pi(Z). Since {gg0:g∈G}=G\{gg_0 : g \in G\} = G, that p-value is the rank of vg0v_{g_0} among the values vg=MI0(gπ(Z))v_g = M_{I_0}(g\pi(Z)), g∈Gg \in G, divided by BB, where the rank of vhv_h is #{g:vg≥vh}\#\{g : v_g \ge v_h\}. Given ZZ, g0g_0 is uniform, and by the rank lemma at most αB\alpha B elements have rank at most αB\alpha B, so the conditional probability is at most α\alpha. □\square

The proof uses the permuted statistics of the false nulls only through the inequality MI0(g)≤MSk∗(g)M_{I_0}(g) \le M_{S_{k^*}}(g), which holds whatever they are. This is why no condition on the false nulls is needed. It also shows which condition on the true nulls is needed: (RH) for the joint law of all of them, not for each one separately.

Random permutations. If GG is replaced by the identity together with bb elements drawn independently and uniformly from GG, the count p^I0=(1+c)/(1+b)\hat p_{I_0} = (1 + c)/(1 + b) is still valid, by Claim 3 in the proof for the permutation test, and the proof of Theorem 3 goes through with that claim in place of Claim 2. Lemma 1 and Theorem 2 are statements about any table of rows, so they hold unchanged.

Proposition 4 (order). For each ii, with marginal p-value pimarg=#{g:Ti(g)≥ti}/Bp_i^{\text{marg}} = \#\{g : T_i(g) \ge t_i\}/B and single-step p-value piss=#{g:max⁡lTl(g)≥ti}/Bp_i^{\text{ss}} = \#\{g : \max_lT_l(g) \ge t_i\}/B,

pimarg≤p~i≤piss.p_i^{\text{marg}} \le \tilde p_i \le p_i^{\text{ss}}.

Proof. Let ii have rank kk. The marginal p-value is p^{i}\hat p_{\{i\}}, which is at most p~i\tilde p_i by Theorem 2. For j≤kj \le k, MSj(g)≤max⁡lTl(g)M_{S_j}(g) \le \max_lT_l(g) and t(j)≥t(k)=tit_{(j)} \ge t_{(k)} = t_i, so {g:MSj(g)≥t(j)}⊆{g:max⁡lTl(g)≥ti}\{g : M_{S_j}(g) \ge t_{(j)}\} \subseteq \{g : \max_lT_l(g) \ge t_i\}, and each term of the maximum in Lemma 1 is at most pissp_i^{\text{ss}}. □\square

So the step-down procedure rejects every hypothesis that the single-step maxT procedure rejects, and no hypothesis whose marginal permutation test does not reject.

What is measured, not proved. The tests check Lemma 1 and Theorem 2 against closed testing over all subsets, on random integer tables and on two-sample data with all 70 splits of 8 units, in exact rational arithmetic, and Proposition 4 on random tables. They measure the FWER (0.030 at α=0.05\alpha = 0.05) and the power in one correlated model. That maxT beats Holm on correlated data is an observation in that model, not a theorem; there is no general inequality between the two, since Holm uses marginal p-values and maxT uses raw statistics on possibly different scales.

Complexity

On a real RAM, given the B×mB \times m table, line L1 sorts in Θ(mlog⁡m)\Theta(m\log m), lines L2 to L5 take Θ(Bm)\Theta(Bm) and lines L6 and L7 take Θ(m)\Theta(m). Building the table dominates: each two-sample statistic costs Θ(n)\Theta(n) per variable and permutation, so the total is Θ(Bmn+mlog⁡m)\Theta(Bmn + m\log m). Rows can be streamed, so the extra space is Θ(m)\Theta(m) for the counts; the reference code keeps the table for clarity.

With full enumeration B=(nn1)B = \binom{n}{n_1}, which grows fast; in practice BB random permutations are drawn with a shuffle and the identity is added, which keeps the level exact. The naive minP version needs a permutation p-value for each statistic in each row, Θ(B2m)\Theta(B^2m) comparisons, or Θ(Bmlog⁡B)\Theta(Bm\log B) if each column is sorted once. Ge, Dudoit and Speed (2003) give an algorithm that avoids the double resampling.

Properties

  • Strong FWER control under the randomization hypothesis for the true nulls, in finite samples, with no assumption on the dependence between the statistics. Proved.
  • Closed testing. The step-down adjusted p-values equal those of closed testing with maxT permutation local tests. Proved and tested.
  • Order. For each hypothesis, marginal permutation p-value ≤\le step-down ≤\le single-step. Proved and tested.
  • Adapts to dependence. Under independence the gain over Holm is small; under strong positive dependence the adjusted p-values approach the marginal ones. The size of the gain is measured, not proved.
  • Monotone in the statistic. A larger observed statistic never gets a larger adjusted p-value.
  • Discreteness. Adjusted p-values are multiples of 1/B1/B. With BB small, as in the hand example, some levels cannot be reached exactly and the FWER is below α\alpha.

Variants and improvements

  • minP. Use min⁡j\min_j of the marginal permutation p-values in place of max⁡jTj\max_j T_j. It weighs the tests equally when the statistics have different null scales; maxT with unstandardized statistics lets variables with a large spread dominate the maximum.
  • Bootstrap version. Resample from a null-centered empirical distribution instead of permuting. This works when no permutation group fits the null, but the control is only asymptotic; Romano and Wolf (2005) give the theory.
  • Romano-Wolf step-down. Any family of intersection tests with critical values that decrease as hypotheses are removed gives a valid step-down method; maxT is the case of a permutation test of the maximum.
  • FDR and other error rates. Resampling estimates of the null law of the number of false rejections give FDR methods and procedures for kk-FWER and false discovery proportions; see the false discovery rate.

When to use it

Use it when you have the raw data, a permutation group that matches the null, and many correlated tests, such as the genes of a microarray, the voxels of an image or the end points of a trial measured on the same subjects. Under independence it is close to Holm on the same statistics, and under strong correlation or with few units it is much more powerful. When the tests are nearly independent and mm is large, the gain is small and Holm's method is cheaper. When many true effects are expected, control the FDR with the Benjamini-Hochberg procedure instead.

Pitfalls

  • Permuting variables one at a time. The method must permute whole units, so that every row of the table uses the same relabeling for all mm statistics. Separate permutations for each test destroy the dependence that the method uses.
  • A null that does not fit the group. Permutation tests the equality of the whole joint distribution of the null variables in the two groups. If the null hypotheses are about means only and the variances or correlations differ between the groups, the randomization hypothesis fails and the guarantee is lost. Equal marginal laws are not enough; the joint law of the null variables must be the same.
  • Leaving out the identity. With random permutations, add the observed labeling to the set of rows, or use (1+c)/(1+B)(1 + c)/(1 + B). A count that can be 0 is not a valid p-value.
  • Too few units. With n=8n = 8 the smallest attainable p-value is 2/702/70. No method can reject at a level below that.
  • Statistics on different scales. With maxT, use studentized statistics, or use minP.

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.

westfall_young_procedure.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/westfall-young-procedure/. The authors are listed in prov/3E4H4P.jsonl.
"""The Westfall-Young step-down maxT procedure, with exact permutation enumeration.

Input: the observed statistics t_1, ..., t_m (large values are evidence against
H_j) and the statistics recomputed on every element of a permutation group G,
one row per element, the identity included. The adjusted p-value of the
hypothesis of rank k (by decreasing t) is the running maximum over j <= k of
  #{g : max over ranks >= j of T(g) >= t_(j)} / |G|.
Rejecting the hypotheses with adjusted p-value <= alpha controls the FWER
strongly when the joint law of the true-null statistics is invariant under G.

two_sample_statistics computes |n_2 S_1 - n_1 S_2| for each variable, an integer
multiple of the absolute difference of the group means, for every split of n
integer observations into groups of sizes n_1 and n_2.
"""

import itertools
from collections.abc import Sequence
from fractions import Fraction


def max_t_adjusted(t_obs: Sequence, t_perm: Sequence[Sequence]) -> list[Fraction]:
    """Step-down maxT adjusted p-values; t_perm has one row per group element, identity included."""
    m, b = len(t_obs), len(t_perm)
    if m == 0:
        return []
    if b == 0 or any(len(row) != m for row in t_perm):
        raise ValueError("t_perm needs at least one row of length m")
    order = sorted(range(m), key=lambda j: -t_obs[j])  # @line L1
    count = [0] * m
    for row in t_perm:  # @line L2
        u = None
        for k in range(m - 1, -1, -1):  # @line L3
            v = row[order[k]]
            u = v if u is None or v > u else u  # @line L4
            if u >= t_obs[order[k]]:  # @line L5
                count[k] += 1
    adjusted = [Fraction(0)] * m
    running = Fraction(0)
    for k in range(m):  # @line L6
        running = max(running, Fraction(count[k], b))  # @line L7
        adjusted[order[k]] = running
    return adjusted  # @line L8


def single_step_max_t(t_obs: Sequence, t_perm: Sequence[Sequence]) -> list[Fraction]:
    """Single-step maxT: #{g : max_j T_j(g) >= t_i} / |G| for each i."""
    b = len(t_perm)
    maxima = [max(row) for row in t_perm]
    return [Fraction(sum(1 for v in maxima if v >= t), b) for t in t_obs]


def splits(n: int, n1: int):
    """All subsets of size n1 of range(n): the orbit of the permutation group acting on the group labels."""
    return itertools.combinations(range(n), n1)


def two_sample_statistics(data: Sequence[Sequence[int]], group1: Sequence[int]) -> list[int]:
    """|n_2 S_1 - n_1 S_2| for each column of data (rows are units), with group 1 the given row indices."""
    n, n1 = len(data), len(group1)
    n2 = n - n1
    in1 = set(group1)
    m = len(data[0])
    out = []
    for j in range(m):
        s1 = sum(data[i][j] for i in in1)
        s2 = sum(data[i][j] for i in range(n)) - s1
        out.append(abs(n2 * s1 - n1 * s2))
    return out


def westfall_young_two_sample(data: Sequence[Sequence[int]], n1: int, alpha=Fraction(1, 20)):
    """Rows 0..n1-1 are group 1. Return (reject, adjusted) by full enumeration of the splits."""
    n = len(data)
    t_obs = two_sample_statistics(data, range(n1))
    t_perm = [two_sample_statistics(data, s) for s in splits(n, n1)]
    adjusted = max_t_adjusted(t_obs, t_perm)
    return [a <= alpha for a in adjusted], adjusted
test_westfall_young_procedure.py 169 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/westfall-young-procedure/. The authors are listed in prov/3E4H4P.jsonl.

import itertools
import random
from fractions import Fraction

import pytest

from westfall_young_procedure import (
    max_t_adjusted,
    single_step_max_t,
    splits,
    two_sample_statistics,
    westfall_young_two_sample,
)


def closed_testing_brute_force(t_obs: list, t_perm: list) -> list[Fraction]:
    """Closed testing with the maxT permutation test for every intersection H_I.

    The local p-value of H_I is #{g : max_{j in I} T_j(g) >= max_{j in I} t_j} / |G|, and the adjusted
    p-value of H_i is the largest local p-value over the sets I that contain i.
    """
    m, b = len(t_obs), len(t_perm)
    adjusted = [Fraction(0)] * m
    for size in range(1, m + 1):
        for subset in itertools.combinations(range(m), size):
            t_max = max(t_obs[j] for j in subset)
            local = Fraction(sum(1 for row in t_perm if max(row[j] for j in subset) >= t_max), b)
            for i in subset:
                adjusted[i] = max(adjusted[i], local)
    return adjusted


def marginal_p_values(t_obs: list, t_perm: list) -> list[Fraction]:
    b = len(t_perm)
    return [Fraction(sum(1 for row in t_perm if row[j] >= t), b) for j, t in enumerate(t_obs)]


def holm_adjusted(p: list) -> list:
    m = len(p)
    order = sorted(range(m), key=lambda i: p[i])
    out, run = [0] * m, 0
    for k, i in enumerate(order):
        run = max(run, min(1, (m - k) * p[i]))
        out[i] = run
    return out


def random_data(rng: random.Random, n: int, m: int, shift: list, rho_scale: int = 3) -> list[list[int]]:
    """n units, m integer variables with a common unit effect; column j is shifted by shift[j] in rows 0..n/2-1."""
    rows = []
    for i in range(n):
        common = rng.gauss(0, 1) * rho_scale
        rows.append([round(10 * (common + rng.gauss(0, 1) + (shift[j] if i < n // 2 else 0))) for j in range(m)])
    return rows


def test_hand_example_two_copies() -> None:
    # Two identical variables, perfectly separated groups. Only the observed split and its mirror reach the
    # observed statistic |4 * 46 - 4 * 6| = 160, so every p-value is 2/70 = 1/35 = 0.0286.
    data = [[10, 10], [11, 11], [12, 12], [13, 13], [0, 0], [1, 1], [2, 2], [3, 3]]
    assert two_sample_statistics(data, range(4)) == [160, 160]
    reject, adjusted = westfall_young_two_sample(data, 4, Fraction(1, 20))
    assert adjusted == [Fraction(1, 35), Fraction(1, 35)]
    assert reject == [True, True]
    # Holm on the marginal permutation p-values pays for two tests: 2/35 = 0.057 > 0.05, nothing rejected.
    t_obs = two_sample_statistics(data, range(4))
    t_perm = [two_sample_statistics(data, s) for s in splits(8, 4)]
    assert holm_adjusted(marginal_p_values(t_obs, t_perm)) == [Fraction(2, 35), Fraction(2, 35)]


def test_hand_example_null_column() -> None:
    # The second variable is constant, so its statistic is 0 for every split and its adjusted p-value is 1.
    data = [[10, 5], [11, 5], [12, 5], [13, 5], [0, 5], [1, 5], [2, 5], [3, 5]]
    reject, adjusted = westfall_young_two_sample(data, 4)
    assert adjusted == [Fraction(1, 35), Fraction(1)]
    assert reject == [True, False]


def test_step_down_equals_closed_testing_on_matrices() -> None:
    rng = random.Random(1999)
    for _ in range(300):
        m = rng.randint(1, 6)
        b = rng.randint(1, 15)
        t_perm = [[rng.randint(0, 6) for _ in range(m)] for _ in range(b)]
        t_obs = t_perm[0]  # the identity row is the observed one
        assert max_t_adjusted(t_obs, t_perm) == closed_testing_brute_force(t_obs, t_perm)


def test_step_down_equals_closed_testing_on_two_sample_data() -> None:
    rng = random.Random(2003)
    for _ in range(25):
        m = rng.randint(1, 5)
        data = random_data(rng, 8, m, [rng.choice([0, 0, 2, 4]) for _ in range(m)])
        t_obs = two_sample_statistics(data, range(4))
        t_perm = [two_sample_statistics(data, s) for s in splits(8, 4)]
        assert len(t_perm) == 70
        assert max_t_adjusted(t_obs, t_perm) == closed_testing_brute_force(t_obs, t_perm)


def test_ordering_against_single_step_and_marginal() -> None:
    """marginal <= step-down <= single-step, for each hypothesis."""
    rng = random.Random(77)
    for _ in range(300):
        m = rng.randint(1, 6)
        t_perm = [[rng.randint(0, 9) for _ in range(m)] for _ in range(rng.randint(1, 12))]
        t_obs = [rng.randint(0, 9) for _ in range(m)]
        step = max_t_adjusted(t_obs, t_perm)
        single = single_step_max_t(t_obs, t_perm)
        marginal = marginal_p_values(t_obs, t_perm)
        assert all(a <= s for a, s in zip(step, single))
        assert all(mg <= a for mg, a in zip(marginal, step))
        # Adjusted p-values are monotone in the observed statistic.
        for i in range(m):
            for j in range(m):
                if t_obs[i] > t_obs[j]:
                    assert step[i] <= step[j]


def test_invalid_input() -> None:
    assert max_t_adjusted([], [[]]) == []
    with pytest.raises(ValueError):
        max_t_adjusted([1.0, 2.0], [])
    with pytest.raises(ValueError):
        max_t_adjusted([1.0, 2.0], [[1.0]])


def test_monte_carlo_fwer_and_power() -> None:
    """Correlated data, 2 true nulls and 2 false nulls, exact enumeration of the 70 splits in each run."""
    rng = random.Random(1993)
    alpha, reps = Fraction(1, 20), 500
    shift = [0, 0, 5, 5]
    fwer = 0
    rejections = {"wy": 0, "single": 0, "holm": 0}
    split_list = list(splits(8, 4))
    for _ in range(reps):
        data = random_data(rng, 8, 4, shift)
        t_obs = two_sample_statistics(data, range(4))
        t_perm = [two_sample_statistics(data, s) for s in split_list]
        wy = max_t_adjusted(t_obs, t_perm)
        single = single_step_max_t(t_obs, t_perm)
        holm = holm_adjusted(marginal_p_values(t_obs, t_perm))
        fwer += any(a <= alpha for a in wy[:2])
        rejections["wy"] += sum(a <= alpha for a in wy[2:])
        rejections["single"] += sum(a <= alpha for a in single[2:])
        rejections["holm"] += sum(a <= alpha for a in holm[2:])
    # The FWER is at most alpha = 0.05 by the theorem. With this seed it measures 0.030; the standard error
    # with 500 runs is about 0.01.
    assert fwer / reps <= 0.05 + 0.03
    # The smallest marginal permutation p-value is 2/70, so Holm needs 4 * 2/70 = 0.114 <= 0.05 and never
    # rejects. maxT rejects 28% of the false nulls here, and the step-down version at least as much as single-step.
    assert rejections["holm"] == 0
    assert rejections["wy"] >= rejections["single"] > 0
    assert 0.2 < rejections["wy"] / (2 * reps) < 0.36


def test_full_null_level_is_exact_for_the_global_test() -> None:
    """Under the complete null the identity row is uniform over the 70 rows, so P(min adjusted <= a) <= a."""
    rng = random.Random(5)
    data = random_data(rng, 8, 3, [0, 0, 0])
    split_list = list(splits(8, 4))
    # Relabeling the units by every split gives the exact distribution of the observed statistics.
    hits = 0
    for s in split_list:
        relabeled = [data[i] for i in s] + [data[i] for i in range(8) if i not in s]
        hits += min(max_t_adjusted(two_sample_statistics(relabeled, range(4)), [two_sample_statistics(relabeled, g) for g in split_list])) <= Fraction(4, 70)
    assert Fraction(hits, 70) <= Fraction(4, 70)

History

Westfall and Young collected resampling-based p-value adjustments in their 1993 book, including the step-down maxT and minP methods and the subset pivotality condition under which they control the family-wise error rate strongly. The methods became standard in genomics after Ge, Dudoit and Speed (2003) analyzed them for microarray data and gave a fast algorithm for minP, implemented with maxT in the Bioconductor package multtest. Romano and Wolf (2005) took the step-down idea apart into intersection tests with monotone critical values, which gave exact control for randomization tests and asymptotic control for bootstrap tests without subset pivotality.

References

  1. Peter H. Westfall and S. Stanley Young, Resampling-Based Multiple Testing, Examples and Methods for p-Value Adjustment, Wiley, 1993, the step-down resampling adjustments based on the maximum statistic and the minimum p-value, and the subset pivotality condition
  2. Youngchao Ge, Sandrine Dudoit and Terence P. Speed, Resampling-based multiple testing for microarray data analysis, Test 12(1) (2003), pages 1 to 77, the step-down maxT and minP algorithms, and the fast minP algorithm that avoids the double resampling of the naive method
  3. Joseph P. Romano and Michael Wolf, Exact and approximate stepdown methods for multiple hypothesis testing, Journal of the American Statistical Association 100(469) (2005), pages 94 to 108, the general step-down method with monotone critical values, exact for randomization tests and approximate with the bootstrap, without subset pivotality

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.table_given
  • 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