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
- Model
- Real RAM
- Properties
- deterministicnot exactofflineiterative
- Evidence
- Proof sketchCode in 1 languages
- Origin
- Milton Friedman, 1937
The Friedman test compares treatments in a randomized block design: each of blocks (subjects, judges, fields, data sets) gives one response to every treatment. It ranks the 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 . 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 degrees of freedom. For 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 for block and treatment , with . The blocks are independent. A common model is , with any block effects and errors that are exchangeable within each block.
Hypotheses. : within each block, the vector is exchangeable, that is, its law does not change when the treatments are permuted. In the additive model this is . The alternative is that some treatments tend to give larger responses than others.
Statistic. Let be the midrank of among , and . The tie-corrected statistic is
which without ties equals .
Null distribution. Under , given the multiset of values in each block, the assignment of each block's values to the treatments is uniform over its permutations, independently across blocks. This conditional law of is exact and gives the same probability to each of the outcomes. As with fixed, converges in law to chi-square with degrees of freedom (asymptotic).
P-values. Large is evidence against , so the p-value is one upper tail: for the asymptotic test, or the share of the outcomes with at least the observed value for the exact test. For the upper tail of is the two-sided sign test.
Rejection rule and size. Reject at level when . The exact p-value gives size at most . The chi-square p-value can be liberal or conservative for small : for , the exact probability is for , for and for .
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 it has the low efficiency of the sign test: against the paired t-test for normal errors. Its efficiency against two-way ANOVA grows with : for normal errors it is , which is at and at . A Monte Carlo run with , , block effects with standard deviation 3, unit normal errors, a shift of 1 for one treatment, samples and seed 53 gave power at , against for the Kruskal-Wallis test that ignores the blocks.
The algorithm
FRIEDMAN(blocks X_1, ..., X_b, each of length k, method)- 1
r_i ← midranks of the k values of block i, for i = 1, ..., b - 2
R_j ← r_1j + ... + r_bj, for j = 1, ..., k - 3
A ← Σ_ij r_ij^2; D ← A - b k (k + 1)^2 / 4 - 4
Q ← (k - 1) · Σ_j (R_j - b(k + 1)/2)^2 / D (Q ← 0 if D = 0) - 5
if method = asymptotic then return Q, P(χ²_{k-1} ≥ Q) - 6
count the (k!)^b outcomes by their vector of rank sums, one block at a time - 7
p ← (number of outcomes with Σ_j R_j^2 ≥ the observed value) / (k!)^b - 8
return Q, p
The code keeps doubled midranks, so is an exact fraction. Line L6 is a dynamic program: its state is the vector of column rank sums after the first blocks, and block moves each state in ways, one for each permutation of its ranks. Given the tie pattern in every block, the denominator and the total are fixed, so increases with , and line L7 compares integers.
Example
Eight judges, three wines. The scores, one row per judge with wines 1, 2 and 3, are , , , , , , and . The within-judge ranks are for five judges, for one and for two. So , against the null mean . Without ties,
The chi-square tail with 2 degrees of freedom gives . The exact count over the outcomes gives . Kendall's coefficient of concordance is . The Kruskal-Wallis test on the same 24 numbers, ignoring the judges, gives , because the differences between judges hide the differences between wines.
Ties. For the blocks , , , and , the tie-corrected statistic is . The chi-square p-value is and the exact conditional p-value is .
Two treatments. For without ties, , where is the number of blocks in which treatment 2 is larger, so is the square of the sign-test without the continuity correction. For 7 blocks with the exact Friedman p-value is , the same as the two-sided sign test.
Correctness
The proof is in proofs/correctness.md. Under each block's values are assigned to the treatments by a uniform random permutation, independently across blocks, so each of the 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 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: blocks, treatments, midranks within block (line L1), rank sums (line L2), and .
Claim 1 (fixed quantities). Given the tie pattern of every block, and do not depend on how each block's values are assigned to the treatments.
Proof. Midranks keep the sum of the ranks in each block, so each block contributes to . A permutation of a block permutes its multiset of midranks, which keeps the sum of their squares.
Claim 2 (the two forms of ). Without ties, .
Proof. Without ties each block contributes to , so . Also by Claim 1. Then , which is the stated form.
Claim 3 (the null law). Under , given the multiset of values in each block, the assignment of each block's values to the treatments is uniform over the permutations of its positions, independently across blocks.
Proof. Within block the vector 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 is a uniform random permutation of a fixed multiset of midranks.
Claim 4 (the dynamic program). After line L6 has processed blocks , the count stored for a vector is the number of the choices of one permutation for each of these blocks whose doubled column rank sums equal .
Proof. Induction on . With no blocks there is one choice, with all sums 0. Every choice for blocks is a choice for blocks followed by one of the permutations of block , which adds the permuted doubled ranks to the sums; the code makes exactly these 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.
Claim 5 (the ordering and validity). Given the tie patterns, is a nondecreasing function of , so line L7 returns under the law of Claim 3, and for every .
Proof. By Claim 1, the denominator is a fixed number and with a fixed subtracted term. If , every block is a single tie, for every outcome, and . Otherwise is a positive multiple of minus a constant, and comparing doubled sums compares , so the comparison is exact. Validity follows as for any upper tail of a discrete law: the rejection set is empty or with , given the values, and averaging keeps the bound.
Claim 6 (two treatments). For without ties, , where is the number of blocks with , and the exact Friedman p-value equals the two-sided sign-test p-value.
Proof. Each block gives ranks or , so and . Claim 2 with gives . Under the law of Claim 3, is Binomial, and exactly when . The binomial law is symmetric, so this probability is , the two-sided sign test.
The chi-square limit. Without ties, the rank vectors are independent and identically distributed under , each a uniform permutation of , with mean and covariance ; the off-diagonal value follows because each rank vector has a fixed sum. By the multivariate central limit theorem, converges in law to . Since is a projection of rank , converges to , and . With ties, the denominator is the average within-block variance of the midranks times , and the same argument applies with scaled accordingly. This gives an approximation, and the page reports how close it is for small .
Cost. Line L1 sorts blocks of size , lines L2 to L4 scan the table once. In the exact branch every column sum lies in and the sums add up to , so at most states exist, and each block moves each state in ways.
Complexity
Line L1 sorts each block: . Lines L2 to L4 take . The asymptotic test therefore costs time and space. The exact count is far more expensive: each rank sum is at most and the sums add up to a known total, so there are at most states, each updated in ways per block, for time. For and the code kept 17561 states and took 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 and .
- Kendall's W. lies in and measures the agreement of the rankings: when all blocks give the same order. Without ties, the mean of the Spearman correlations over all pairs of blocks is .
- Chi-square accuracy. Monte Carlo runs with , normal data and samples gave chi-square sizes at of for (seed 51) and for (seed 52).
Variants and improvements
- Exact tables and Monte Carlo. For small and use the exact count. Otherwise draw random within-block permutations; the share of draws with 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 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 aligned values together uses the information between blocks and gains power when is small.
- Ordered alternatives. Page's test adds 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 .
Pitfalls
- Ignoring the blocks. Analyzing blocked data with the Kruskal-Wallis test lost almost all power in the Monte Carlo run above ( against ).
- Small . The chi-square approximation gave for and , above the nominal . Use the exact count.
- Ties. Without the tie correction in the denominator, is too small and the test conservative.
- Low efficiency for small . With two or three treatments the test discards much information; for 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.
# 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 .
References
- 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
- 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)
- 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.
| Ladder | Level | What the next level needs |
|---|---|---|
| Human proof | H1 sketch |
|
| Lean | L0 no Lean part |
|
| Code (python) | I0 not checked yet |
|
| Visual | V0 none |
|
| Writing | W2 basic |
|
Tag DRZ1M4 Edit this page History Report an error Markdown