Algorithm Search⌘K

Definitionintro

Randomized complete block design

Also called RCBD, randomized block design.

Groups similar units into blocks of t and randomizes each of t treatments once within every block, so differences between blocks drop out of the treatment comparisons.

A randomized complete block design (RCBD) is the simplest way to remove a known source of variation from a comparison of treatments. The experimental units are first sorted into blocks of similar units, such as plots in the same strip of a field, batches of the same raw material or measurements on the same day. Each block holds exactly as many units as there are treatments, every treatment is given to exactly one unit of each block, and the order inside each block is randomized separately. The treatments are then compared inside blocks, so the differences between blocks leave the error. It is a randomized experiment with a restricted randomization, and its standard analysis is a two-way ANOVA with one observation per cell and no interaction.

Definition

Let there be t≥2t \ge 2 treatments and b≥2b \ge 2 blocks of tt units each, tbtb units in all. A randomized complete block design assigns the treatments by an independent, uniformly random permutation of {1,…,t}\{1, \dots, t\} to the units of each block, for example by a Fisher-Yates shuffle per block. So each of the (t!)b(t!)^b plans has probability (t!)−b(t!)^{-b}, and every treatment occurs exactly once in every block.

Write yijy_{ij} for the response of treatment ii in block jj. The usual model is additive:

yij=μ+τi+βj+eij,∑iτi=0,∑jβj=0,y_{ij} = \mu + \tau_i + \beta_j + e_{ij}, \qquad \sum_i\tau_i = 0, \quad \sum_j\beta_j = 0,

with iid N(0,σ2)N(0, \sigma^2) errors. With the treatment means yˉi⋅\bar y_{i\cdot}, the block means yˉ⋅j\bar y_{\cdot j} and the grand mean yˉ\bar y, the analysis is

source sum of squares degrees of freedom
treatments SST=b∑i(yˉi⋅−yˉ)2SS_T = b\sum_i(\bar y_{i\cdot} - \bar y)^2 t−1t - 1
blocks SSB=t∑j(yˉ⋅j−yˉ)2SS_B = t\sum_j(\bar y_{\cdot j} - \bar y)^2 b−1b - 1
error SSE=∑i,j(yij−yˉi⋅−yˉ⋅j+yˉ)2SSE = \sum_{i,j}(y_{ij} - \bar y_{i\cdot} - \bar y_{\cdot j} + \bar y)^2 (t−1)(b−1)(t - 1)(b - 1)

and the test of H0:τ1=⋯=τtH_0: \tau_1 = \dots = \tau_t uses F=SST/(t−1)SSE/((t−1)(b−1))F = \frac{SS_T/(t-1)}{SSE/((t-1)(b-1))}.

Theorem (the analysis is exact). SST=SST+SSB+SSESST = SS_T + SS_B + SSE, the three terms are squared lengths of projections onto orthogonal subspaces, and under the model F∼Ft−1,(t−1)(b−1)F \sim F_{t-1,(t-1)(b-1)} when all τi=0\tau_i = 0, whatever the block effects are.

