Algorithm Search⌘K

Algorithmcore

Wilcoxon signed-rank test

Also called signed-rank test.

Tests whether paired differences are symmetric about zero by the sum of the ranks of their absolute values that belong to positive differences.

Time
Θ(n^3) worst · best
Space
Θ(n^2) extra
Where
n = the number of nonzero differences
Properties
deterministicexactofflineiterative
Origin
Frank Wilcoxon, 1945

The Wilcoxon signed-rank test checks whether paired differences are symmetric about zero, or about a given value μ0\mu_0. It ranks the absolute differences and adds the ranks of the positive ones. Under the null hypothesis each sign is a fair coin given the absolute values, so the sum has an exact law that depends only on the ranks, and a short dynamic program counts it. Unlike the sign test, it uses the sizes of the differences through their ranks, so it is nearly as powerful as the paired t-test for normal data and much better for heavy tails. The price is the extra assumption of symmetry: it is not a test of the median alone.

In plain words

Ten patients try two drugs, and for each one we note how much more the second drug helped. Put the differences in order of size, ignoring the sign, and number them 1, 2, 3 and so on. Then add up the numbers that belong to differences where the second drug was better.

If the drugs are equally good and the differences are spread evenly around zero, each number is equally likely to land on the plus side or the minus side, like a coin toss. So the sum is usually near half the total. A sum close to the total means the large differences all point the same way, which is hard to explain by luck. Small differences count little and large ones count much, so one big outlier counts only as the largest rank, not as its full size.

The problem

Model. D1,…,DND_1, \ldots, D_N are independent. In the paired design Di=Yi−XiD_i = Y_i - X_i; in the one-sample design Di=Xi−μ0D_i = X_i - \mu_0. Values Di=0D_i = 0 are dropped, and nn is the number of nonzero values left.

Hypotheses. H0H_0: each DiD_i has a distribution symmetric about 00, that is, DiD_i and −Di-D_i have the same law. The DiD_i may have different symmetric laws. The alternatives are "greater" (the DiD_i tend to be positive), "less" and two-sided. A shift model Di=θ+EiD_i = \theta + E_i, with EiE_i symmetric about 0, is the usual setting, and then H0H_0 is θ=0\theta = 0.

Statistic. Rank ∣D1∣,…,∣Dn∣\lvert D_1 \rvert, \ldots, \lvert D_n \rvert from 11 to nn, giving tied values the mean of their ranks (midranks). Then W+=∑i:Di>0RiW^+ = \sum_{i : D_i > 0} R_i.

Null distribution. Exact and conditional on the absolute values. Under H0H_0, given ∣D1∣,…,∣Dn∣\lvert D_1 \rvert, \ldots, \lvert D_n \rvert, the signs are independent fair coins, so W+W^+ has the law of ∑iεiRi\sum_i \varepsilon_i R_i with independent εi∈{0,1}\varepsilon_i \in \{0, 1\}, P(εi=1)=1/2P(\varepsilon_i = 1) = 1/2. Each of the 2n2^n sign vectors has probability 2−n2^{-n}. The mean is n(n+1)/4n(n + 1)/4 and the variance is n(n+1)(2n+1)/24−∑j(tj3−tj)/48n(n + 1)(2n + 1)/24 - \sum_j (t_j^3 - t_j)/48, where tjt_j are the sizes of the groups of tied ∣Di∣\lvert D_i \rvert. The law is symmetric about its mean.

P-values. With c(w)c(w) the number of sign vectors whose sum is ww:

  • Greater: Phi(w)=∑v≥wc(v)/2nP_{hi}(w) = \sum_{v \ge w} c(v) / 2^n.
  • Less: Plo(w)=∑v≤wc(v)/2nP_{lo}(w) = \sum_{v \le w} c(v) / 2^n.
  • Two-sided: p(w)=min⁡{1,2min⁡(Plo(w),Phi(w))}p(w) = \min\{1, 2 \min(P_{lo}(w), P_{hi}(w))\}. The null law is symmetric about its mean, so doubling equals P(∣W+−EW+∣≥∣w−EW+∣)P(\lvert W^+ - E W^+ \rvert \ge \lvert w - E W^+ \rvert).

