Algorithm Search⌘K

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
Properties
deterministicexactofflineiterative
Origin
Henry Scheffé, Holbrook Working, Harold Hotelling, 1953

Scheffé's method gives confidence intervals for every contrast of kk group means at once, with simultaneous coverage exactly 1−α1 - \alpha. A contrast is a weighted sum ∑ciμi\sum c_i\mu_i whose weights add up to zero, such as μ1−μ2\mu_1 - \mu_2 or μ1−12(μ2+μ3)\mu_1 - \frac12(\mu_2 + \mu_3). 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, (k−1)F(k−1,ν,1−α)\sqrt{(k-1)F_{(k-1,\nu,1-\alpha)}} 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 yijy_{ij} for groups i=1,…,ki = 1, \dots, k (k≥2k \ge 2) and units j=1,…,ni≥1j = 1, \dots, n_i \ge 1, with N=∑ni>kN = \sum n_i > k. The model is yij=μi+eijy_{ij} = \mu_i + e_{ij} with iid N(0,σ2)N(0, \sigma^2) errors. MSE=1ν∑i,j(yij−yˉi)2MSE = \frac1\nu\sum_{i,j}(y_{ij} - \bar y_i)^2 with ν=N−k\nu = N - k. The group sizes may differ.

Hypotheses. The family of all contrasts: for every nonzero c∈Rkc \in \mathbb R^k with ∑ci=0\sum c_i = 0, Hc:ψc=0H_c: \psi_c = 0, where ψc=∑iciμi\psi_c = \sum_i c_i\mu_i, 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, ψ^c=∑iciyˉi\hat\psi_c = \sum_i c_i\bar y_i with the estimated standard error se^c=MSE∑ici2/ni\widehat{\mathrm{se}}_c = \sqrt{MSE\sum_i c_i^2/n_i}, and

fc=ψ^c2(k−1) se^c2.f_c = \frac{\hat\psi_c^2}{(k - 1)\,\widehat{\mathrm{se}}_c^2} .

Null distribution. Exact. By the Cauchy-Schwarz inequality, max⁡cψ^c2/se^c2=SSB/MSE=(k−1)F\max_c\hat\psi_c^2/\widehat{\mathrm{se}}_c^2 = SSB/MSE = (k - 1)F, where FF is the one-way ANOVA statistic, and the maximum is attained at ci=ni(yˉi−yˉ)c_i = n_i(\bar y_i - \bar y). Applied to the centred estimates ψ^c−ψc\hat\psi_c - \psi_c, the same identity shows that max⁡cfc\max_c f_c computed from the errors has the Fk−1,νF_{k-1,\nu} law for every μ\mu and σ\sigma. The single contrast fixed in advance has the smaller law tν2/(k−1)t_\nu^2/(k-1).

Rejection rule and size. The simultaneous intervals are

ψ^c±M se^c,M=(k−1)F(k−1,ν,1−α),\hat\psi_c \pm M\,\widehat{\mathrm{se}}_c, \qquad M = \sqrt{(k - 1)F_{(k-1,\nu,1-\alpha)}},

and HcH_c is rejected when its interval excludes 0, that is when fc>F(k−1,ν,1−α)f_c > F_{(k-1,\nu,1-\alpha)}. The probability that all intervals cover is exactly 1−α1 - \alpha, for equal or unequal sizes, and the family-wise error rate is exactly α\alpha under μ1=⋯=μk\mu_1 = \dots = \mu_k and at most α\alpha otherwise. For k=3k = 3 and ν=12\nu = 12, F(2,12,0.95)=3.885294F_{(2,12,0.95)} = 3.885294 and M=2.78758M = 2.78758.

p-value. The Scheffé adjusted p-value of a contrast is pc=P(Fk−1,ν>fc)p_c = P(F_{k-1,\nu} > f_c). 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

  1. SCHEFFE(groups y[1..k], contrasts c[1..m], α) ▷ k ≥ 2, N > k
  2. 1(n[1..k], ȳ[1..k], MSE, ν) ← sizes, means, two-pass pooled variance, ν = N - k
  3. 2M ← sqrt((k - 1) · F_(k-1, ν, 1-α)) ▷ the F quantile
  4. 3for each contrast c: ▷ check Σ c[i] = 0 and c ≠ 0
  5. 4ψ ← Σ_i c[i]·ȳ[i]
  6. 5se ← sqrt(MSE · Σ_i c[i]² / n[i])
  7. 6f ← ψ² / ((k - 1)·se²)
  8. 7record (ψ, se, f, P(F(k-1, ν) > f), ψ - M·se, ψ + M·se)
  9. 8return the records

