Algorithm Search⌘K

Algorithmcore

Friedman test

Also called Friedman rank test.

A rank test for k treatments in a randomized block design. It ranks within each block and compares the treatment rank sums.

Time
Θ(b k log k) worst · best
Space
Θ(b k) extra
Where
b = the number of blocks; k = the number of treatments
Properties
deterministicnot exactofflineiterative
Origin
Milton Friedman, 1937

The Friedman test compares kk treatments in a randomized block design: each of bb blocks (subjects, judges, fields, data sets) gives one response to every treatment. It ranks the kk responses within each block, adds the ranks of each treatment over the blocks, and measures how far these rank sums are from their common null mean b(k+1)/2b(k+1)/2. Ranking within blocks removes the block effects completely, so large differences between blocks cost nothing. Under the null hypothesis that the treatments do not matter, the ranks in each block are a random permutation, and the statistic is approximately chi-square with k−1k - 1 degrees of freedom. For k=2k = 2 the test is the sign test.

In plain words

Eight judges taste three wines and give each one a score. Some judges give high scores to everything, others are harsh. So, for each judge, replace the scores by places: 1 for the wine that judge liked least, 3 for the one liked most. Then add up the places of each wine over all judges.

If the wines are equally good, every order of places is equally likely for every judge, and the three totals should be close to each other. If one wine gets the top place from almost every judge, its total is far above the others. The test measures how far apart the totals are, and asks how often random orders for each judge would spread them this far.

The problem

Model. The responses are XijX_{ij} for block i=1,…,bi = 1, \ldots, b and treatment j=1,…,kj = 1, \ldots, k, with k≥2k \ge 2. The blocks are independent. A common model is Xij=μ+βi+τj+EijX_{ij} = \mu + \beta_i + \tau_j + E_{ij}, with any block effects βi\beta_i and errors that are exchangeable within each block.

Hypotheses. H0H_0: within each block, the vector (Xi1,…,Xik)(X_{i1}, \ldots, X_{ik}) is exchangeable, that is, its law does not change when the treatments are permuted. In the additive model this is τ1=⋯=τk\tau_1 = \cdots = \tau_k. The alternative is that some treatments tend to give larger responses than others.

Statistic. Let rijr_{ij} be the midrank of XijX_{ij} among Xi1,…,XikX_{i1}, \ldots, X_{ik}, and Rj=∑irijR_j = \sum_i r_{ij}. The tie-corrected statistic is

Q=(k−1)∑j=1k(Rj−b(k+1)2)2∑i,jrij2−bk(k+1)24,Q = \frac{(k-1) \sum_{j=1}^{k} \left(R_j - \frac{b(k+1)}{2}\right)^2}{\sum_{i,j} r_{ij}^2 - \frac{b k (k+1)^2}{4}},

which without ties equals 12bk(k+1)∑jRj2−3b(k+1)\frac{12}{bk(k+1)} \sum_j R_j^2 - 3b(k+1).

Null distribution. Under H0H_0, given the multiset of values in each block, the assignment of each block's values to the treatments is uniform over its k!k! permutations, independently across blocks. This conditional law of QQ is exact and gives the same probability (k!)−b(k!)^{-b} to each of the (k!)b(k!)^b outcomes. As b→∞b \to \infty with kk fixed, QQ converges in law to chi-square with k−1k - 1 degrees of freedom (asymptotic).

P-values. Large QQ is evidence against H0H_0, so the p-value is one upper tail: P(χk−12≥Q)P(\chi^2_{k-1} \ge Q) for the asymptotic test, or the share of the (k!)b(k!)^b outcomes with QQ at least the observed value for the exact test. For k=2k = 2 the upper tail of QQ is the two-sided sign test.

Rejection rule and size. Reject at level α\alpha when p≤αp \le \alpha. The exact p-value gives size at most α\alpha. The chi-square p-value can be liberal or conservative for small bb: for k=3k = 3, the exact probability P(Q≥5.991)P(Q \ge 5.991) is 0.06940.0694 for b=4b = 4, 0.05210.0521 for b=6b = 6 and 0.02780.0278 for b=3b = 3.