Proof. In Rtb\mathbb R^{tb} let V0V_0 be the constant vectors, VTV_T the vectors vij=aiv_{ij} = a_i with ∑iai=0\sum_i a_i = 0, and VBV_B the vectors vij=cjv_{ij} = c_j with ∑jcj=0\sum_j c_j = 0. For a∈VTa \in V_T and c∈VBc \in V_B, ⟨a,c⟩=∑i∑jaicj=(∑iai)(∑jcj)=0\langle a, c\rangle = \sum_i\sum_j a_ic_j = (\sum_i a_i)(\sum_j c_j) = 0, and both are orthogonal to the constants because their entries sum to zero. This is the only place where completeness is used: every treatment meets every block exactly once. Let VEV_E be the orthogonal complement of V0⊕VT⊕VBV_0 \oplus V_T \oplus V_B, of dimension tb−1−(t−1)−(b−1)=(t−1)(b−1)tb - 1 - (t - 1) - (b - 1) = (t-1)(b-1). The projection of yy onto VTV_T is yˉi⋅−yˉ\bar y_{i\cdot} - \bar y at (i,j)(i, j), because y−(yˉi⋅−yˉ)y - (\bar y_{i\cdot} - \bar y) is orthogonal to VTV_T; in the same way for VBV_B and V0V_0. The remainder yij−yˉi⋅−yˉ⋅j+yˉy_{ij} - \bar y_{i\cdot} - \bar y_{\cdot j} + \bar y is the projection onto VEV_E. Pythagoras gives the decomposition. The mean vector μ+τi+βj\mu + \tau_i + \beta_j lies in V0⊕VT⊕VBV_0 \oplus V_T \oplus V_B, so its projection onto VEV_E is 0, and its projection onto VTV_T is τ\tau. By the lemma on projections of a normal vector in the one-way ANOVA proof, SST/σ2SS_T/\sigma^2 and SSE/σ2SSE/\sigma^2 are independent, SSE/σ2∼χ(t−1)(b−1)2SSE/\sigma^2 \sim \chi^2_{(t-1)(b-1)}, and SST/σ2∼χt−12SS_T/\sigma^2 \sim \chi^2_{t-1} when τ=0\tau = 0. □\square

The test file checks the closed forms against exact least squares by model comparison, in rational arithmetic, on random tables. If the additive model fails because treatments and blocks interact, the interaction goes into SSESSE: E[MSE]=σ2+∑i,jγij2/((t−1)(b−1))E[MSE] = \sigma^2 + \sum_{i,j}\gamma_{ij}^2/((t-1)(b-1)) for interaction effects γij\gamma_{ij}, and the F-test loses power. The design has no replication inside cells, so it cannot separate interaction from error.

Why blocking helps. The difference of two treatment means is yˉi⋅−yˉk⋅=τi−τk+eˉi⋅−eˉk⋅\bar y_{i\cdot} - \bar y_{k\cdot} = \tau_i - \tau_k + \bar e_{i\cdot} - \bar e_{k\cdot}: the block effects cancel exactly, because both treatments appear once in every block. Its variance is 2σ2/b2\sigma^2/b, where σ2\sigma^2 is the variation inside blocks only. A completely randomized design on the same units has the variation between blocks in its error as well. The relative efficiency estimates the ratio of the two error variances from the blocked analysis,

RE=(b−1)MSB+b(t−1)MSE(tb−1)MSE,RE = \frac{(b - 1)MS_B + b(t - 1)MSE}{(tb - 1)MSE},

the number of completely randomized replicates that one block is worth.

Randomization. Randomizing inside each block makes the assignment independent of every unit property, including the ones that the blocks do not capture. It justifies the comparison without the normal model: under the sharp null of no effect on any unit, the distribution of FF over the (t!)b(t!)^b equally likely plans gives an exact permutation test (Fisher, 1935).

Examples and non-examples

Example: four treatments in five blocks. Four treatments A to D are tried on five batches of material (the blocks), with each batch split into four parts:

treatment block 1 block 2 block 3 block 4 block 5 mean
A 20 26 30 18 28 24.4
B 23 26 34 19 31 26.6
C 18 24 31 17 25 23
D 24 29 34 22 31 28
block mean 21.25 26.25 32.25 19 28.75 25.5
source sum of squares df mean square F p
treatments 74.6 3 24.867 746/31=24.065746/31 = 24.065 2.30⋅10−52.30 \cdot 10^{-5}
blocks 468 4 117 113.23 2.0⋅10−92.0 \cdot 10^{-9}
error 12.4 12 31/30=1.033331/30 = 1.0333
total 555 19