A separate function returns the best contrast ci=ni(yˉi−yˉ)c_i = n_i(\bar y_i - \bar y), whose ff equals the ANOVA FF. 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 n=5n = 5, yˉ=(6,10,7)\bar y = (6, 10, 7), MSE=2.5MSE = 2.5, ν=12\nu = 12 and M=2.78758M = 2.78758. The ANOVA F statistic is 8.667 with p-value 0.004687.

contrast cc ψ^c\hat\psi_c (L4) se^c\widehat{\mathrm{se}}_c (L5) fcf_c (L6) pcp_c 95% simultaneous interval
A - B: (1,−1,0)(1, -1, 0) −4-4 1 8 0.006196 [−6.788,−1.212][-6.788, -1.212]
A - C: (1,0,−1)(1, 0, -1) −1-1 1 0.5 0.6186 [−3.788,1.788][-3.788, 1.788]
B - C: (0,1,−1)(0, 1, -1) 33 1 4.5 0.03482 [0.212,5.788][0.212, 5.788]
A vs mean of B, C: (1,−12,−12)(1, -\frac12, -\frac12) −2.5-2.5 0.8660 4.1667 0.04225 [−4.914,−0.086][-4.914, -0.086]
B vs mean of A, C: (−12,1,−12)(-\frac12, 1, -\frac12) 3.53.5 0.8660 8.1667 0.005772 [1.086,5.914][1.086, 5.914]
best: (−253,353,−103)(-\frac{25}3, \frac{35}3, -\frac{10}3) 43.33343.333 10.408 8.6667 0.004687 [14.319,72.347][14.319, 72.347]

The best contrast is ni(yˉi−yˉ)n_i(\bar y_i - \bar y) with yˉ=23/3\bar y = 23/3, and its ff and pp are those of the F-test. For the pairs, Tukey's half-width is 2.6682.668 against Scheffé's 2.7882.788. For A against the mean of B and C, Tukey's extension to contrasts gives the half-width 3.77293⋅2.5/5⋅12∑∣ci∣=2.6683.77293 \cdot \sqrt{2.5/5} \cdot \frac12\sum|c_i| = 2.668, which includes −2.5-2.5, while Scheffé's half-width 2.4142.414 excludes 0.

Coverage by simulation. Groups of sizes 3, 5 and 8 with means 0,1,−0.50, 1, -0.5 and σ=2\sigma = 2, 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 P((k−1)Fk−1,ν>t(ν,0.975)2)P\big((k - 1)F_{k-1,\nu} > t_{(\nu,0.975)}^2\big), computed from the exact law:

kk, ν\nu 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 did_i and any contrast, ∑cidi=∑(ci/ni)⋅ni(di−dˉ)\sum c_id_i = \sum (c_i/\sqrt{n_i})\cdot\sqrt{n_i}(d_i - \bar d) with dˉ=∑nidi/N\bar d = \sum n_id_i/N, because ∑ci=0\sum c_i = 0. The Cauchy-Schwarz inequality gives (∑cidi)2/∑(ci2/ni)≤∑ni(di−dˉ)2(\sum c_id_i)^2/\sum(c_i^2/n_i) \le \sum n_i(d_i - \bar d)^2, with equality at ci=ni(di−dˉ)c_i = n_i(d_i - \bar d). With di=yˉid_i = \bar y_i the bound is SSBSSB, so the largest fcf_c is FF, which proves the equivalence with the F-test. With di=yˉi−μid_i = \bar y_i - \mu_i the bound is the between-group sum of squares of the errors, which is σ2χk−12\sigma^2\chi^2_{k-1} and independent of MSEMSE by the one-way ANOVA proof. So the largest centred fcf_c has the Fk−1,νF_{k-1,\nu} law, and all intervals cover exactly when it is at most F(k−1,ν,1−α)F_{(k-1,\nu,1-\alpha)}, with probability 1−α1 - \alpha. 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 SSB/MSE=(k−1)FSSB/MSE = (k - 1)F, attained at the contrast with coefficients ni(yˉi−yˉ)n_i(\bar y_i - \bar y). It follows that Scheffé's intervals cover every contrast at once with probability exactly 1−α1 - \alpha, 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 yij=μi+eijy_{ij} = \mu_i + e_{ij}, i=1,…,ki = 1, \dots, k, j=1,…,ni≥1j = 1, \dots, n_i \ge 1, with iid N(0,σ2)N(0, \sigma^2) errors, N=∑ni>kN = \sum n_i > k, ν=N−k\nu = N - k, MSE=SSW/νMSE = SSW/\nu and yˉ=∑niyˉi/N\bar y = \sum n_i\bar y_i/N. A contrast is a nonzero c∈Rkc \in \mathbb R^k with ∑ici=0\sum_i c_i = 0; it estimates ψc=∑ciμi\psi_c = \sum c_i\mu_i by ψ^c=∑ciyˉi\hat\psi_c = \sum c_i\bar y_i, with se^c2=MSE∑ci2/ni\widehat{\mathrm{se}}_c^2 = MSE\sum c_i^2/n_i.

Lemma 1 (the largest contrast). Let d1,…,dkd_1, \dots, d_k be any numbers and dˉ=∑nidi/N\bar d = \sum n_id_i/N. For every contrast cc,

(∑icidi)2∑ici2/ni≤∑ini(di−dˉ)2,\frac{\big(\sum_i c_id_i\big)^2}{\sum_i c_i^2/n_i} \le \sum_i n_i(d_i - \bar d)^2,

with equality when ci=ni(di−dˉ)c_i = n_i(d_i - \bar d), which is a contrast whenever the did_i are not all equal.

Proof. Because ∑ci=0\sum c_i = 0, ∑cidi=∑ci(di−dˉ)=∑icini⋅ni(di−dˉ)\sum c_id_i = \sum c_i(d_i - \bar d) = \sum_i \frac{c_i}{\sqrt{n_i}}\cdot\sqrt{n_i}(d_i - \bar d). The Cauchy-Schwarz inequality gives (∑cidi)2≤∑ci2/ni⋅∑ni(di−dˉ)2(\sum c_id_i)^2 \le \sum c_i^2/n_i\cdot\sum n_i(d_i - \bar d)^2. Equality holds when the two vectors are proportional, ci/ni∝ni(di−dˉ)c_i/\sqrt{n_i} \propto \sqrt{n_i}(d_i - \bar d), that is ci∝ni(di−dˉ)c_i \propto n_i(d_i - \bar d). These coefficients sum to ∑nidi−Ndˉ=0\sum n_id_i - N\bar d = 0, so they form a contrast if they are not all 0. □\square

With di=yˉid_i = \bar y_i the right side is SSBSSB, so sup⁡cψ^c2/se^c2=SSB/MSE=(k−1)F\sup_c\hat\psi_c^2/\widehat{\mathrm{se}}_c^2 = SSB/MSE = (k - 1)F, where FF 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 μ\mu and σ\sigma,

max⁡c(ψ^c−ψc)2se^c2∼(k−1)Fk−1,ν.\max_c \frac{(\hat\psi_c - \psi_c)^2}{\widehat{\mathrm{se}}_c^2} \sim (k - 1)F_{k-1,\nu}.

Proof. Put di=yˉi−μid_i = \bar y_i - \mu_i, the mean of the errors of group ii. Then ψ^c−ψc=∑cidi\hat\psi_c - \psi_c = \sum c_id_i, and Lemma 1 gives the maximum ∑ni(di−dˉ)2/MSE\sum n_i(d_i - \bar d)^2/MSE. The numerator is SSBSSB computed from the errors e=y−μe = y - \mu in place of yy. MSEMSE is the same for yy and for ee, because μ\mu 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, SSB(e)/σ2∼χk−12SSB(e)/\sigma^2 \sim \chi^2_{k-1} independent of SSW/σ2∼χν2SSW/\sigma^2 \sim \chi^2_\nu, and their ratio scaled by the degrees of freedom is Fk−1,νF_{k-1,\nu}. □\square