Sensitivity and power. The test detects treatment effects that are consistent across blocks. It uses only the order within each block, so it ignores how large the differences are, and for k=2k = 2 it has the low efficiency of the sign test: 2/π2/\pi against the paired t-test for normal errors. Its efficiency against two-way ANOVA grows with kk: for normal errors it is (3/π)⋅k/(k+1)(3/\pi) \cdot k/(k+1), which is 2/π2/\pi at k=2k = 2 and 0.7160.716 at k=3k = 3. A Monte Carlo run with b=10b = 10, k=3k = 3, block effects with standard deviation 3, unit normal errors, a shift of 1 for one treatment, r=2000r = 2000 samples and seed 53 gave power 0.4420.442 at α=0.05\alpha = 0.05, against 0.0050.005 for the Kruskal-Wallis test that ignores the blocks.

The algorithm

  1. FRIEDMAN(blocks X_1, ..., X_b, each of length k, method)
  2. 1r_i ← midranks of the k values of block i, for i = 1, ..., b
  3. 2R_j ← r_1j + ... + r_bj, for j = 1, ..., k
  4. 3A ← Σ_ij r_ij^2; D ← A - b k (k + 1)^2 / 4
  5. 4Q ← (k - 1) · Σ_j (R_j - b(k + 1)/2)^2 / D (Q ← 0 if D = 0)
  6. 5if method = asymptotic then return Q, P(χ²_{k-1} ≥ Q)
  7. 6count the (k!)^b outcomes by their vector of rank sums, one block at a time
  8. 7p ← (number of outcomes with Σ_j R_j^2 ≥ the observed value) / (k!)^b
  9. 8return Q, p

The code keeps doubled midranks, so QQ is an exact fraction. Line L6 is a dynamic program: its state is the vector of column rank sums after the first ii blocks, and block i+1i + 1 moves each state in k!k! ways, one for each permutation of its ranks. Given the tie pattern in every block, the denominator DD and the total ∑jRj=bk(k+1)/2\sum_j R_j = bk(k+1)/2 are fixed, so QQ increases with ∑jRj2\sum_j R_j^2, and line L7 compares integers.

Example

Eight judges, three wines. The scores, one row per judge with wines 1, 2 and 3, are (8.2,7.1,9.0)(8.2, 7.1, 9.0), (6.5,6.1,7.4)(6.5, 6.1, 7.4), (7.9,7.0,8.8)(7.9, 7.0, 8.8), (5.5,5.9,6.8)(5.5, 5.9, 6.8), (9.1,8.0,8.7)(9.1, 8.0, 8.7), (6.8,6.0,7.7)(6.8, 6.0, 7.7), (7.2,6.9,7.0)(7.2, 6.9, 7.0) and (8.0,7.5,8.5)(8.0, 7.5, 8.5). The within-judge ranks are (2,1,3)(2, 1, 3) for five judges, (1,2,3)(1, 2, 3) for one and (3,1,2)(3, 1, 2) for two. So R=(17,9,22)R = (17, 9, 22), against the null mean b(k+1)/2=16b(k+1)/2 = 16. Without ties,

Q=128⋅3⋅4(172+92+222)−3⋅8⋅4=106.75−96=10.75.Q = \frac{12}{8 \cdot 3 \cdot 4}(17^2 + 9^2 + 22^2) - 3 \cdot 8 \cdot 4 = 106.75 - 96 = 10.75.

The chi-square tail with 2 degrees of freedom gives p=0.00463p = 0.00463. The exact count over the 68=16796166^8 = 1679616 outcomes gives p=221/93312=0.00237p = 221/93312 = 0.00237. Kendall's coefficient of concordance is W=Q/(b(k−1))=0.672W = Q/(b(k-1)) = 0.672. The Kruskal-Wallis test on the same 24 numbers, ignoring the judges, gives p=0.097p = 0.097, because the differences between judges hide the differences between wines.