The treatments differ clearly (F(3,12,0.95)=3.4903F_{(3,12,0.95)} = 3.4903). The relative efficiency is 14505/589=24.6314505/589 = 24.63: an unblocked experiment would need about 25 times as many units for the same precision. The standard error of a difference of two treatment means is 2MSE/5=0.643\sqrt{2MSE/5} = 0.643.

Non-example: the same data analysed as one-way. Ignoring the blocks puts SSBSS_B into the error: SSW=468+12.4=480.4SSW = 468 + 12.4 = 480.4 on 16 degrees of freedom, and the one-way ANOVA gives F=0.8282F = 0.8282 on (3,16)(3, 16), p=0.4975p = 0.4975. The standard error of a difference becomes 3.4663.466. Analysing a blocked experiment as if it were completely randomized throws away the design.

Example: matched pairs. With t=2t = 2 the design is the paired comparison, and F=T2F = T^2, where TT is the paired Student t statistic of the within-block differences. Treatments A and B of the example alone give F=242/27=8.963F = 242/27 = 8.963, T=−2.994T = -2.994 on 4 degrees of freedom, and p=0.0402p = 0.0402.

Non-example: blocks smaller than the number of treatments. When a block holds fewer than tt units (a day allows only three runs, a judge can taste only four wines), the design is incomplete. The orthogonality in the theorem fails, and the treatment means must be adjusted for blocks; the balanced incomplete block design keeps the analysis simple.

Non-example: one randomization for all blocks. Using the same random order in every block is not an RCBD. A trend in position inside the blocks (the east side of each strip, the last run of each day) then hits the same treatment every time. Two crossed nuisance factors such as rows and columns call for a Latin square design instead.

Example: ranks. For data far from normal, the Friedman test ranks the tt responses inside each block and has an exact null law under the same randomization.

  • Two-way ANOVA: the RCBD analysis is the additive two-way model with one observation per cell; with replicates in each cell the interaction can be tested.
  • Latin square design: blocks in two directions at once, rows and columns, with tt levels each.
  • Balanced incomplete block design: blocks smaller than tt, with every pair of treatments together equally often.
  • Linear mixed model: treats the block effects as random, βj∼N(0,σβ2)\beta_j \sim N(0, \sigma_\beta^2). In a complete balanced design the treatment F-test is the same, and the variance components come from restricted maximum likelihood.
  • Tukey's test and Scheffé's method: follow-up comparisons of the treatment means with MSEMSE on (t−1)(b−1)(t-1)(b-1) degrees of freedom.
  • CUPED: adjusts for a pre-experiment covariate after the experiment, where blocking stratifies on it before; both remove predictable variation from the comparison.

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.

randomized_block_design.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/randomized-block-design/. The authors are listed in prov/24Z82C.jsonl.
"""Randomized complete block design: randomization and the two-way additive analysis.

y[i][j] is the response of treatment i (t treatments) in block j (b blocks). The model is
y[i][j] = mu + tau_i + beta_j + e[i][j]: blocks and treatments add, with no interaction.
"""

import random
from collections.abc import Sequence
from typing import NamedTuple


class BlockAnova(NamedTuple):
    ss_treat: float
    ss_block: float
    ss_error: float
    df_treat: int
    df_block: int
    df_error: int
    f_treat: float
    mse: float


def randomize(t: int, b: int, rng: random.Random) -> list[list[int]]:
    """For each block, an independent uniform permutation: plot p of block j gets treatment
    plan[j][p]. Every treatment appears exactly once in every block."""
    plan = []
    for _ in range(b):
        order = list(range(t))
        rng.shuffle(order)  # Fisher-Yates
        plan.append(order)
    return plan