Lemma 3 (exact simultaneous coverage). Let M=(k−1)F(k−1,ν,1−α)M = \sqrt{(k - 1)F_{(k-1,\nu,1-\alpha)}}. Then

P(ψc∈[ψ^c−Mse^c, ψ^c+Mse^c] for every contrast c)=1−α.P\big(\psi_c \in [\hat\psi_c - M\widehat{\mathrm{se}}_c,\ \hat\psi_c + M\widehat{\mathrm{se}}_c] \text{ for every contrast } c\big) = 1 - \alpha .

Proof. All intervals cover if and only if (ψ^c−ψc)2/se^c2≤M2(\hat\psi_c - \psi_c)^2/\widehat{\mathrm{se}}_c^2 \le M^2 for every cc, which holds if and only if the maximum in Lemma 2 is at most M2M^2. By Lemma 2 this has probability P(Fk−1,ν≤F(k−1,ν,1−α))=1−αP(F_{k-1,\nu} \le F_{(k-1,\nu,1-\alpha)}) = 1 - \alpha, since the F law is continuous. □\square

The intervals are invariant under scaling of cc: ψ^tc=tψ^c\hat\psi_{tc} = t\hat\psi_c and se^tc=∣t∣se^c\widehat{\mathrm{se}}_{tc} = |t|\widehat{\mathrm{se}}_c. So the family is really indexed by the directions of contrasts, a sphere of dimension k−2k - 2.

Lemma 4 (the code). L1 returns the sizes, the means, MSEMSE and ν\nu, with the group means subtracted before squaring. L2 sets MM. For each contrast, L4 and L5 compute ψ^c\hat\psi_c and se^c\widehat{\mathrm{se}}_c, L6 computes fc=ψ^c2/((k−1)se^c2)f_c = \hat\psi_c^2/((k - 1)\widehat{\mathrm{se}}_c^2), and L7 returns pc=P(Fk−1,ν>fc)p_c = P(F_{k-1,\nu} > f_c) and the interval ψ^c±Mse^c\hat\psi_c \pm M\widehat{\mathrm{se}}_c. The interval excludes 0 if and only if fc>F(k−1,ν,1−α)f_c > F_{(k-1,\nu,1-\alpha)}, if and only if pc<αp_c < \alpha.

Proof. Each line is its formula. The interval excludes 0 if and only if ∣ψ^c∣>Mse^c|\hat\psi_c| > M\widehat{\mathrm{se}}_c; square both sides and divide by (k−1)se^c2(k - 1)\widehat{\mathrm{se}}_c^2. The upper tail of FF is strictly decreasing, which gives the p-value form. The code rejects vectors that do not sum to 0, the zero vector, N≤kN \le k and MSE=0MSE = 0. □\square

Lemma 5 (equivalence with the F-test). The F-test at level α\alpha rejects, F>F(k−1,ν,1−α)F > F_{(k-1,\nu,1-\alpha)}, if and only if the Scheffé interval of some contrast excludes 0. The contrast ci=ni(yˉi−yˉ)c_i = n_i(\bar y_i - \bar y) is such a contrast whenever one exists, and its Scheffé p-value equals the F-test p-value. For every contrast, pc≥pFp_c \ge p_F.

Proof. By Lemma 1, fc≤SSB/((k−1)MSE)=Ff_c \le SSB/((k-1)MSE) = F for every contrast, with equality at ci=ni(yˉi−yˉ)c_i = n_i(\bar y_i - \bar y). If some interval excludes 0, then F≥fc>F(k−1,ν,1−α)F \ge f_c > F_{(k-1,\nu,1-\alpha)} by Lemma 4. Conversely, if F>F(k−1,ν,1−α)F > F_{(k-1,\nu,1-\alpha)}, then the means are not all equal, the maximizing coefficients form a contrast, its fc=Ff_c = F, and its interval excludes 0. The p-values follow because P(Fk−1,ν>⋅)P(F_{k-1,\nu} > \cdot) is decreasing. □\square