Ties. For the blocks (1,2,2)(1, 2, 2), (3,3,1)(3, 3, 1), (2,1,3)(2, 1, 3), (1,2,3)(1, 2, 3) and (1,1,2)(1, 1, 2), the tie-corrected statistic is Q=42/17=2.471Q = 42/17 = 2.471. The chi-square p-value is 0.2910.291 and the exact conditional p-value is 29/81=0.35829/81 = 0.358.

Two treatments. For k=2k = 2 without ties, Q=(S−b/2)2/(b/4)Q = (S - b/2)^2/(b/4), where SS is the number of blocks in which treatment 2 is larger, so QQ is the square of the sign-test zz without the continuity correction. For 7 blocks with S=5S = 5 the exact Friedman p-value is 29/6429/64, the same as the two-sided sign test.

Correctness

The proof is in proofs/correctness.md. Under H0H_0 each block's values are assigned to the treatments by a uniform random permutation, independently across blocks, so each of the (k!)b(k!)^b outcomes has the same probability given the values. The dynamic program of line L6 counts these outcomes by their rank-sum vectors by induction on the number of blocks. The statistic is an increasing function of ∑jRj2\sum_j R_j^2 given the tie pattern, so the exact p-value is the upper tail of a discrete law and is valid. The chi-square limit follows from the central limit theorem for the sum over blocks of the independent rank vectors.

Proof: The Friedman statistic, its exact conditional p-value, and why both are validfull

We use the pseudocode of the page: bb blocks, kk treatments, midranks rijr_{ij} within block ii (line L1), rank sums RjR_j (line L2), and rˉ=(k+1)/2\bar r = (k+1)/2.

Claim 1 (fixed quantities). Given the tie pattern of every block, ∑jRj=bk(k+1)/2\sum_j R_j = bk(k+1)/2 and A=∑i,jrij2A = \sum_{i,j} r_{ij}^2 do not depend on how each block's values are assigned to the treatments.

Proof. Midranks keep the sum of the ranks 1,…,k1, \ldots, k in each block, so each block contributes k(k+1)/2k(k+1)/2 to ∑jRj\sum_j R_j. A permutation of a block permutes its multiset of midranks, which keeps the sum of their squares. □\square

Claim 2 (the two forms of QQ). Without ties, Q=12bk(k+1)∑jRj2−3b(k+1)Q = \frac{12}{bk(k+1)} \sum_j R_j^2 - 3b(k+1).

Proof. Without ties each block contributes ∑l=1kl2=k(k+1)(2k+1)/6\sum_{l=1}^{k} l^2 = k(k+1)(2k+1)/6 to AA, so D=A−bk(k+1)2/4=bk(k+1)(k−1)/12D = A - bk(k+1)^2/4 = bk(k+1)(k-1)/12. Also ∑j(Rj−brˉ)2=∑jRj2−kb2rˉ2\sum_j (R_j - b\bar r)^2 = \sum_j R_j^2 - k b^2 \bar r^2 by Claim 1. Then Q=12bk(k+1)(∑jRj2−b2k(k+1)24)Q = \frac{12}{bk(k+1)} \left(\sum_j R_j^2 - \frac{b^2 k (k+1)^2}{4}\right), which is the stated form. □\square

Claim 3 (the null law). Under H0H_0, given the multiset of values in each block, the assignment of each block's values to the treatments is uniform over the k!k! permutations of its positions, independently across blocks.

Proof. Within block ii the vector (Xi1,…,Xik)(X_{i1}, \ldots, X_{ik}) is exchangeable, so given its multiset of values every arrangement of these values over the treatments has the same conditional probability. The blocks are independent, so these conditional laws are independent. The midranks of a block depend only on its multiset of values and the arrangement, so the rank vector of block ii is a uniform random permutation of a fixed multiset of midranks. □\square