def rcbd_anova(y: Sequence[Sequence[float]]) -> BlockAnova:
    """Sums of squares for treatments, blocks and error, by two passes over the t x b table."""
    t, b = len(y), len(y[0])
    if t < 2 or b < 2 or any(len(r) != b for r in y):
        raise ValueError("need a complete t x b table with t, b >= 2")
    grand = sum(map(sum, y)) / (t * b)
    tm = [sum(r) / b for r in y]
    bm = [sum(y[i][j] for i in range(t)) / t for j in range(b)]
    ss_treat = b * sum((m - grand) ** 2 for m in tm)
    ss_block = t * sum((m - grand) ** 2 for m in bm)
    ss_error = sum((y[i][j] - tm[i] - bm[j] + grand) ** 2 for i in range(t) for j in range(b))
    df_t, df_b, df_e = t - 1, b - 1, (t - 1) * (b - 1)
    mse = ss_error / df_e
    if mse == 0.0:
        raise ValueError("the residuals are all zero")
    return BlockAnova(ss_treat, ss_block, ss_error, df_t, df_b, df_e, (ss_treat / df_t) / mse, mse)


def relative_efficiency(y: Sequence[Sequence[float]]) -> float:
    """Estimated variance of a completely randomized design on the same units over the
    blocked error variance: ((b - 1) MSB + b (t - 1) MSE) / ((tb - 1) MSE)."""
    a = rcbd_anova(y)
    t, b = a.df_treat + 1, a.df_block + 1
    msb = a.ss_block / a.df_block
    return ((b - 1) * msb + b * (t - 1) * a.mse) / ((t * b - 1) * a.mse)
test_randomized_block_design.py 112 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/randomized-block-design/. The authors are listed in prov/24Z82C.jsonl.

import random
from fractions import Fraction

import pytest

from randomized_block_design import randomize, rcbd_anova, relative_efficiency

EXAMPLE = [[20, 26, 30, 18, 28], [23, 26, 34, 19, 31], [18, 24, 31, 17, 25], [24, 29, 34, 22, 31]]


def residual_ss(cols: list[list[Fraction]], y: list[Fraction]) -> Fraction:
    """Exact least squares residual sum of squares by Gauss-Jordan on the normal equations."""
    k = len(cols)
    m = [[sum(a * c for a, c in zip(cols[i], cols[j])) for j in range(k)]
         + [sum(a * v for a, v in zip(cols[i], y))] for i in range(k)]
    for c in range(k):
        piv = next(r for r in range(c, k) if m[r][c] != 0)
        m[c], m[piv] = m[piv], m[c]
        for r in range(k):
            if r != c and m[r][c] != 0:
                f = m[r][c] / m[c][c]
                m[r] = [x - f * z for x, z in zip(m[r], m[c])]
    beta = [m[i][k] / m[i][i] for i in range(k)]
    fit = [sum(b * col[n] for b, col in zip(beta, cols)) for n in range(len(y))]
    return sum((a - f) ** 2 for a, f in zip(y, fit))


def exact_by_model_comparison(table):
    t, b = len(table), len(table[0])
    cells = [(i, j) for i in range(t) for j in range(b)]
    y = [Fraction(table[i][j]) for i, j in cells]
    one = [[Fraction(1)] * len(cells)]
    treat = [[Fraction(int(i == a) - int(i == t - 1)) for i, _ in cells] for a in range(t - 1)]
    block = [[Fraction(int(j == c) - int(j == b - 1)) for _, j in cells] for c in range(b - 1)]
    rss_full = residual_ss(one + treat + block, y)
    rss_no_treat = residual_ss(one + block, y)
    rss_no_block = residual_ss(one + treat, y)
    return rss_no_treat - rss_full, rss_no_block - rss_full, rss_full


def test_example() -> None:
    a = rcbd_anova(EXAMPLE)
    assert abs(a.ss_treat - 74.6) < 1e-9 and abs(a.ss_block - 468.0) < 1e-9 and abs(a.ss_error - 12.4) < 1e-9
    assert (a.df_treat, a.df_block, a.df_error) == (3, 4, 12)
    assert abs(a.f_treat - 746 / 31) < 1e-9
    assert abs(relative_efficiency(EXAMPLE) - 14505 / 589) < 1e-9