Lemma 6 (strong family-wise error control). Reject Hc:ψc=0H_c: \psi_c = 0 when pc<αp_c < \alpha. For every μ\mu, the probability of rejecting at least one true HcH_c, over all contrasts at once, is at most α\alpha. Under μ1=⋯=μk\mu_1 = \dots = \mu_k it is exactly α\alpha.

Proof. If HcH_c is true and rejected, the interval of cc excludes 0=ψc0 = \psi_c, so it misses. By Lemma 3 some interval misses with probability exactly α\alpha. Under the complete null every HcH_c is true, and some HcH_c is rejected exactly when the F-test rejects (Lemma 5), which has probability α\alpha. □\square

Nothing in Lemmas 1 to 6 needs equal group sizes. The same argument works for any qq-dimensional space of estimable linear functions a⊤ba^\top b in a linear model y=Xb+ey = Xb + e with nn rows and kk columns: the supremum of the squared standardized estimates is qq times the regression F statistic of the hypothesis that all of them are 0, and the multiplier is qF(q,n−k,1−α)\sqrt{qF_{(q,n-k,1-\alpha)}}.

Termination. L1 makes two passes over the NN observations. L2 doubles an upper bracket until the F upper tail falls below α\alpha, which happens because the tail tends to 0, and then bisects at most 400 times. Each contrast costs O(k)O(k) 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 1−α1 - \alpha, the contrast tests control the family-wise error rate in the strong sense with error exactly α\alpha under the complete null, and the F-test of one-way ANOVA rejects exactly when the interval of some contrast excludes 0, the contrast ci=ni(yˉi−yˉ)c_i = n_i(\bar y_i - \bar y) being one such contrast.

Proof. Lemmas 1 to 6. ■\blacksquare

Complexity

On a real RAM, L1 makes two passes over the NN observations, Θ(N)\Theta(N). Each of the mm contrasts costs Θ(k)\Theta(k) 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 Θ(N+mk)\Theta(N + mk) and the extra space is Θ(k+m)\Theta(k + m) 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. MSEMSE subtracts each group mean before squaring, which avoids catastrophic cancellation. ψ^c\hat\psi_c and the sum ∑ci2/ni\sum c_i^2/n_i use exact summation of the terms (math.fsum). The check ∑ci=0\sum c_i = 0 is done with a relative tolerance of 10−910^{-9}, so a contrast such as (1,−13,−13,−13)(1, -\frac13, -\frac13, -\frac13) 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. 1−α1 - \alpha for all contrasts, for every NN, every set of sizes and every σ\sigma, 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 FF is not.
  • Scale invariance. Multiplying cc by a nonzero number multiplies ψ^c\hat\psi_c and se^c\widehat{\mathrm{se}}_c 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 1−α1 - \alpha, and the multiplier grows like k\sqrt{k} with the number of groups.
  • Works in any linear model. For a qq-dimensional space of estimable functions in y=Xb+ey = Xb + e with nn rows and kk columns, the multiplier is qF(q,n−k,1−α)\sqrt{qF_{(q,n-k,1-\alpha)}} and the equivalence is with the regression F-test of that hypothesis.

Variants and improvements

  • Regression bands. With q=2q = 2 the intervals for b0+b1xb_0 + b_1x over all xx give the Working-Hotelling confidence band around a fitted linear regression line, y^(x)±2F(2,n−2,1−α) se^(x)\hat y(x) \pm \sqrt{2F_{(2,n-2,1-\alpha)}}\,\widehat{\mathrm{se}}(x).
  • 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 mm contrasts fixed in advance, the Bonferroni correction with t(ν,1−α/(2m))t_{(\nu,1-\alpha/(2m))} is shorter when mm 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 MSE∑ci2/niMSE\sum c_i^2/n_i by ∑ci2si2/ni\sum c_i^2s_i^2/n_i 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 k−1k - 1, the dimension of the contrast space, not the number of contrasts examined, and the error degrees of freedom ν\nu 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 MSEMSE 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.

scheffe_method.pyI0RawGitHub
# 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

  1. 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
  2. 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)
  3. 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)
  4. 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.

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