Claim 4 (the dynamic program). After line L6 has processed blocks 1,…,i1, \ldots, i, the count stored for a vector s=(s1,…,sk)s = (s_1, \ldots, s_k) is the number of the (k!)i(k!)^i choices of one permutation for each of these blocks whose doubled column rank sums equal ss.

Proof. Induction on ii. With no blocks there is one choice, with all sums 0. Every choice for blocks 1,…,i+11, \ldots, i + 1 is a choice for blocks 1,…,i1, \ldots, i followed by one of the k!k! permutations of block i+1i + 1, which adds the permuted doubled ranks to the sums; the code makes exactly these k!k! moves from each state and adds the counts. Permutations of the positions are used even when a block has ties, so tied values give repeated vectors, each counted once per permutation, matching the uniform law of Claim 3. □\square

Claim 5 (the ordering and validity). Given the tie patterns, QQ is a nondecreasing function of ∑jRj2\sum_j R_j^2, so line L7 returns P(Q≥Qobs)P(Q \ge Q_{obs}) under the law of Claim 3, and PH0(p≤α)≤αP_{H_0}(p \le \alpha) \le \alpha for every α\alpha.

Proof. By Claim 1, the denominator DD is a fixed number and ∑j(Rj−brˉ)2=∑jRj2−kb2rˉ2\sum_j (R_j - b \bar r)^2 = \sum_j R_j^2 - k b^2 \bar r^2 with a fixed subtracted term. If D=0D = 0, every block is a single tie, Q=0Q = 0 for every outcome, and p=1p = 1. Otherwise QQ is a positive multiple of ∑jRj2\sum_j R_j^2 minus a constant, and comparing doubled sums compares 4∑jRj24\sum_j R_j^2, so the comparison is exact. Validity follows as for any upper tail of a discrete law: the rejection set is empty or {Q≥q∗}\{Q \ge q^*\} with P(Q≥q∗)≤αP(Q \ge q^*) \le \alpha, given the values, and averaging keeps the bound. □\square

Claim 6 (two treatments). For k=2k = 2 without ties, Q=(2S−b)2/bQ = (2S - b)^2 / b, where SS is the number of blocks with Xi2>Xi1X_{i2} > X_{i1}, and the exact Friedman p-value equals the two-sided sign-test p-value.

Proof. Each block gives ranks (1,2)(1, 2) or (2,1)(2, 1), so R2=b+SR_2 = b + S and R2−3b/2=S−b/2=−(R1−3b/2)R_2 - 3b/2 = S - b/2 = -(R_1 - 3b/2). Claim 2 with k=2k = 2 gives Q=126b⋅2(S−b/2)2=(2S−b)2/bQ = \frac{12}{6b} \cdot 2 (S - b/2)^2 = (2S - b)^2/b. Under the law of Claim 3, SS is Binomial(b,1/2)(b, 1/2), and Q≥QobsQ \ge Q_{obs} exactly when ∣S−b/2∣≥∣Sobs−b/2∣\lvert S - b/2 \rvert \ge \lvert S_{obs} - b/2 \rvert. The binomial law is symmetric, so this probability is min⁡{1,2min⁡(P(S≤Sobs),P(S≥Sobs))}\min\{1, 2 \min(P(S \le S_{obs}), P(S \ge S_{obs}))\}, the two-sided sign test. □\square