def test_closed_form_equals_least_squares() -> None:
    rng = random.Random(1)
    for _ in range(10):
        t, b = rng.randint(2, 5), rng.randint(2, 5)
        table = [[rng.randint(0, 40) for _ in range(b)] for _ in range(t)]
        if len({v for r in table for v in r}) < 3:
            continue
        sst, ssb, sse = exact_by_model_comparison(table)
        try:
            a = rcbd_anova(table)
        except ValueError:
            assert sse == 0
            continue
        assert abs(a.ss_treat - float(sst)) < 1e-9 and abs(a.ss_block - float(ssb)) < 1e-9
        assert abs(a.ss_error - float(sse)) < 1e-9


def test_randomization_is_a_permutation_per_block() -> None:
    plan = randomize(4, 6, random.Random(2))
    assert len(plan) == 6 and all(sorted(p) == [0, 1, 2, 3] for p in plan)
    # every position gets each treatment equally often over many draws
    rng = random.Random(3)
    counts = [0] * 4
    for _ in range(4000):
        counts[randomize(4, 1, rng)[0][0]] += 1
    assert all(abs(c - 1000) < 4 * (4000 * 0.25 * 0.75) ** 0.5 for c in counts)


def test_ignoring_the_blocks() -> None:
    # the one-way analysis of the same table puts the block sum of squares into the error
    y = [[Fraction(v) for v in r] for r in EXAMPLE]
    means = [sum(r) / len(r) for r in y]
    ssw = sum((v - m) ** 2 for r, m in zip(y, means) for v in r)
    assert ssw == Fraction(2402, 5) == Fraction(468) + Fraction(62, 5)
    grand = sum(map(sum, y)) / 20
    ssa = 5 * sum((m - grand) ** 2 for m in means)
    f_one_way = (ssa / 3) / (ssw / 16)
    assert abs(float(f_one_way) - 0.8282) < 1e-4


def test_two_treatments_is_the_paired_t_test() -> None:
    rng = random.Random(5)
    for table in [EXAMPLE[:2]] + [[[rng.randint(0, 30) for _ in range(6)] for _ in range(2)] for _ in range(5)]:
        d = [Fraction(u - v) for u, v in zip(*table)]
        b = len(d)
        m = sum(d) / b
        s2 = sum((x - m) ** 2 for x in d) / (b - 1)
        if s2 == 0:
            continue
        t2 = m * m / (s2 / b)
        assert abs(rcbd_anova(table).f_treat - float(t2)) < 1e-9 * max(1.0, float(t2))
    assert abs(rcbd_anova(EXAMPLE[:2]).f_treat - 242 / 27) < 1e-9


def test_errors() -> None:
    with pytest.raises(ValueError):
        rcbd_anova([[1, 2, 3]])
    with pytest.raises(ValueError):
        rcbd_anova([[1, 2], [3]])
    with pytest.raises(ValueError):
        rcbd_anova([[1, 2], [3, 4]])  # additive exactly, so no error variance

References

  1. The Design of Experiments, the chapters on field experiments in randomized blocks (general locator, chapter not confirmed)
  2. George E. P. Box, J. Stuart Hunter and William G. Hunter, Statistics for Experimenters, second edition, Wiley, 2005, Section 4.2 (randomized block designs), starting on p. 145
  3. Douglas C. Montgomery, Design and Analysis of Experiments, tenth edition, Wiley, 2019, Chapter 4 (randomized blocks, Latin squares and related designs; chapter-level locator)
  4. George Casella and Roger L. Berger, Statistical Inference, second edition, Duxbury, 2002, Chapter 11 (analysis of variance and the partition of sums of squares; 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.

LadderLevelWhat the next level needs
Human proofH0 no proof
  • add a proof in proofs/ (06.5)
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)
WritingW4 complete
  • a review of the text: no review record reviews/24Z82C/text.yaml