Rejection rule and size. Reject at level α\alpha when p(w)≤αp(w) \le \alpha. The size is at most α\alpha for every nn, and with ties it is at most α\alpha conditionally on the tie pattern. The null law is discrete, so the size is usually below α\alpha. For n=20n = 20 without ties the two-sided test at α=0.05\alpha = 0.05 rejects for W+≤52W^+ \le 52 or W+≥158W^+ \ge 158, with size 2⋅0.024220=0.0484402 \cdot 0.024220 = 0.048440.

Sensitivity and power. The test detects a shift of a symmetric law. It also reacts to asymmetry: a skewed law with median 00 is outside H0H_0, and the test rejects it often (see Properties). In the shift model its asymptotic relative efficiency against the t-test is 3/π≈0.9553/\pi \approx 0.955 under normal errors, and at least 0.8640.864 for every symmetric continuous law (Hodges and Lehmann 1956).

The algorithm

  1. SIGNED-RANK-TEST(d_1, ..., d_n, alternative)
  2. 1drop every d_i = 0, and let n be the number of values left
  3. 2r_i ← 2 · (midrank of |d_i| among |d_1|, ..., |d_n|) ▷ doubled, so every r_i is an integer
  4. 3w ← sum of r_i over the i with d_i > 0
  5. 4T ← r_1 + ... + r_n; c[0] ← 1; c[s] ← 0 for s = 1, ..., T
  6. 5for i ← 1 to n
  7. 6for s ← T down to r_i: c[s] ← c[s] + c[s - r_i] ▷ c[s] counts subsets with sum s
  8. 7U ← c[w] + ... + c[T]; L ← c[0] + ... + c[w]
  9. 8return U / 2^n, L / 2^n or min(1, 2 · min(U, L) / 2^n) for greater, less or two-sided

The code returns W+=w/2W^+ = w/2 and the p-value. Lines L5 and L6 are the standard count of subsets by their sum; the downward loop in line L6 uses each rir_i at most once. Midranks of tied values can be half-integers, so the code doubles every rank and counts doubled sums; then all indices are integers and every count is exact. The division by 2n2^n in line L8 is one exact rational, rounded once to a float. The code also offers the normal approximation z=(W+−n(n+1)/4∓1/2)/σz = (W^+ - n(n+1)/4 \mp 1/2) / \sigma with the tie-corrected variance σ2\sigma^2 given above.

Example

Mixed signs. Take the differences 1.8,−0.6,3.1,2.4,−1.3,0.9,2.2,0.0,1.5,−0.41.8, -0.6, 3.1, 2.4, -1.3, 0.9, 2.2, 0.0, 1.5, -0.4. Line L1 drops the zero, so n=9n = 9. The absolute values in order are 0.4,0.6,0.9,1.3,1.5,1.8,2.2,2.4,3.10.4, 0.6, 0.9, 1.3, 1.5, 1.8, 2.2, 2.4, 3.1, with ranks 1 to 9. The negative differences have ranks 1, 2 and 4, so W+=45−7=38W^+ = 45 - 7 = 38. A value W+≥38W^+ \ge 38 means the negative ranks sum to at most 7, and 19 of the 512 subsets of {1,…,9}\{1, \ldots, 9\} have a sum of at most 7. So the one-sided p-value is 19/512=0.037119/512 = 0.0371 and the two-sided p-value is 19/256=0.074219/256 = 0.0742. The normal approximation gives z=1.777z = 1.777 and p=0.0756p = 0.0756 with the continuity correction, and z=1.836z = 1.836 and p=0.0663p = 0.0663 without it. The sign test on the same data gives 65/128=0.50865/128 = 0.508, because it ignores that the three negative values are among the four smallest.

The counts. For n=4n = 4 without ties the doubled ranks are 2,4,6,82, 4, 6, 8, and lines L5 and L6 give the counts of W+=0,1,…,10W^+ = 0, 1, \ldots, 10 as 1,1,1,2,2,2,2,2,1,1,11, 1, 1, 2, 2, 2, 2, 2, 1, 1, 1, which add up to 16=2416 = 2^4. With ranks 1,2.5,2.5,41, 2.5, 2.5, 4 (a tie in the middle) the doubled ranks are 2,5,5,82, 5, 5, 8, and the nonzero counts are at the doubled sums 0,2,5,7,8,10,12,13,15,18,200, 2, 5, 7, 8, 10, 12, 13, 15, 18, 20, with counts 1,1,2,2,1,2,1,2,2,1,11, 1, 2, 2, 1, 2, 1, 2, 2, 1, 1. Both lists are symmetric, as the proof requires.