The chi-square limit. Without ties, the rank vectors ρi=(ri1,…,rik)\rho_i = (r_{i1}, \ldots, r_{ik}) are independent and identically distributed under H0H_0, each a uniform permutation of 1,…,k1, \ldots, k, with mean rˉ1\bar r \mathbf{1} and covariance Σ=k(k+1)12(I−1k11⊤)\Sigma = \frac{k(k+1)}{12}(I - \frac{1}{k} \mathbf{1}\mathbf{1}^{\top}); the off-diagonal value −(k+1)/12-(k+1)/12 follows because each rank vector has a fixed sum. By the multivariate central limit theorem, Z=b−1/2∑i(ρi−rˉ1)Z = b^{-1/2} \sum_i (\rho_i - \bar r \mathbf{1}) converges in law to N(0,Σ)N(0, \Sigma). Since I−1k11⊤I - \frac{1}{k}\mathbf{1}\mathbf{1}^{\top} is a projection of rank k−1k - 1, 12k(k+1)∥Z∥2\frac{12}{k(k+1)} \lVert Z \rVert^2 converges to χk−12\chi^2_{k-1}, and 12k(k+1)∥Z∥2=12bk(k+1)∑j(Rj−brˉ)2=Q\frac{12}{k(k+1)} \lVert Z \rVert^2 = \frac{12}{bk(k+1)} \sum_j (R_j - b\bar r)^2 = Q. With ties, the denominator D/(b(k−1))D/(b(k-1)) is the average within-block variance of the midranks times k/(k−1)k/(k-1), and the same argument applies with Σ\Sigma scaled accordingly. This gives an approximation, and the page reports how close it is for small bb.

Cost. Line L1 sorts bb blocks of size kk, lines L2 to L4 scan the table once. In the exact branch every column sum lies in [b,bk][b, bk] and the sums add up to bk(k+1)/2bk(k+1)/2, so at most (bk+1)k−1(bk + 1)^{k-1} states exist, and each block moves each state in k!k! ways. □\square

Complexity

Line L1 sorts each block: Θ(bklog⁡k)\Theta(b k \log k). Lines L2 to L4 take Θ(bk)\Theta(bk). The asymptotic test therefore costs Θ(bklog⁡k)\Theta(b k \log k) time and Θ(bk)\Theta(bk) space. The exact count is far more expensive: each rank sum is at most bkbk and the sums add up to a known total, so there are at most (bk+1)k−1(bk + 1)^{k-1} states, each updated in k!k! ways per block, for O(b⋅k!⋅(bk+1)k−1)O(b \cdot k! \cdot (bk+1)^{k-1}) time. For b=10b = 10 and k=4k = 4 the code kept 17561 states and took 0.680.68 s of CPU time.

Properties

  • Block effects vanish. Ranks within a block do not change when a constant is added to the whole block, or when the block is transformed by any increasing function.
  • Distribution-free. Given the tie pattern of each block, the exact null law depends only on bb and kk.
  • Kendall's W. W=Q/(b(k−1))W = Q / (b(k-1)) lies in [0,1][0, 1] and measures the agreement of the bb rankings: W=1W = 1 when all blocks give the same order. Without ties, the mean of the Spearman correlations over all pairs of blocks is (bW−1)/(b−1)(bW - 1)/(b - 1).
  • Chi-square accuracy. Monte Carlo runs with k=3k = 3, normal data and r=4000r = 4000 samples gave chi-square sizes at α=0.05\alpha = 0.05 of 0.04280.0428 for b=5b = 5 (seed 51) and 0.04850.0485 for b=20b = 20 (seed 52).

Variants and improvements

  • Exact tables and Monte Carlo. For small bb and kk use the exact count. Otherwise draw random within-block permutations; the share of draws with QQ at least the observed value, with one added to the numerator and the denominator, is a valid permutation test p-value.
  • The F form. Iman and Davenport (1980) proposed F=(b−1)Q/(b(k−1)−Q)F = (b - 1) Q / (b(k-1) - Q) referred to an F distribution, which is usually closer to the exact law than the chi-square.
  • Aligned ranks. Subtracting a block estimate (such as the block mean) and ranking all bkbk aligned values together uses the information between blocks and gains power when kk is small.
  • Ordered alternatives. Page's test adds jRjj R_j over the treatments and has more power against a monotone trend.
  • Incomplete blocks. Durbin's test extends the method to balanced incomplete block designs.
  • Follow-up comparisons. After a significant result, pairwise comparisons of rank sums need a multiple-comparison correction.

When to use it

