Definitioncore
Factorial design
Also called full factorial experiment, 2^k factorial design.
An experiment that runs every combination of the levels of several factors, so that main effects and all interactions can be estimated.
A factorial design runs every combination of the levels of several factors. With factors at two levels each it has runs and is called a design. Fisher and Yates used factorial designs at Rothamsted for two reasons. First, every run is used to estimate every effect, so a factorial experiment gets the precision of a one-factor-at-a-time experiment with fewer runs. Second, it estimates interactions, which tell whether the effect of one factor depends on the level of another. In a two-level design the contrast columns are orthogonal vectors, so the effects are estimated independently, and Yates's algorithm computes all of them in additions. That algorithm is the fast Walsh-Hadamard transform.
Definition
Let factors have levels. A full factorial design runs each of the treatment combinations times, in an order chosen at random as in a randomized experiment. A two-way ANOVA with equal cell counts is the analysis of a full factorial design with two factors.
Two-level designs. Code the low level of each factor as and the high level as , and name the factors . A run is named by the lower-case letters of its factors at the high level, and is the run with all factors low. In standard order the runs are numbered , and factor (with as ) is high in run when bit of is 1. So the order is . Write for the level of factor in run , and for the response of run (the mean of its replicates).
For a set of factors, with bit mask , the contrast column has the entry in run , and . The contrast and the effect of are
and is the grand mean. In the order of the masks the effects are . The main effect is the mean response at high minus the mean response at low . The two-factor interaction is half of the difference between the effect at high and the effect at low . Higher interactions repeat this one level up.
The model. In the regression notation of ordinary least squares, let have the columns , so rows and columns including the intercept . This is the saturated model: it fits every run mean exactly. The coefficient is half the effect , because a factor moves two units from to .
Theorem 1 (orthogonality). For all sets and , if and otherwise. So and the least squares estimates are . With replicates of each run and independent errors of variance , the effect estimates are uncorrelated and . The sum of squares of effect is , and
Proof. Since , , where is the symmetric difference. Let be nonempty and pick . The map that changes the level of factor is a bijection on the runs, and it changes the sign of , so . With this gives for , and . Stack the replicates: the full model matrix has replaced by and by , where is the vector of run means. So , that is , with covariance , and has variance . Because is square and invertible, the fitted values are the run means, so the between-run sum of squares is .
Three consequences follow.
- Each is the drop in the residual sum of squares when is added to any model that contains other columns , because the columns are orthogonal. So the type I, II and III sums of squares of the two-way ANOVA agree, and with each effect has the regression F-test on degrees of freedom.
- Every effect uses all runs. With and , from 8 runs. A one-factor-at-a-time experiment that runs each times estimates by the mean of minus the mean of , with variance . It needs , so 16 runs, for the same precision, and it estimates no interaction.
- is the Sylvester-Hadamard matrix with some columns negated (Theorem 2), so its columns are the codewords of the Hadamard code in form, and is a Walsh-Hadamard transform matrix.
Theorem 2 (Yates's algorithm is the fast Walsh-Hadamard transform). The algorithm below returns the contrasts in the order of the masks . In matrix form , where is the Sylvester-Hadamard matrix, a Kronecker product power with , and . It does additions and subtractions, against for the direct sums.
YATES(y[0..N-1]) ▷ N = 2^k, runs in standard order- 1
col ← y - 2
repeat k times: - 3
sums ← (col[2i] + col[2i+1] for i = 0, ..., N/2 - 1) - 4
diffs ← (col[2i+1] - col[2i] for i = 0, ..., N/2 - 1) - 5
col ← sums followed by diffs - 6
return col ▷ col[s] = c_S; effect = col[s]/(N/2), mean = col[0]/N
Proof. First the matrix form. If is bit of , then , so and .
Now the passes. A pass reads positions and and writes position (the sum) and position (the difference). In bits, it removes the lowest bit of the position, moves the other bits down by one, and puts a new top bit . The value written is : for the sum, for the second minus the first. Claim: after passes, the entry at the position whose bits, from low to high, are equals
For this is itself. Pass removes the lowest bit , sums over it with the weight , and puts on top, which is the claim for . After passes the position is and the entry is . Each pass does additions and subtractions.
Each pass is one sparse factor of followed by a perfect shuffle, with the same read and write pattern in every pass. The in-place form on the fast Walsh-Hadamard transform page uses butterflies at distances instead. Since and , the data come back as , so setting small contrasts to zero before this inverse gives fitted values. On integer data all the arithmetic is exact. The test file checks Theorem 2 against the direct sums for in exact arithmetic, and checks for .
Without replication. With the model is saturated and no degrees of freedom are left for error. The usual answers are to replicate, to pool high-order interactions that are assumed zero, or to plot the effects on normal probability paper, where pure noise lies on a line (Daniel, 1959; cited, not proved here).
Blocking. When a block holds only half of the runs, the experimenter confounds a high-order interaction with the blocks: in a design, the runs with go in one block and the runs with in the other. Then cannot be estimated, but by Theorem 1 every other column is orthogonal to the block column, so the other effects are unchanged. To run only one of the blocks is to run a fractional factorial design.
Examples and non-examples
Example: a pilot plant experiment. This is the pilot plant example of Box, Hunter and Hunter, Chapter 5, with temperature (), concentration () and catalyst (). The yields in standard order are , and Yates's algorithm gives:
| run | pass 1 | pass 2 | pass 3 | effect | estimate | ||
|---|---|---|---|---|---|---|---|
| (1) | 60 | 132 | 254 | 514 | I | 64.25 (mean) | |
| a | 72 | 122 | 260 | 92 | A | 23 | 1058 |
| b | 54 | 135 | 26 | -20 | B | -5 | 50 |
| ab | 68 | 125 | 66 | 6 | AB | 1.5 | 4.5 |
| c | 52 | 12 | -10 | 6 | C | 1.5 | 4.5 |
| ac | 83 | 14 | -10 | 40 | AC | 10 | 200 |
| bc | 45 | 31 | 2 | 0 | BC | 0 | 0 |
| abc | 80 | 35 | 4 | 2 | ABC | 0.5 | 0.5 |
The sums of squares add to , the total sum of squares about the mean, as Theorem 1 says. The large effects are , and . The temperature effect is with catalyst low and with catalyst high, and the interaction is . So the main effect of the catalyst, , does not mean that the catalyst has no effect: it changes the effect of temperature. With one replicate there is no error estimate, so the decision about which effects are real needs replicates or a probability plot. The test file checks every number in the table.
Example: the model matrix of a design. In standard order the columns are
with . A balanced two-way ANOVA of two factors at two levels with observations per cell is this design, and its sums of squares are .
Example: the design as a code and as an array. The runs, written as 0/1 vectors, are all of , so the design is an orthogonal array of strength : every set of columns contains every combination of levels equally often. A fractional design keeps only part of this strength.
Non-example: one factor at a time. Start at and change alone: the estimate is . In the pilot plant the temperature effect is at low catalyst and at high catalyst, so the experiment that holds low never sees the larger effect. It also needs twice the runs for the same precision (Theorem 1).
Non-example: a lost run. If run is lost, the 7 remaining runs do not form a factorial design. Every column is at , so every pair of distinct columns now has inner product . The estimates are correlated, the sum of squares of an effect depends on the other terms in the model, and the analysis needs the type I, II and III choices of the unbalanced two-way ANOVA.
Related definitions
- Two-way ANOVA: the analysis of a two-factor factorial; balance gives orthogonal sums of squares.
- Fractional factorial design: runs a fraction of a design and aliases effects in a known pattern.
- Plackett-Burman design: two-level main-effect designs whose run size is a multiple of 4, built from Hadamard matrices.
- Orthogonal array: the general frame; a full design is an orthogonal array of strength .
- Walsh-Hadamard transform and fast Walsh-Hadamard transform: the contrasts are a Walsh-Hadamard transform, and Yates's algorithm is a fast one.
- Response surface methodology: starts with a two-level factorial, often with center points, to fit a first-order model and find the direction of improvement.
- Optimal experimental design: for the first-order model with columns on the cube , a two-level design of runs whose model matrix has , such as the design, is D-optimal among designs of runs. Each diagonal entry of is at most , and Hadamard's inequality bounds the determinant of by the product of its diagonal entries.
Code
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/factorial-design/. The authors are listed in prov/NCP43N.jsonl.
"""Two-level full factorial designs 2^k and Yates's algorithm.
Runs are in standard order: run x = 0, ..., 2^k - 1 sets factor i (A = 0, B = 1, ...)
to its high level when bit i of x is 1, so the order is (1), a, b, ab, c, ac, bc, abc, ...
The contrast of the effect with factor set S (bit mask s) is sum_x y_x prod_{i in S} (+1 if
bit i of x is set, else -1). Yates's algorithm computes all 2^k contrasts in k passes:
each pass writes the sums of consecutive pairs into the first half and the differences
(second minus first) into the second half. It is a fast Walsh-Hadamard transform, so it
costs k 2^k additions instead of the 4^k of the direct sums.
"""
from string import ascii_uppercase
def runs(k: int) -> list[tuple[int, ...]]:
"""The 2^k runs in standard order, as tuples of -1 / +1 levels for A, B, ..."""
return [tuple(1 if (x >> i) & 1 else -1 for i in range(k)) for x in range(2 ** k)]
def effect_name(s: int) -> str:
"""The label of the effect with bit mask s: 0 -> I, 1 -> A, 3 -> AB, 5 -> AC."""
return "".join(ascii_uppercase[i] for i in range(s.bit_length()) if (s >> i) & 1) or "I"
def yates(y: list[float]) -> list[float]:
"""All 2^k contrasts of responses y in standard order, in effect order I, A, B, AB, C, ..."""
n = len(y)
k = n.bit_length() - 1
if n == 0 or n != 1 << k:
raise ValueError("the number of runs must be a power of two")
col = list(y) # @line L1
for _ in range(k): # @line L2
half = n // 2
sums = [col[2 * i] + col[2 * i + 1] for i in range(half)] # @line L3
diffs = [col[2 * i + 1] - col[2 * i] for i in range(half)] # @line L4
col = sums + diffs # @line L5
return col # @line L6
def contrasts_direct(y: list[float]) -> list[float]:
"""The same contrasts by their definition, 4^k operations: the reference for tests."""
n = len(y)
out = []
for s in range(n):
total = 0
for x, v in enumerate(y):
sign = 1
for i in range(n.bit_length() - 1):
if (s >> i) & 1:
sign *= 1 if (x >> i) & 1 else -1
total += sign * v
out.append(total)
return out
def effects(y: list[float]) -> dict[str, float]:
"""Effect estimates: contrast / (N / 2) for each effect, and the grand mean for I."""
n = len(y)
c = yates(y)
return {effect_name(s): (c[s] / n if s == 0 else 2.0 * c[s] / n) for s in range(n)}
test_factorial_design.py 125 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/factorial-design/. The authors are listed in prov/NCP43N.jsonl.
import random
from fractions import Fraction
import pytest
from factorial_design import contrasts_direct, effect_name, effects, runs, yates
EXAMPLE = [60, 72, 54, 68, 52, 83, 45, 80] # (1), a, b, ab, c, ac, bc, abc
def sylvester(k: int) -> list[list[int]]:
"""The 2^k x 2^k Sylvester-Hadamard matrix, H_(s, x) = (-1)^popcount(s & x)."""
n = 2 ** k
return [[-1 if bin(s & x).count("1") % 2 else 1 for x in range(n)] for s in range(n)]
def test_example() -> None:
assert yates(EXAMPLE) == [514, 92, -20, 6, 6, 40, 0, 2]
e = effects(EXAMPLE)
assert e["I"] == 64.25 and e["A"] == 23.0 and e["B"] == -5.0 and e["AC"] == 10.0
assert e["AB"] == 1.5 and e["C"] == 1.5 and e["BC"] == 0.0 and e["ABC"] == 0.5
def test_yates_equals_direct_contrasts() -> None:
rng = random.Random(1)
for k in range(0, 9):
y = [Fraction(rng.randint(-99, 99), rng.randint(1, 9)) for _ in range(2 ** k)]
c = yates(y)
if k <= 6:
assert c == contrasts_direct(y)
continue
# for larger k, compare a few contrasts with their definition
for s in rng.sample(range(2 ** k), 5):
direct = sum(v * (-1) ** (bin(s).count("1") - bin(s & x).count("1")) for x, v in enumerate(y))
assert c[s] == direct
def test_yates_is_a_walsh_hadamard_transform() -> None:
# Contrast s = sum_x y_x prod_{i in s} (2 bit_i(x) - 1) = (-1)^|s| sum_x (-1)^|s & x| y_x
# (each factor in s contributes -1 when its bit is 0): H y up to the sign (-1)^|s|.
rng = random.Random(2)
for k in range(1, 7):
y = [rng.randint(-50, 50) for _ in range(2 ** k)]
h = sylvester(k)
hy = [sum(h[s][x] * y[x] for x in range(2 ** k)) for s in range(2 ** k)]
c = yates(y)
assert all(c[s] == (-1) ** bin(s).count("1") * hy[s] for s in range(2 ** k))
def test_standard_order_and_orthogonality() -> None:
r = runs(3)
assert r[:4] == [(-1, -1, -1), (1, -1, -1), (-1, 1, -1), (1, 1, -1)]
assert [effect_name(s) for s in range(8)] == ["I", "A", "B", "AB", "C", "AC", "BC", "ABC"]
cols = [[1 if v == 1 else -1 for v in col] for col in zip(*r)]
for i in range(3):
for j in range(3):
assert sum(a * b for a, b in zip(cols[i], cols[j])) == (8 if i == j else 0)
def test_example_passes_and_interaction() -> None:
y = EXAMPLE
first = [y[0] + y[1], y[2] + y[3], y[4] + y[5], y[6] + y[7], y[1] - y[0], y[3] - y[2], y[5] - y[4], y[7] - y[6]]
assert first == [132, 122, 135, 125, 12, 14, 31, 35]
second = [first[0] + first[1], first[2] + first[3], first[4] + first[5], first[6] + first[7],
first[1] - first[0], first[3] - first[2], first[5] - first[4], first[7] - first[6]]
assert second == [254, 260, 26, 66, -10, -10, 2, 4]
# the A effect at low C and at high C; AC is half their difference
a_low_c = ((y[1] - y[0]) + (y[3] - y[2])) / 2
a_high_c = ((y[5] - y[4]) + (y[7] - y[6])) / 2
assert (a_low_c, a_high_c) == (13, 33) and (a_high_c - a_low_c) / 2 == effects(y)["AC"]
# sums of squares c^2 / N
assert [Fraction(c * c, 8) for c in yates(y)[1:]] == [1058, 50, Fraction(9, 2), Fraction(9, 2), 200, 0, Fraction(1, 2)]
def test_factorial_against_one_factor_at_a_time() -> None:
# Var(effect) / sigma^2 is the sum of the squared coefficients of the linear estimator.
factorial_a = [Fraction(1 if r[0] == 1 else -1, 4) for r in runs(3)]
assert sum(c * c for c in factorial_a) == Fraction(1, 2) # 8 runs
# one factor at a time: (1), a, b, c, each repeated m times; A = mean(a) - mean((1))
for m, var in ((2, Fraction(1)), (4, Fraction(1, 2))):
coef = [Fraction(-1, m)] * m + [Fraction(1, m)] * m
assert sum(c * c for c in coef) == var # 4m runs in all
# so 16 one-factor-at-a-time runs give the precision of 8 factorial runs
def contrast_column(s: int, k: int) -> list[int]:
col = []
for r in runs(k):
v = 1
for i in range(k):
if (s >> i) & 1:
v *= r[i]
col.append(v)
return col
def test_inverse_and_parseval() -> None:
# y = H D c / N, and sum (y - mean)^2 = sum_{s > 0} c_s^2 / N
k, n = 3, 8
c = yates(EXAMPLE)
h = sylvester(k)
back = [Fraction(sum(h[x][s] * (-1) ** bin(s).count("1") * c[s] for s in range(n)), n) for x in range(n)]
assert back == EXAMPLE
mean = Fraction(sum(EXAMPLE), n)
assert sum((v - mean) ** 2 for v in EXAMPLE) == Fraction(2635, 2) == sum(Fraction(v * v, n) for v in c[1:])
def test_non_examples() -> None:
# one factor at a time from the base run (1): A = a - (1) = 12, but A is 13 at low C and 33 at high C
assert EXAMPLE[1] - EXAMPLE[0] == 12
# drop the run abc: every pair of distinct contrast columns now has inner product -1
k = 3
cols = [contrast_column(s, k)[:-1] for s in range(8)]
for s in range(8):
for t in range(8):
ip = sum(a * b for a, b in zip(cols[s], cols[t]))
assert ip == (7 if s == t else -1)
def test_errors() -> None:
with pytest.raises(ValueError):
yates([1.0, 2.0, 3.0])
References
- George E. P. Box, J. Stuart Hunter and William G. Hunter, Statistics for Experimenters, second edition, Wiley, 2005, Chapter 5 (factorial designs at two levels), starting on p. 173; Section 5.16 (blocking the 2^k designs), starting on p. 211
- The Design and Analysis of Factorial Experiments, the tabular method for the effects of a 2^n experiment (general locator, page not confirmed)
- Douglas C. Montgomery, Design and Analysis of Experiments, tenth edition, Wiley, 2019, the chapters on factorial designs, the 2^k design and blocking in the 2^k design (chapter-level locator)
Where this leads
About this page
The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.
| Ladder | Level | What the next level needs |
|---|---|---|
| Human proof | H0 no proof |
|
| Lean | L0 no Lean part |
|
| Code (python) | I0 not checked yet |
|
| Visual | V0 none |
|
| Writing | W4 complete |
|
Tag NCP43N Edit this page History Report an error Markdown