Paired data. For the sleep data of Cushny and Peebles (1905) the 9 nonzero differences are all positive, so W+=45W^+ = 45, the largest value, and the two-sided p-value is 2/512=1/2562/512 = 1/256, the same as for the sign test. The normal approximation gives 0.00910.0091 with the continuity correction and 0.00760.0076 without it.

Correctness

The proof is in proofs/correctness.md. Given the absolute values, symmetry of each DiD_i makes its sign a fair coin independent of everything else, and the ranks are fixed by the absolute values. So the conditional null law of W+W^+ gives each of the 2n2^n subsets of ranks the probability 2−n2^{-n}. After step ii of line L5, c[s]c[s] is the number of subsets of {r1,…,ri}\{r_1, \ldots, r_i\} with sum ss, because a subset either leaves out rir_i (the old c[s]c[s]) or contains it (the old c[s−ri]c[s - r_i]). Line L7 then gives exact tail counts, and each p-value is valid by the argument used for the sign test.

Proof: The signed-rank test computes the exact conditional null law, and each p-value is validfull

We use the pseudocode of the page. D1,…,DND_1, \ldots, D_N are independent, and under H0H_0 each DiD_i has the same law as −Di-D_i. Let Z={i:Di≠0}Z = \{i : D_i \ne 0\}, n=∣Z∣n = \lvert Z \rvert, and A=(∣Di∣)i∈ZA = (\lvert D_i \rvert)_{i \in Z}.

Claim 1 (the signs given the sizes). Under H0H_0, conditional on ZZ and AA, the signs εi=1{Di>0}\varepsilon_i = \mathbf{1}\{D_i > 0\}, i∈Zi \in Z, are independent and each equals 1 with probability 1/21/2.

Proof. Write Di=σi∣Di∣D_i = \sigma_i \lvert D_i \rvert with σi∈{−1,0,1}\sigma_i \in \{-1, 0, 1\}. Symmetry gives (σi,∣Di∣)=d(−σi,∣Di∣)(\sigma_i, \lvert D_i \rvert) \overset{d}{=} (-\sigma_i, \lvert D_i \rvert), so for every Borel set B⊆(0,∞)B \subseteq (0, \infty), P(σi=1,∣Di∣∈B)=P(σi=−1,∣Di∣∈B)P(\sigma_i = 1, \lvert D_i \rvert \in B) = P(\sigma_i = -1, \lvert D_i \rvert \in B). Hence, given ∣Di∣\lvert D_i \rvert and Di≠0D_i \ne 0, σi\sigma_i is ±1\pm 1 with probability 1/21/2 each. The pairs (σi,∣Di∣)(\sigma_i, \lvert D_i \rvert) are independent over ii, so these conditional laws are independent. □\square

Claim 2 (the null law). Let r1,…,rnr_1, \ldots, r_n be the doubled midranks of AA, which line L2 computes and which depend only on AA. Conditional on ZZ and AA, 2W+=∑iεiri2W^+ = \sum_{i} \varepsilon_i r_i, and each of the 2n2^n vectors ε∈{0,1}n\varepsilon \in \{0, 1\}^n has probability 2−n2^{-n}. So P(2W+=s∣Z,A)=c(s)/2nP(2W^+ = s \mid Z, A) = c(s)/2^n, where c(s)c(s) is the number of subsets of the multiset {r1,…,rn}\{r_1, \ldots, r_n\} (subsets of indices) with sum ss.

Proof. Immediate from Claim 1, because the ranks are functions of AA. □\square

Claim 3 (the dynamic program). After the iteration ii of line L5, c[s]c[s] is the number of index sets J⊆{1,…,i}J \subseteq \{1, \ldots, i\} with ∑j∈Jrj=s\sum_{j \in J} r_j = s, for every 0≤s≤T0 \le s \le T.