Use it for repeated measures or blocked experiments with three or more treatments when the responses are ordinal, skewed, or on scales that differ from block to block: judges with their own scale, subjects with different baselines, algorithms compared over many data sets. For two treatments use the signed-rank test, which also uses the size of each difference. For independent groups use the Kruskal-Wallis test. When the errors are close to normal, two-way ANOVA is more powerful, especially for small kk.

Pitfalls

  • Ignoring the blocks. Analyzing blocked data with the Kruskal-Wallis test lost almost all power in the Monte Carlo run above (0.0050.005 against 0.4420.442).
  • Small bb. The chi-square approximation gave P(Q≥5.991)=0.0694P(Q \ge 5.991) = 0.0694 for k=3k = 3 and b=4b = 4, above the nominal 0.050.05. Use the exact count.
  • Ties. Without the tie correction in the denominator, QQ is too small and the test conservative.
  • Low efficiency for small kk. With two or three treatments the test discards much information; for k=2k = 2 it is only the sign test.
  • Missing values. The test needs a complete table. Dropping incomplete blocks can bias the result; designs with planned missing cells need Durbin's test or a model.

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.

friedman_core.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/friedman-test/. The authors are listed in prov/DRZ1M4.jsonl.

import itertools
import math
from fractions import Fraction

from stdist import chi2_sf


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 q_statistic(blocks: list[list[float]]) -> Fraction:
    """The tie-corrected Friedman statistic as an exact Fraction.

    Q = (k - 1) sum_j (R_j - b (k + 1) / 2)^2 / (sum_ij r_ij^2 - b k (k + 1)^2 / 4).
    Without ties it equals 12 / (b k (k + 1)) sum_j R_j^2 - 3 b (k + 1).
    """
    b, k = len(blocks), len(blocks[0])
    r2 = [doubled_midranks(row) for row in blocks]  # @line L1
    col = [Fraction(sum(row[j] for row in r2), 2) for j in range(k)]  # @line L2
    a = sum(Fraction(v * v, 4) for row in r2 for v in row)  # @line L3
    c = Fraction(b * k * (k + 1) ** 2, 4)
    if a == c:
        return Fraction(0)  # every block is one tie: no information
    centre = Fraction(b * (k + 1), 2)
    return (k - 1) * sum((s - centre) ** 2 for s in col) / (a - c)  # @line L4


def rank_sum_counts(blocks: list[list[float]]) -> dict[tuple[int, ...], int]:
    """Number of the (k!)^b within-block orderings that give each vector of doubled
    column rank sums. A DP over the blocks; the state is the vector of sums so far."""
    k = len(blocks[0])
    counts: dict[tuple[int, ...], int] = {(0,) * k: 1}
    for row in blocks:
        perms = list(itertools.permutations(doubled_midranks(row)))
        nxt: dict[tuple[int, ...], int] = {}
        for sums, cnt in counts.items():
            for perm in perms:
                key = tuple(s + r for s, r in zip(sums, perm))
                nxt[key] = nxt.get(key, 0) + cnt
        counts = nxt
    return counts


def friedman(
    blocks: list[list[float]], method: str = "asymptotic", exact: bool = False
) -> tuple[float, float | Fraction]:
    """Friedman test of H0: within each block the k treatments are exchangeable.

    blocks[i][j] is the response of treatment j in block i. Returns (Q, p).
    method "asymptotic" uses the upper tail of chi-square with k - 1 degrees of
    freedom. method "exact" computes the permutation null: each block's ranks
    are permuted in all k! ways, independently across blocks, and the p-value is
    the share of the (k!)^b outcomes with sum_j R_j^2 at least the observed one.
    """
    if len(blocks) == 0 or len(blocks[0]) < 2 or any(len(r) != len(blocks[0]) for r in blocks):
        raise ValueError("need b >= 1 blocks of the same length k >= 2")
    if method not in ("asymptotic", "exact"):
        raise ValueError("unknown method")
    q = q_statistic(blocks)
    b, k = len(blocks), len(blocks[0])
    if method == "asymptotic":  # @line L5
        return float(q), chi2_sf(float(q), k - 1)
    observed = [sum(doubled_midranks(row)[j] for row in blocks) for j in range(k)]
    target = sum(s * s for s in observed)
    counts = rank_sum_counts(blocks)  # @line L6
    hits = sum(cnt for sums, cnt in counts.items() if sum(s * s for s in sums) >= target)
    p = Fraction(hits, math.factorial(k) ** b)  # @line L7
    return float(q), (p if exact else float(p))  # @line L8
