Algorithmcore
Scheffe's method
Also called Scheffe test, Scheffe simultaneous intervals.
Simultaneous confidence intervals for all contrasts of k group means, with multiplier sqrt((k-1)F). Exact coverage 1 - alpha, even for contrasts chosen after seeing the data.
- Time
- Θ(n + m·k) worst · best
- Space
- Θ(k + m) extra
- Where
- k = the number of groups; m = the number of contrasts asked for; n = the total number of observations
- Model
- Real RAM
- Properties
- deterministicexactofflineiterative
- Evidence
- Proof sketchCode in 1 languages
- Origin
- Henry Scheffé, Holbrook Working, Harold Hotelling, 1953
Scheffé's method gives confidence intervals for every contrast of group means at once, with simultaneous coverage exactly . A contrast is a weighted sum whose weights add up to zero, such as or . There are infinitely many of them, but the largest standardized contrast of the sample means is a fixed multiple of the one-way ANOVA F statistic. So one critical value from the F distribution, standard errors, covers them all. Because the guarantee holds for all contrasts, it holds also for contrasts chosen after looking at the data. The F-test rejects exactly when some contrast has an interval that excludes zero.
In plain words
After an experiment with several groups, you often look at the averages and then decide which comparison to make. You may compare one group with the average of two others because the data suggest it. A comparison chosen this way looks significant too often, because you picked the most striking one. Scheffé's method protects every comparison of this kind at once, including all the ones you might have picked. It finds how large the most striking comparison can be by chance, and it makes every interval wide enough for that worst case. The price is wider intervals than methods that protect only a short list of comparisons.
The problem
Model. Data for groups () and units , with . The model is with iid errors. with . The group sizes may differ.
Hypotheses. The family of all contrasts: for every nonzero with , , where , against the two-sided alternative. The goal is the family-wise error rate over this infinite family, in the strong sense.
Statistic. For each contrast, with the estimated standard error , and
Null distribution. Exact. By the Cauchy-Schwarz inequality, , where is the one-way ANOVA statistic, and the maximum is attained at . Applied to the centred estimates , the same identity shows that computed from the errors has the law for every and . The single contrast fixed in advance has the smaller law .
Rejection rule and size. The simultaneous intervals are
and is rejected when its interval excludes 0, that is when . The probability that all intervals cover is exactly , for equal or unequal sizes, and the family-wise error rate is exactly under and at most otherwise. For and , and .
p-value. The Scheffé adjusted p-value of a contrast is . It is never smaller than the p-value of the F-test, and it equals it for the best contrast.
Sensitivity and power. Scheffé's method has full power against the direction in which the means actually lie: the F-test rejects if and only if some contrast is significant. For any single fixed contrast it is conservative, because it pays for the whole family. For pairwise differences Tukey's test gives shorter intervals; for contrasts with many nonzero weights Scheffé's intervals are often shorter (example below).
The algorithm
SCHEFFE(groups y[1..k], contrasts c[1..m], α) ▷ k ≥ 2, N > k- 1
(n[1..k], ȳ[1..k], MSE, ν) ← sizes, means, two-pass pooled variance, ν = N - k - 2
M ← sqrt((k - 1) · F_(k-1, ν, 1-α)) ▷ the F quantile - 3
for each contrast c: ▷ check Σ c[i] = 0 and c ≠ 0 - 4
ψ ← Σ_i c[i]·ȳ[i] - 5
se ← sqrt(MSE · Σ_i c[i]² / n[i]) - 6
f ← ψ² / ((k - 1)·se²) - 7
record (ψ, se, f, P(F(k-1, ν) > f), ψ - M·se, ψ + M·se) - 8
return the records
A separate function returns the best contrast , whose equals the ANOVA . L2 brackets the quantile by doubling and bisects the F upper tail, which the shared helper computes by the incomplete beta continued fraction.
Example
The groups of the Tukey example: A = 5, 7, 6, 8, 4, B = 9, 11, 10, 12, 8, C = 6, 8, 7, 5, 9, so , , , and . The ANOVA F statistic is 8.667 with p-value 0.004687.
| contrast | (L4) | (L5) | (L6) | 95% simultaneous interval | |
|---|---|---|---|---|---|
| A - B: | 1 | 8 | 0.006196 | ||
| A - C: | 1 | 0.5 | 0.6186 | ||
| B - C: | 1 | 4.5 | 0.03482 | ||
| A vs mean of B, C: | 0.8660 | 4.1667 | 0.04225 | ||
| B vs mean of A, C: | 0.8660 | 8.1667 | 0.005772 | ||
| best: | 10.408 | 8.6667 | 0.004687 |
The best contrast is with , and its and are those of the F-test. For the pairs, Tukey's half-width is against Scheffé's . For A against the mean of B and C, Tukey's extension to contrasts gives the half-width , which includes , while Scheffé's half-width excludes 0.
Coverage by simulation. Groups of sizes 3, 5 and 8 with means and , 3000 replications, seed 4: the share of data sets in which the worst contrast misses its true value, which is the share in which some contrast misses, is 0.047 (exact value 0.05, standard error 0.004).
The cost of not adjusting. Testing the most striking contrast, the best one, with an ordinary t-test at level 0.05 has the true size , computed from the exact law:
| , | true size of the unadjusted test of the best contrast |
|---|---|
| 3, 12 | 0.1353 |
| 5, 30 | 0.4017 |
| 10, 30 | 0.8874 |
Correctness
For any numbers and any contrast, with , because . The Cauchy-Schwarz inequality gives , with equality at . With the bound is , so the largest is , which proves the equivalence with the F-test. With the bound is the between-group sum of squares of the errors, which is and independent of by the one-way ANOVA proof. So the largest centred has the law, and all intervals cover exactly when it is at most , with probability . A false rejection makes some interval miss, which gives strong control. The full proofs are in the correctness proof below.
Proof: Scheffe's intervals cover all contrasts at once with probability exactly 1 - alpha, and the F-test rejects exactly when some contrast is significantfull
We prove that the largest squared standardized contrast of the group means is , attained at the contrast with coefficients . It follows that Scheffé's intervals cover every contrast at once with probability exactly , for equal or unequal group sizes, that the contrast tests control the family-wise error rate in the strong sense, and that the one-way ANOVA F-test rejects exactly when some contrast interval excludes 0. The model is , , , with iid errors, , , and . A contrast is a nonzero with ; it estimates by , with .
Lemma 1 (the largest contrast). Let be any numbers and . For every contrast ,
with equality when , which is a contrast whenever the are not all equal.
Proof. Because , . The Cauchy-Schwarz inequality gives . Equality holds when the two vectors are proportional, , that is . These coefficients sum to , so they form a contrast if they are not all 0.
With the right side is , so , where is the one-way ANOVA statistic. The supremum over the infinite set of contrasts is attained, and best_contrast returns the maximizer.
Lemma 2 (the pivot). For every and ,
Proof. Put , the mean of the errors of group . Then , and Lemma 1 gives the maximum . The numerator is computed from the errors in place of . is the same for and for , because is constant within each group. The errors satisfy the one-way null hypothesis (all their means are 0), so by Lemma 3 of the one-way ANOVA proof, independent of , and their ratio scaled by the degrees of freedom is .
Lemma 3 (exact simultaneous coverage). Let . Then
Proof. All intervals cover if and only if for every , which holds if and only if the maximum in Lemma 2 is at most . By Lemma 2 this has probability , since the F law is continuous.
The intervals are invariant under scaling of : and . So the family is really indexed by the directions of contrasts, a sphere of dimension .
Lemma 4 (the code). L1 returns the sizes, the means, and , with the group means subtracted before squaring. L2 sets . For each contrast, L4 and L5 compute and , L6 computes , and L7 returns and the interval . The interval excludes 0 if and only if , if and only if .
Proof. Each line is its formula. The interval excludes 0 if and only if ; square both sides and divide by . The upper tail of is strictly decreasing, which gives the p-value form. The code rejects vectors that do not sum to 0, the zero vector, and .
Lemma 5 (equivalence with the F-test). The F-test at level rejects, , if and only if the Scheffé interval of some contrast excludes 0. The contrast is such a contrast whenever one exists, and its Scheffé p-value equals the F-test p-value. For every contrast, .
Proof. By Lemma 1, for every contrast, with equality at . If some interval excludes 0, then by Lemma 4. Conversely, if , then the means are not all equal, the maximizing coefficients form a contrast, its , and its interval excludes 0. The p-values follow because is decreasing.
Lemma 6 (strong family-wise error control). Reject when . For every , the probability of rejecting at least one true , over all contrasts at once, is at most . Under it is exactly .
Proof. If is true and rejected, the interval of excludes , so it misses. By Lemma 3 some interval misses with probability exactly . Under the complete null every is true, and some is rejected exactly when the F-test rejects (Lemma 5), which has probability .
Nothing in Lemmas 1 to 6 needs equal group sizes. The same argument works for any -dimensional space of estimable linear functions in a linear model with rows and columns: the supremum of the squared standardized estimates is times the regression F statistic of the hypothesis that all of them are 0, and the multiplier is .
Termination. L1 makes two passes over the observations. L2 doubles an upper bracket until the F upper tail falls below , which happens because the tail tends to 0, and then bisects at most 400 times. Each contrast costs operations and one F tail, which is a continued fraction with a fixed cap of iterations.
Theorem. Under the normal model with a common variance and any group sizes, the intervals returned by the code cover all contrasts of the group means simultaneously with probability exactly , the contrast tests control the family-wise error rate in the strong sense with error exactly under the complete null, and the F-test of one-way ANOVA rejects exactly when the interval of some contrast excludes 0, the contrast being one such contrast.
Proof. Lemmas 1 to 6.
Complexity
On a real RAM, L1 makes two passes over the observations, . Each of the contrasts costs for L4 and L5 and one F tail of bounded cost. L2 costs one quantile, at most 400 bisection steps after the bracket search. The total time is and the extra space is for the means and the records. The method needs no search over contrasts: the infinite family is handled by the closed-form maximum.
Numerical stability. subtracts each group mean before squaring, which avoids catastrophic cancellation. and the sum use exact summation of the terms (math.fsum). The check is done with a relative tolerance of , so a contrast such as given in floating point is accepted. The p-value is the upper tail computed directly, not one minus the distribution function.
Properties
- Exact simultaneous coverage. for all contrasts, for every , every set of sizes and every , under the normal model.
- Valid after data snooping. Because every contrast is covered, a contrast chosen after looking at the means keeps the guarantee.
- Equivalent to the F-test. The F-test rejects if and only if some contrast interval excludes 0. No contrast can be significant when is not.
- Scale invariance. Multiplying by a nonzero number multiplies and by the same factor, so the decision does not change.
- Conservative for small families. For a fixed finite list of contrasts the coverage is above , and the multiplier grows like with the number of groups.
- Works in any linear model. For a -dimensional space of estimable functions in with rows and columns, the multiplier is and the equivalence is with the regression F-test of that hypothesis.
Variants and improvements
- Regression bands. With the intervals for over all give the Working-Hotelling confidence band around a fitted linear regression line, .
- Factorial and block designs. In a balanced two-way ANOVA or a randomized block design, contrasts of the levels of one factor use $q = $ the number of levels minus 1 and the error degrees of freedom of that design.
- Smaller families. For contrasts fixed in advance, the Bonferroni correction with is shorter when is small; for all pairs, Tukey's test. Choose the shortest method before seeing the data; choosing after seeing the intervals is itself data snooping.
- Stepwise improvement. Applying the F-test to subsets of means in a closed family, as the closed testing principle does, rejects more hypotheses at the same family-wise error rate but gives no simultaneous intervals.
- Unequal variances. Welch-type versions replace by with estimated degrees of freedom. Their coverage is approximate.
When to use it
Use Scheffé's method when the contrasts of interest are not known before the data are seen, or when they include contrasts other than pairwise differences, and the errors are close to normal with a common variance. Use Tukey's test when only pairwise comparisons matter and the Bonferroni correction for a short list of planned contrasts. Use it also when a significant F-test must be followed by a contrast that explains it: the best contrast always exists and is significant.
Pitfalls
- Using it for pairs only. For pairwise differences Tukey's intervals are shorter; Scheffé wastes power there.
- Unadjusted tests of snooped contrasts. The true size of an ordinary t-test of the most striking contrast is 0.135 with three groups and 0.887 with ten (table above).
- Wrong degrees of freedom. The multiplier uses , the dimension of the contrast space, not the number of contrasts examined, and the error degrees of freedom of the whole analysis.
- A significant F with no significant pair. This is possible. The significant contrast then involves more than two means, and the best contrast shows which.
- Unequal variances. The pooled misstates the standard error of contrasts that weight the noisy groups heavily.
- Unchecked weights. Weights that do not add up to 0 define a different family; the code rejects them.
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/scheffe-method/. The authors are listed in prov/JFSS0K.jsonl.
"""Scheffe's method: simultaneous intervals and tests for all contrasts of k group means.
A contrast is c = (c_1, ..., c_k) with sum c_i = 0, and psi = sum c_i mu_i. Its estimate is
psi_hat = sum c_i ybar_i with standard error sqrt(MSE sum c_i^2 / n_i). Scheffe's interval is
psi_hat +- sqrt((k - 1) F_crit) se, where F_crit is the upper alpha point of F with
(k - 1, N - k) degrees of freedom. The intervals hold simultaneously for every contrast with
probability exactly 1 - alpha under the normal model, because the largest squared
standardized contrast is SSB / MSE = (k - 1) F, the one-way ANOVA statistic times k - 1.
"""
import math
from collections.abc import Sequence
from typing import NamedTuple
from stdist import f_ppf, f_sf
class Contrast(NamedTuple):
estimate: float # psi_hat
se: float # sqrt(MSE sum c_i^2 / n_i)
f: float # psi_hat^2 / ((k - 1) se^2), referred to F_(k-1, N-k)
p: float # the Scheffe adjusted p-value
lo: float
hi: float
def summary(groups: Sequence[Sequence[float]]) -> tuple[list[int], list[float], float, int]:
"""Group sizes, group means, MSE (two-pass) and its degrees of freedom N - k."""
k = len(groups)
n = [len(g) for g in groups]
if k < 2 or min(n) == 0 or sum(n) <= k:
raise ValueError("need k >= 2 nonempty groups and N > k")
means = [math.fsum(g) / len(g) for g in groups]
ssw = math.fsum((v - m) ** 2 for g, m in zip(groups, means) for v in g)
if ssw == 0.0:
raise ValueError("every group is constant, so MSE = 0")
return n, means, ssw / (sum(n) - k), sum(n) - k
def scheffe(groups: Sequence[Sequence[float]], contrasts: Sequence[Sequence[float]],
alpha: float = 0.05) -> list[Contrast]:
"""Scheffe intervals and adjusted p-values for the given contrasts."""
k = len(groups)
n, means, mse, nu = summary(groups) # @line L1
mult = math.sqrt((k - 1) * f_ppf(1.0 - alpha, k - 1, nu)) # @line L2
out = []
for c in contrasts: # @line L3
if len(c) != k or abs(math.fsum(c)) > 1e-9 * max(map(abs, c)) or not any(c):
raise ValueError("a contrast needs k coefficients that sum to 0, not all 0")
est = math.fsum(ci * m for ci, m in zip(c, means)) # @line L4
se = math.sqrt(mse * math.fsum(ci * ci / ni for ci, ni in zip(c, n))) # @line L5
f = est * est / ((k - 1) * se * se) # @line L6
out.append(Contrast(est, se, f, f_sf(f, k - 1, nu), est - mult * se, est + mult * se)) # @line L7
return out # @line L8
def best_contrast(groups: Sequence[Sequence[float]]) -> list[float]:
"""The contrast with the largest psi_hat^2 / se^2: c_i = n_i (ybar_i - ybar), up to scale."""
n, means, _, _ = summary(groups)
grand = math.fsum(ni * m for ni, m in zip(n, means)) / sum(n)
return [ni * (m - grand) for ni, m in zip(n, means)]
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)
test_scheffe_method.py 123 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/scheffe-method/. The authors are listed in prov/JFSS0K.jsonl.
import math
import random
from fractions import Fraction
import pytest
from scheffe_method import best_contrast, scheffe, summary
from stdist import f_ppf, f_sf
EXAMPLE = [[5, 7, 6, 8, 4], [9, 11, 10, 12, 8], [6, 8, 7, 5, 9]]
def exact_parts(groups: list[list[int]]) -> tuple[list[Fraction], Fraction, Fraction]:
"""Group means, SSB and MSE in exact arithmetic."""
n = [len(g) for g in groups]
means = [Fraction(sum(g), len(g)) for g in groups]
grand = sum(ni * m for ni, m in zip(n, means)) / sum(n)
ssb = sum(ni * (m - grand) ** 2 for ni, m in zip(n, means))
ssw = sum((v - m) ** 2 for g, m in zip(groups, means) for v in g)
return means, ssb, ssw / (sum(n) - len(groups))
def t2(c: list[Fraction], groups: list[list[int]], means: list[Fraction], mse: Fraction) -> Fraction:
"""psi_hat^2 / se^2 of the contrast c, exactly."""
psi = sum(ci * m for ci, m in zip(c, means))
return psi * psi / (mse * sum(ci * ci / len(g) for ci, g in zip(c, groups)))
def test_example() -> None:
res = scheffe(EXAMPLE, [[1, -1, 0], [0, 1, -1], [1, -0.5, -0.5]])
mult = math.sqrt(2.0 * f_ppf(0.95, 2, 12))
assert abs(mult - 2.7875773835545417) < 1e-9
assert [r.estimate for r in res] == [-4.0, 3.0, -2.5]
assert abs(res[0].se - 1.0) < 1e-12 and abs(res[2].se - math.sqrt(0.75)) < 1e-12
assert abs(res[0].f - 8.0) < 1e-12 and abs(res[1].f - 4.5) < 1e-12
assert abs(res[1].p - 0.03481542554547846) < 1e-10
assert abs(res[1].lo - (3.0 - mult)) < 1e-12 and res[1].lo > 0.0
assert res[2].hi < 0.0
def test_supremum_over_contrasts_is_k_minus_one_times_f() -> None:
rng = random.Random(1)
for _ in range(40):
groups = [[rng.randint(0, 30) for _ in range(rng.randint(1, 6))] for _ in range(rng.randint(2, 5))]
k, big_n = len(groups), sum(len(g) for g in groups)
if big_n <= k:
continue
means, ssb, mse = exact_parts(groups)
if mse == 0 or ssb == 0:
continue
top = ssb / mse
best = [Fraction(len(g)) * (m - sum(len(h) * mh for h, mh in zip(groups, means)) / big_n)
for g, m in zip(groups, means)]
assert sum(best) == 0 and t2(best, groups, means, mse) == top # attained, exactly
for _ in range(200): # no contrast does better
c = [Fraction(rng.randint(-9, 9)) for _ in range(k)]
c[-1] -= sum(c)
if any(c):
assert t2(c, groups, means, mse) <= top
# the float code's best contrast gives the F-test: (k - 1) F = SSB / MSE
f_test = float(ssb / (k - 1) / mse)
r = scheffe(groups, [best_contrast(groups)])[0]
assert abs(r.f - f_test) <= 1e-9 * f_test
assert abs(r.p - f_sf(f_test, k - 1, big_n - k)) < 1e-12
def test_random_search_approaches_the_bound() -> None:
rng = random.Random(2)
groups = [[rng.gauss(mu, 1.0) for _ in range(n)] for mu, n in ((0.0, 4), (0.8, 6), (0.3, 5), (1.1, 7))]
n, means, mse, _ = summary(groups)
grand = sum(ni * m for ni, m in zip(n, means)) / sum(n)
top = sum(ni * (m - grand) ** 2 for ni, m in zip(n, means)) / mse
value = lambda c: (sum(ci * m for ci, m in zip(c, means))) ** 2 / (mse * sum(ci * ci / ni for ci, ni in zip(c, n)))
c = [1.0, -1.0, 0.0, 0.0]
for _ in range(4000): # random local search over the contrast space
d = [ci + rng.gauss(0.0, 0.1) for ci in c]
mean_d = sum(d) / len(d)
d = [di - mean_d for di in d]
assert value(d) <= top * (1 + 1e-12)
if value(d) > value(c):
c = d
assert value(c) > 0.999 * top
def test_f_test_rejects_iff_some_contrast_interval_excludes_zero() -> None:
rng = random.Random(3)
for _ in range(300):
groups = [[rng.gauss(rng.choice((0.0, 0.6)), 1.0) for _ in range(4)] for _ in range(4)]
n, means, mse, nu = summary(groups)
grand = sum(means) / 4
f = sum(4 * (m - grand) ** 2 for m in means) / 3 / mse
rejects = f_sf(f, 3, nu) <= 0.05
best = scheffe(groups, [best_contrast(groups)])[0]
assert rejects == (best.lo > 0.0 or best.hi < 0.0)
pairwise = scheffe(groups, [[1 if t == i else -1 if t == j else 0 for t in range(4)]
for i in range(4) for j in range(i + 1, 4)])
if any(r.lo > 0.0 or r.hi < 0.0 for r in pairwise):
assert rejects # a significant pair implies a significant F-test, not conversely
def test_simultaneous_coverage() -> None:
rng = random.Random(4)
reps, misses = 3000, 0
mu = [0.0, 1.0, -0.5]
for _ in range(reps):
groups = [[rng.gauss(m, 2.0) for _ in range(n)] for m, n in zip(mu, (3, 5, 8))]
best = best_contrast([[v - m for v in g] for g, m in zip(groups, mu)])
r = scheffe(groups, [best])[0]
truth = sum(c * m for c, m in zip(best, mu))
misses += not (r.lo <= truth <= r.hi) # the worst contrast misses iff any contrast misses
assert abs(misses / reps - 0.05) < 4.0 * math.sqrt(0.05 * 0.95 / reps)
def test_errors() -> None:
with pytest.raises(ValueError):
scheffe(EXAMPLE, [[1, 1, 0]])
with pytest.raises(ValueError):
scheffe(EXAMPLE, [[1, -1]])
with pytest.raises(ValueError):
scheffe([[1.0, 1.0], [2.0, 2.0]], [[1, -1]])
History
Holbrook Working and Harold Hotelling used the maximum of a standardized linear function to build a confidence band around a regression line in 1929. Henry Scheffé applied the same idea to all contrasts in the analysis of variance in his 1953 Biometrika paper, which answered the question of what further inferences are valid after the F-test rejects, and compared his method with Tukey's range method. His 1959 book The Analysis of Variance presented it as the S-method, beside Tukey's T-method.
References
- Henry Scheffé, A method for judging all contrasts in the analysis of variance, Biometrika 40(1-2), 1953, pp. 87 to 110 as given by the publisher (some indexes give 87 to 104); the S-method and its comparison with Tukey's range method
- Henry Scheffé, The Analysis of Variance, Wiley, 1959, Wiley Classics Library reprint 1999, the chapter on simultaneous confidence intervals, the S-method (general locator, chapter number not confirmed)
- George Casella and Roger L. Berger, Statistical Inference, second edition, Duxbury, 2002, Chapter 11 (simultaneous estimation of contrasts in the oneway analysis of variance; chapter-level locator)
- Douglas C. Montgomery, Design and Analysis of Experiments, tenth edition, Wiley, 2019, Chapter 3 (comparisons among treatment means after the analysis of variance; chapter-level locator)
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 JFSS0K Edit this page History Report an error Markdown