Proof. Induction on ii. Before the loop, c[0]=1c[0] = 1 (the empty set) and c[s]=0c[s] = 0 for s>0s > 0. In iteration ii, a set J⊆{1,…,i}J \subseteq \{1, \ldots, i\} with sum ss either leaves out ii, and is counted by the old c[s]c[s], or contains ii, and then J∖{i}J \setminus \{i\} has sum s−ris - r_i and is counted by the old c[s−ri]c[s - r_i]. Line L6 visits ss in decreasing order, so when it reads c[s−ri]c[s - r_i] with ri≥1r_i \ge 1, that entry has not yet been updated in this iteration and still holds the old value. Entries with s<ris < r_i are not changed, which is correct because no set containing ii has such a sum. □\square

Claim 4 (the returned values). Line L3 gives w=2W+w = 2W^+. By Claims 2 and 3, line L7 gives U=2nP(W+≥Wobs+∣Z,A)U = 2^n P(W^+ \ge W^+_{obs} \mid Z, A) and L=2nP(W+≤Wobs+∣Z,A)L = 2^n P(W^+ \le W^+_{obs} \mid Z, A), and line L8 returns the three p-values of the page exactly.

Claim 5 (validity). For every α∈[0,1]\alpha \in [0, 1], PH0(p≤α)≤αP_{H_0}(p \le \alpha) \le \alpha for each p-value.

Proof. Condition on ZZ and AA, so that the null law of W+W^+ is the discrete law of Claim 2. For the "greater" p-value, the set {v:P(W+≥v)≤α}\{v : P(W^+ \ge v) \le \alpha\} is empty or has a least element v∗v^*, and the conditional probability of rejection is P(W+≥v∗)≤αP(W^+ \ge v^*) \le \alpha. The "less" case is the same in the other direction. For the two-sided p-value, rejection forces one of the two one-sided p-values to be at most α/2\alpha/2, and each event has conditional probability at most α/2\alpha/2. Averaging over (Z,A)(Z, A) keeps the bound. □\square

Claim 6 (symmetry and the two-sided rule). c(s)=c(T−s)c(s) = c(T - s), so the conditional law of W+W^+ is symmetric about T/4=E(W+∣Z,A)T/4 = E(W^+ \mid Z, A), and 2min⁡(Plo,Phi)2 \min(P_{lo}, P_{hi}), capped at 1, equals P(∣W+−T/4∣≥∣w/2−T/4∣)P(\lvert W^+ - T/4 \rvert \ge \lvert w/2 - T/4 \rvert).

Proof. Taking complements, J↦{1,…,n}∖JJ \mapsto \{1, \ldots, n\} \setminus J, is a bijection from the sets with sum ss to the sets with sum T−sT - s. Take w/2≤T/4w/2 \le T/4; the other case is symmetric. The event ∣W+−T/4∣≥T/4−w/2\lvert W^+ - T/4 \rvert \ge T/4 - w/2 is the union of W+≤w/2W^+ \le w/2 and W+≥T/2−w/2W^+ \ge T/2 - w/2, which by symmetry have the same probability PloP_{lo}. If w/2<T/4w/2 < T/4 the two events are disjoint and the union has probability 2Plo2 P_{lo}; also Plo≤PhiP_{lo} \le P_{hi} there. If w/2=T/4w/2 = T/4 the event is certain, and 2min⁡(Plo,Phi)≥12 \min(P_{lo}, P_{hi}) \ge 1, so the cap gives 1. □\square

Moments. Given AA, W+=∑iεiRiW^+ = \sum_i \varepsilon_i R_i with Ri=ri/2R_i = r_i/2, so EW+=12∑iRi=n(n+1)/4E W^+ = \frac{1}{2} \sum_i R_i = n(n+1)/4, because midranks keep the sum n(n+1)/2n(n+1)/2. Var⁡W+=14∑iRi2\operatorname{Var} W^+ = \frac{1}{4} \sum_i R_i^2. A tie group of size tt that covers the ranks a+1,…,a+ta + 1, \ldots, a + t has midrank m=a+(t+1)/2m = a + (t + 1)/2, and replacing the ranks by mm lowers the sum of squares by ∑k=1t(a+k−m)2=(t3−t)/12\sum_{k=1}^{t} (a + k - m)^2 = (t^3 - t)/12. So Var⁡W+=n(n+1)(2n+1)/24−∑j(tj3−tj)/48\operatorname{Var} W^+ = n(n+1)(2n+1)/24 - \sum_j (t_j^3 - t_j)/48. The tests check both formulas in exact fractions.