stdist.py 238 lines
# SPDX-License-Identifier: MIT
# Shared helper of the pe1 statistics pages of https://algorithm.tamnd.com/. The authors are listed in prov/.
"""Normal, chi-square, t and F distribution functions in the standard library.

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

import math
from statistics import NormalDist

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


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


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


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


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


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


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


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


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

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


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


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


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


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


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


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


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


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

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


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


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


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

from friedman_core import doubled_midranks, friedman, q_statistic, rank_sum_counts

__all__ = ["doubled_midranks", "friedman", "q_statistic", "rank_sum_counts"]
test_friedman_test.py 120 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/friedman-test/. The authors are listed in prov/DRZ1M4.jsonl.

import itertools
import math
import random
from fractions import Fraction

import pytest

from friedman_test import doubled_midranks, friedman, q_statistic, rank_sum_counts

ROWS = [[8.2, 7.1, 9.0], [6.5, 6.1, 7.4], [7.9, 7.0, 8.8], [5.5, 5.9, 6.8],
        [9.1, 8.0, 8.7], [6.8, 6.0, 7.7], [7.2, 6.9, 7.0], [8.0, 7.5, 8.5]]


def midranks(row: list[float]) -> list[Fraction]:
    return [sum(1 for t in row if t < v) + Fraction(sum(1 for t in row if t == v) + 1, 2) for v in row]


def q_direct(blocks: list[list[float]]) -> Fraction:
    """Q = (b (k - 1) / SS_W-total) x sum of squared deviations of the column mean ranks,
    computed from Fractions with no doubling: an independent formula."""
    b, k = len(blocks), len(blocks[0])
    ranks = [midranks(row) for row in blocks]
    mean = Fraction(k + 1, 2)
    col_means = [sum(r[j] for r in ranks) / b for j in range(k)]
    ss_total = sum((v - mean) ** 2 for r in ranks for v in r)
    if ss_total == 0:
        return Fraction(0)
    return b * b * (k - 1) * sum((m - mean) ** 2 for m in col_means) / ss_total


def brute_force_p(blocks: list[list[float]]) -> Fraction:
    """Permute every block in all k! ways (positions, so tied values count separately)."""
    k = len(blocks[0])
    q_obs = q_direct(blocks)
    perms = [list(itertools.permutations(row)) for row in blocks]
    hits = total = 0
    for choice in itertools.product(*perms):
        total += 1
        hits += q_direct([list(row) for row in choice]) >= q_obs
    assert total == math.factorial(k) ** len(blocks)
    return Fraction(hits, total)


def test_page_examples() -> None:
    assert q_statistic(ROWS) == Fraction(43, 4)
    assert friedman(ROWS, "exact", exact=True)[1] == Fraction(221, 93312)
    assert friedman(ROWS)[1] == pytest.approx(0.0046309187, abs=1e-9)
    rows2 = [[1, 2, 2], [3, 3, 1], [2, 1, 3], [1, 2, 3], [1, 1, 2]]
    assert q_statistic(rows2) == Fraction(42, 17)
    assert friedman(rows2, "exact", exact=True)[1] == Fraction(29, 81)


def test_two_formulas_agree() -> None:
    rng = random.Random(1)
    for _ in range(300):
        b, k = rng.randint(1, 6), rng.randint(2, 5)
        blocks = [[rng.randint(0, 3) for _ in range(k)] for _ in range(b)]
        assert q_statistic(blocks) == q_direct(blocks)


def test_untied_closed_form() -> None:
    rng = random.Random(2)
    for _ in range(100):
        b, k = rng.randint(1, 8), rng.randint(2, 6)
        blocks = [rng.sample(range(100), k) for _ in range(b)]
        col = [sum(Fraction(r, 2) for r in (doubled_midranks(row)[j] for row in blocks)) for j in range(k)]
        want = Fraction(12, b * k * (k + 1)) * sum(c * c for c in col) - 3 * b * (k + 1)
        assert q_statistic(blocks) == want


def test_exact_against_all_permutations() -> None:
    rng = random.Random(3)
    for _ in range(30):
        b, k = rng.choice([(1, 3), (2, 3), (3, 3), (4, 2), (5, 2), (2, 4), (3, 2)])
        blocks = [[rng.randint(0, 3) for _ in range(k)] for _ in range(b)]
        assert friedman(blocks, "exact", exact=True)[1] == brute_force_p(blocks)


def test_two_treatments_is_the_sign_test() -> None:
    rng = random.Random(4)
    for _ in range(100):
        b = rng.randint(1, 12)
        blocks = [rng.sample(range(50), 2) for _ in range(b)]  # no ties within a block
        s = sum(1 for x, y in blocks if y > x)
        assert q_statistic(blocks) == Fraction((2 * s - b) ** 2, b)  # (S - b/2)^2 / (b/4)
        tail = sum(math.comb(b, j) for j in range(min(s, b - s) + 1))
        assert friedman(blocks, "exact", exact=True)[1] == min(Fraction(1), Fraction(2 * tail, 2**b))


def test_exact_critical_values_k3() -> None:
    def tail(b: int, q: Fraction) -> Fraction:
        counts = rank_sum_counts([[1, 2, 3]] * b)
        hits = sum(c for s, c in counts.items()
                   if Fraction(12, 12 * b) * sum(Fraction(x, 2) ** 2 for x in s) - 12 * b >= q)
        return Fraction(hits, 6**b)

    assert tail(6, Fraction(7)) == Fraction(25, 864)  # 0.0289, the 5% point for b = 6
    assert tail(4, Fraction(5991, 1000)) == Fraction(5, 72)  # 0.0694: chi-square is liberal here
    assert sum(rank_sum_counts([[1, 2, 3]] * 5).values()) == 6**5


def test_chi_square_size_monte_carlo() -> None:
    rng = random.Random(52)
    r, alpha = 1500, 0.05
    hits = sum(friedman([[rng.gauss(0.0, 1.0) for _ in range(3)] for _ in range(20)])[1] <= alpha
               for _ in range(r))
    assert abs(hits / r - alpha) <= 4 * math.sqrt(alpha * (1 - alpha) / r)


def test_edges() -> None:
    with pytest.raises(ValueError):
        friedman([])
    with pytest.raises(ValueError):
        friedman([[1.0]])
    with pytest.raises(ValueError):
        friedman([[1.0, 2.0], [1.0]])
    assert friedman([[1.0, 1.0], [2.0, 2.0]], "exact", exact=True) == (0.0, 1)

History

Milton Friedman, then a young economist, published the test in 1937. He replaced each row of a two-way table by its ranks and proposed the chi-square approximation for the spread of the rank sums; a short correction followed in 1939. Kendall and Babington Smith (1939) studied the same statistic as a measure of agreement among rankers, the coefficient of concordance WW.

References

  1. Myles Hollander, Douglas A. Wolfe and Eric Chicken, Nonparametric Statistical Methods, third edition, Wiley, 2014, Chapter 7 (the two-way layout), the section on the Friedman test for general alternatives
  2. E. L. Lehmann, Nonparametrics, Statistical Methods Based on Ranks, revised edition, Springer, 2006, The chapter on blocked comparisons of several treatments (the Friedman test and its ties)
  3. Milton Friedman, The use of ranks to avoid the assumption of normality implicit in the analysis of variance, Journal of the American Statistical Association 32(200), 1937, pp. 675 to 701 (the rank statistic for a two-way table and its chi-square approximation)

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