Cost. Line L2 sorts in O(nlog⁡n)O(n \log n). T=∑iri=n(n+1)T = \sum_i r_i = n(n+1), so line L6 does at most TT additions for each of the nn values of ii: Θ(n3)\Theta(n^3) additions in total, and the array has T+1=Θ(n2)T + 1 = \Theta(n^2) entries. Line L7 costs O(n2)O(n^2). □\square

Complexity

Lines L1 to L3 cost O(nlog⁡n)O(n \log n) for the sort. The total TT of the doubled ranks is n(n+1)n(n + 1), so line L6 runs Θ(n2)\Theta(n^2) times for each of the nn values of ii, and lines L5 and L6 cost Θ(n3)\Theta(n^3) additions. The array cc has n(n+1)+1n(n+1) + 1 entries, so the space is Θ(n2)\Theta(n^2). The counts are integers below 2n2^n, so in bit operations the cost is O(n4)O(n^4). For nn in the hundreds the normal approximation is accurate and costs O(nlog⁡n)O(n \log n).

Properties

  • Distribution-free under symmetry. The conditional null law depends only on the tie pattern, not on the law of the DiD_i.
  • Conservative and exact. The size is at most α\alpha, and the p-values are exact rationals.
  • Robust. A wild value enters W+W^+ only through its rank, which is at most nn, however large the value is.
  • Efficiency. In the shift model the efficiency against the t-test is 3/π3/\pi for normal errors and at least 0.8640.864 for every symmetric law; for heavy tails it can be arbitrarily large. A Monte Carlo run with n=20n = 20, D∼N(0.5,1)D \sim N(0.5, 1), r=2000r = 2000 samples and seed 12 gave power 0.5400.540 at α=0.05\alpha = 0.05, against 0.3870.387 for the sign test on the same samples.
  • Symmetry matters. A Monte Carlo run with n=20n = 20, r=2000r = 2000 samples of D=E−ln⁡2D = E - \ln 2, EE exponential with mean 1 (median 0 but skewed), and seed 11 rejected at α=0.05\alpha = 0.05 in 10.1%10.1\% of samples. The sign test rejected in 3.9%3.9\%. The signed-rank test is a test of symmetry about 00, not of the median.

Variants and improvements

  • Estimator and interval. The Hodges-Lehmann estimator of the center is the median of the Walsh averages (Di+Dj)/2(D_i + D_j)/2, i≤ji \le j. Inverting the test gives a confidence interval between two order statistics of the Walsh averages, an example of test-interval duality.
  • Zeros. Dropping the zeros is Wilcoxon's rule and the one the code uses. Pratt (1959) proposed ranking the zeros with the other values and then dropping them from the sum, which changes the null law.
  • Normal approximation. zz with the tie-corrected variance and a continuity correction of 1/21/2. For n=9n = 9 it gave 0.07560.0756 against the exact 0.07420.0742.
  • Paired permutation test. Using the differences themselves in place of their ranks gives the permutation test over sign changes. It is exact under the same hypothesis, but its null law depends on the data, so it cannot be tabulated.
  • More than two conditions. For blocks with more than two treatments, the Friedman test ranks within each block.

When to use it

Use it for paired data or for one sample about a point, when the differences are plausibly symmetric but maybe not normal: measurement errors, before and after scores on an interval scale, differences of logarithms. It loses little against the t-test for normal data and wins for heavy tails. If the distribution of the differences may be skewed and the question is about the median, use the sign test. If only the direction of each difference is reliable, the ranks of the sizes mean nothing, and the sign test is again the right choice.

Pitfalls

  • It is not a median test. For skewed differences with median 0 it rejected in 10.1%10.1\% of Monte Carlo samples at the nominal 5%5\%.
  • Ranks need meaningful differences. Ranking ∣Di∣\lvert D_i \rvert assumes that differences can be compared across pairs. For ordinal ratings this may be false.
  • Ties and the normal approximation. Without the tie correction to the variance, the approximation is conservative. The exact count in lines L5 and L6 handles ties with no approximation.
  • Large nn. The exact count costs Θ(n3)\Theta(n^3) time and Θ(n2)\Theta(n^2) space; for nn in the thousands use the normal approximation.
  • Two different "Wilcoxon tests". The signed-rank test is for paired data. For two independent samples, use the rank-sum test, which is the Mann-Whitney U test.

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.

wilcoxon_core.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/wilcoxon-signed-rank-test/. The authors are listed in prov/8KPP1Q.jsonl.

import math
from fractions import Fraction

ALTERNATIVES = ("two-sided", "greater", "less")


def doubled_midranks(values: list[float]) -> list[int]:
    """Return 2 x (midrank of each value), in input order. Doubling keeps midranks integers."""
    n = len(values)
    order = sorted(range(n), key=values.__getitem__)
    r2 = [0] * n
    i = 0
    while i < n:
        j = i
        while j + 1 < n and values[order[j + 1]] == values[order[i]]:
            j += 1
        for t in range(i, j + 1):
            r2[order[t]] = i + j + 2  # 2 x the mean of the ranks i + 1, ..., j + 1
        i = j + 1
    return r2


def tie_sizes(values: list[float]) -> list[int]:
    """Sizes of the groups of equal values."""
    counts: dict[float, int] = {}
    for v in values:
        counts[v] = counts.get(v, 0) + 1
    return list(counts.values())


def signed_rank_counts(r2: list[int]) -> list[int]:
    """c[s] = number of subsets of the doubled ranks r2 with sum s (a subset-sum count)."""
    total = sum(r2)
    c = [0] * (total + 1)
    c[0] = 1
    for r in r2:  # @line L5
        for s in range(total, r - 1, -1):  # @line L6
            c[s] += c[s - r]
    return c


def wilcoxon_signed_rank(
    d: list[float], alternative: str = "two-sided", mu0: float = 0.0, exact: bool = False
) -> tuple[float, float | Fraction]:
    """Wilcoxon signed-rank test of H0: D - mu0 is symmetric about 0.

    Returns (W+, p). Differences equal to mu0 are dropped. Tied |d_i| get
    midranks, and the null law is then the exact conditional law given the
    ranks: the signs are independent fair coins. "greater" is the alternative
    that D tends to exceed mu0. The two-sided p-value doubles the smaller tail;
    the null law is symmetric, so this equals P(|W+ - E W+| >= |w - E W+|).
    """
    if alternative not in ALTERNATIVES:
        raise ValueError("unknown alternative")
    kept = [v - mu0 for v in d if v != mu0]  # @line L1
    n = len(kept)
    r2 = doubled_midranks([abs(v) for v in kept])  # @line L2
    w2 = sum(r for r, v in zip(r2, kept) if v > 0)  # @line L3
    c = signed_rank_counts(r2)  # @line L4
    upper = sum(c[w2:])  # @line L7
    lower = sum(c[: w2 + 1])
    total = 2**n
    if alternative == "greater":  # @line L8
        p = Fraction(upper, total)
    elif alternative == "less":
        p = Fraction(lower, total)
    else:
        p = min(Fraction(1), Fraction(2 * min(upper, lower), total))
    return w2 / 2, (p if exact else float(p))


def wilcoxon_normal(
    d: list[float], alternative: str = "two-sided", mu0: float = 0.0, correction: bool = True
) -> tuple[float, float]:
    """Normal approximation with the tie-corrected variance. Returns (z, p)."""
    if alternative not in ALTERNATIVES:
        raise ValueError("unknown alternative")
    kept = [v - mu0 for v in d if v != mu0]
    n = len(kept)
    if n == 0:
        return 0.0, 1.0
    a = [abs(v) for v in kept]
    w = sum(r for r, v in zip(doubled_midranks(a), kept) if v > 0) / 2
    mean = n * (n + 1) / 4
    var = n * (n + 1) * (2 * n + 1) / 24 - sum(t**3 - t for t in tie_sizes(a)) / 48
    sd = math.sqrt(var)
    c = 0.5 if correction else 0.0
    if alternative == "greater":
        z = (w - mean - c) / sd
        return z, 0.5 * math.erfc(z / math.sqrt(2.0))
    if alternative == "less":
        z = (w - mean + c) / sd
        return z, 0.5 * math.erfc(-z / math.sqrt(2.0))
    z = math.copysign(max(0.0, abs(w - mean) - c), w - mean) / sd
    return z, min(1.0, math.erfc(abs(z) / math.sqrt(2.0)))
test_wilcoxon_signed_rank_test.py 121 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/wilcoxon-signed-rank-test/. The authors are listed in prov/8KPP1Q.jsonl.

import itertools
import math
import random
from fractions import Fraction

import pytest

from wilcoxon_signed_rank_test import (
    doubled_midranks, signed_rank_counts, tie_sizes, wilcoxon_normal, wilcoxon_signed_rank,
)

# Cushny and Peebles (1905), as used by Student (1908): extra hours of sleep under two drugs.
DRUG_1 = [0.7, -1.6, -0.2, -1.2, -0.1, 3.4, 3.7, 0.8, 0.0, 2.0]
DRUG_2 = [1.9, 0.8, 1.1, 0.1, -0.1, 4.4, 5.5, 1.6, 4.6, 3.4]
DIFF = [round(b - a, 1) for a, b in zip(DRUG_1, DRUG_2)]
MIXED = [1.8, -0.6, 3.1, 2.4, -1.3, 0.9, 2.2, 0.0, 1.5, -0.4]


def brute_force(d: list[float]) -> tuple[Fraction, Fraction, Fraction]:
    """W+ and its tails by listing all 2^n sign vectors on the observed |d| (midranks)."""
    kept = [v for v in d if v != 0]
    n = len(kept)
    a = [abs(v) for v in kept]
    ranks = []
    for v in a:  # midrank = (number below) + (number equal + 1) / 2
        below = sum(1 for t in a if t < v)
        equal = sum(1 for t in a if t == v)
        ranks.append(below + Fraction(equal + 1, 2))
    w = sum(r for r, v in zip(ranks, kept) if v > 0)
    upper = lower = 0
    for signs in itertools.product((0, 1), repeat=n):
        t = sum(r for r, e in zip(ranks, signs) if e)
        upper += t >= w
        lower += t <= w
    return w, Fraction(upper, 2**n), Fraction(lower, 2**n)


def test_page_examples() -> None:
    assert wilcoxon_signed_rank(DIFF, exact=True) == (45.0, Fraction(1, 256))
    assert wilcoxon_signed_rank(MIXED, exact=True) == (38.0, Fraction(19, 256))
    assert wilcoxon_signed_rank(MIXED, "greater", exact=True) == (38.0, Fraction(19, 512))
    assert wilcoxon_normal(DIFF)[1] == pytest.approx(0.0090906980, abs=1e-9)
    assert wilcoxon_normal(MIXED)[1] == pytest.approx(0.0755605675, abs=1e-9)
    assert signed_rank_counts([2, 4, 6, 8])[::2] == [1, 1, 1, 2, 2, 2, 2, 2, 1, 1, 1]
    assert signed_rank_counts([2, 5, 5, 8]) == [1, 0, 1, 0, 0, 2, 0, 2, 1, 0, 2, 0, 1, 2, 0, 2,
                                                0, 0, 1, 0, 1]


def test_against_all_sign_vectors() -> None:
    rng = random.Random(3)
    for _ in range(150):
        n = rng.randint(0, 11)
        d = [rng.choice([-1, 1]) * rng.randint(0, 6) for _ in range(n)]  # many ties and zeros
        w, upper, lower = brute_force(d)
        got_w, got_g = wilcoxon_signed_rank(d, "greater", exact=True)
        assert got_w == float(w)
        assert got_g == upper
        assert wilcoxon_signed_rank(d, "less", exact=True)[1] == lower
        assert wilcoxon_signed_rank(d, exact=True)[1] == min(Fraction(1), 2 * min(upper, lower))


def test_counts_match_subsets() -> None:
    for n in range(0, 11):
        r2 = [2 * i for i in range(1, n + 1)]
        c = signed_rank_counts(r2)
        want = [0] * len(c)
        for mask in range(2**n):
            want[sum(r for i, r in enumerate(r2) if mask >> i & 1)] += 1
        assert c == want


def test_null_mean_and_variance() -> None:
    for values in ([1, 2, 3, 4, 5, 6, 7, 8], [1, 1, 2, 3, 3, 3, 4, 5, 5]):
        n = len(values)
        r2 = doubled_midranks(values)
        c = signed_rank_counts(r2)
        total = 2**n
        mean = sum(Fraction(s, 2) * cnt for s, cnt in enumerate(c)) / total
        var = sum(Fraction(s, 2) ** 2 * cnt for s, cnt in enumerate(c)) / total - mean**2
        ties = sum(t**3 - t for t in tie_sizes(values))
        assert mean == Fraction(n * (n + 1), 4)
        assert var == Fraction(n * (n + 1) * (2 * n + 1), 24) - Fraction(ties, 48)


def test_null_is_symmetric() -> None:
    c = signed_rank_counts(doubled_midranks([1, 2, 2, 3, 5, 5, 5, 8]))
    assert c == c[::-1]


def test_critical_value_n20() -> None:
    c = signed_rank_counts([2 * i for i in range(1, 21)])
    assert Fraction(sum(c[: 2 * 52 + 1]), 2**20) <= Fraction(25, 1000)
    assert Fraction(sum(c[: 2 * 53 + 1]), 2**20) > Fraction(25, 1000)


def test_size_under_symmetry_monte_carlo() -> None:
    rng = random.Random(5)
    n, r, alpha = 15, 2000, 0.05
    hits = sum(wilcoxon_signed_rank([rng.gauss(0.0, 1.0) for _ in range(n)])[1] <= alpha
               for _ in range(r))
    assert hits / r <= alpha + 4 * math.sqrt(alpha * (1 - alpha) / r)


def test_skewed_null_median_is_not_enough() -> None:
    # Median 0 but not symmetric: the test rejects far more often than alpha.
    rng = random.Random(11)
    n, r, alpha = 20, 2000, 0.05
    hits = sum(wilcoxon_signed_rank([rng.expovariate(1.0) - math.log(2.0)
                                     for _ in range(n)])[1] <= alpha for _ in range(r))
    assert hits / r > alpha + 4 * math.sqrt(alpha * (1 - alpha) / r)


def test_edges() -> None:
    assert wilcoxon_signed_rank([0.0, 0.0], exact=True) == (0.0, 1)
    assert wilcoxon_normal([0.0]) == (0.0, 1.0)
    with pytest.raises(ValueError):
        wilcoxon_signed_rank([1.0], "both")
    assert wilcoxon_signed_rank([3.0, 4.0], mu0=3.0, exact=True) == (1.0, 1)
wilcoxon_signed_rank_test.py 12 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/wilcoxon-signed-rank-test/. The authors are listed in prov/8KPP1Q.jsonl.
"""Entry point named after the slug. The code lives in wilcoxon_core.py, because tools treat
a file whose name ends in _test.py as a test file and skip its @line markers."""

from wilcoxon_core import (
    ALTERNATIVES, doubled_midranks, signed_rank_counts, tie_sizes, wilcoxon_normal,
    wilcoxon_signed_rank,
)

__all__ = ["ALTERNATIVES", "doubled_midranks", "signed_rank_counts", "tie_sizes",
           "wilcoxon_normal", "wilcoxon_signed_rank"]

History

Frank Wilcoxon, a chemist at the American Cyanamid Company, gave the signed-rank test for paired comparisons and the rank-sum test for two samples in one paper of 1945, with tables for small samples, as quick replacements for the t-test. Hodges and Lehmann (1956) showed that the loss of efficiency against the t-test is small, which changed the view of rank tests from quick approximations to serious tools. Pratt (1959) studied the handling of zeros and ties.

References

  1. Myles Hollander, Douglas A. Wolfe and Eric Chicken, Nonparametric Statistical Methods, third edition, Wiley, 2014, Chapter 3 (the one-sample location problem), the section on the Wilcoxon signed rank test
  2. E. L. Lehmann, Nonparametrics, Statistical Methods Based on Ranks, revised edition, Springer, 2006, The chapter on paired comparisons and the one-sample problem (the signed-rank test, ties, zeros and efficiency)
  3. Frank Wilcoxon, Individual comparisons by ranking methods, Biometrics Bulletin 1(6), 1945, pp. 80 to 83 (the paired-sample test by signed ranks, with a table of exact tail probabilities)

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