Algorithm Search⌘K

Definitioncore

Latin square design

Also called Latin square experiment.

Compares n treatments while blocking two nuisance factors with n levels each, by placing the treatments as the symbols of an n x n Latin square. Needs only n² runs.

A Latin square design compares nn treatments on n2n^2 experimental units that are classified in two directions, such as nn days by nn operators, or nn rows by nn columns of a field. Each treatment appears exactly once in each row and once in each column, so the treatments are placed as the symbols of a Latin square. Row and column differences then drop out of the treatment comparisons, as block differences do in a randomized block design, but in two directions at once and with only n2n^2 runs instead of n3n^3. Two Latin squares that are orthogonal give a Graeco-Latin square, which blocks a third factor, and a complete set of n−1n - 1 mutually orthogonal Latin squares exists when nn is a prime power.

Definition

A Latin square of order nn is an n×nn \times n array LL on nn symbols in which every symbol occurs exactly once in each row and exactly once in each column. Number the rows, columns and symbols 0,…,n−10, \dots, n - 1. A Latin square design for nn treatments uses two blocking factors with nn levels each; the unit in row ii and column jj receives treatment L(i,j)L(i, j). The square is randomized by permuting its rows, its columns and its symbols at random. The additive model is

yij=μ+ρi+γj+τL(i,j)+eij,y_{ij} = \mu + \rho_i + \gamma_j + \tau_{L(i,j)} + e_{ij},

with zero-sum row effects ρ\rho, column effects γ\gamma and treatment effects τ\tau, and iid N(0,σ2)N(0, \sigma^2) errors. With row, column and treatment means yˉi⋅\bar y_{i\cdot}, yˉ⋅j\bar y_{\cdot j} and yˉ(s)\bar y_{(s)}, the analysis is

source sum of squares degrees of freedom
rows n∑i(yˉi⋅−yˉ)2n\sum_i(\bar y_{i\cdot} - \bar y)^2 n−1n - 1
columns n∑j(yˉ⋅j−yˉ)2n\sum_j(\bar y_{\cdot j} - \bar y)^2 n−1n - 1
treatments n∑s(yˉ(s)−yˉ)2n\sum_s(\bar y_{(s)} - \bar y)^2 n−1n - 1
error ∑i,j(yij−yˉi⋅−yˉ⋅j−yˉ(L(i,j))+2yˉ)2\sum_{i,j}(y_{ij} - \bar y_{i\cdot} - \bar y_{\cdot j} - \bar y_{(L(i,j))} + 2\bar y)^2 (n−1)(n−2)(n - 1)(n - 2)

and the treatment test is F=MStreatments/MSEF = MS_{\text{treatments}}/MSE on (n−1,(n−1)(n−2))(n - 1, (n - 1)(n - 2)) degrees of freedom. A useful design needs n≥3n \ge 3.

Theorem 1 (the analysis is exact). The four sums of squares add up to the total, and under the model F∼Fn−1,(n−1)(n−2)F \sim F_{n-1,(n-1)(n-2)} when all τs=0\tau_s = 0.

Proof. Let VRV_R, VCV_C and VTV_T hold the zero-sum vectors that are constant on rows, on columns and on treatments. Rows and columns are orthogonal as in the randomized block design proof. For a∈VRa \in V_R and c∈VTc \in V_T, ⟨a,c⟩=∑iai∑jcL(i,j)=∑iai∑scs=0\langle a, c\rangle = \sum_i a_i\sum_j c_{L(i,j)} = \sum_i a_i\sum_s c_s = 0, because row ii holds every symbol once. Columns and treatments are orthogonal for the same reason. So the constants, VRV_R, VCV_C and VTV_T are mutually orthogonal, and their orthogonal complement has dimension n2−1−3(n−1)=(n−1)(n−2)n^2 - 1 - 3(n - 1) = (n - 1)(n - 2). Each sum of squares in the table is the squared length of the projection onto one of these subspaces, and the mean vector lies in their sum. The lemma on projections of a normal vector in the one-way ANOVA proof gives the F law. □\square

Theorem 2 (a Latin square of every order). For every n≥1n \ge 1, the cyclic square L(i,j)=(i+j) mod nL(i, j) = (i + j) \bmod n is a Latin square.

Proof. In row ii, the map j↦(i+j) mod nj \mapsto (i + j) \bmod n is a bijection of {0,…,n−1}\{0, \dots, n - 1\} with inverse s↦(s−i) mod ns \mapsto (s - i) \bmod n, so the row holds each symbol once. The same argument in ii applies to each column. □\square

How many Latin squares there are is a hard counting problem; see counting Latin squares. Deciding whether a partly filled square can be completed is NP-complete; see Latin square completion.

Orthogonal squares. Two Latin squares L1L_1 and L2L_2 of order nn are orthogonal if, superimposed, every ordered pair of symbols (L1(i,j),L2(i,j))(L_1(i,j), L_2(i,j)) occurs exactly once. The superimposed square is a Graeco-Latin square: one symbol set blocks a third factor, or two treatment factors are run together. A set of squares that are orthogonal in pairs is a set of mutually orthogonal Latin squares (MOLS).

Theorem 3 (at most n−1n - 1 MOLS). For n≥2n \ge 2, a set of mutually orthogonal Latin squares of order nn has at most n−1n - 1 squares.

Proof. Renaming the symbols of one square keeps it Latin and keeps it orthogonal to the others, since a bijection of symbols maps the set of all n2n^2 ordered pairs onto itself. So assume the first row of every square is 0,1,…,n−10, 1, \dots, n - 1. Look at the cell (1,0)(1, 0). In each square its symbol is not 0, because 0 is already in column 0 at (0,0)(0, 0). If two squares had the same symbol ss at (1,0)(1, 0), the pair (s,s)(s, s) would occur at (1,0)(1, 0) and also at (0,s)(0, s), which is a different cell; this contradicts orthogonality. So the squares have distinct nonzero symbols at (1,0)(1, 0), and there are at most n−1n - 1 of them. □\square

Theorem 4 (a complete set for prime powers). Let qq be a prime power and Fq\mathbb F_q the field with qq elements. For a∈Fqa \in \mathbb F_q, a≠0a \ne 0, put La(x,y)=ax+yL_a(x, y) = ax + y. The q−1q - 1 squares LaL_a are mutually orthogonal Latin squares.

Proof. For fixed xx, y↦ax+yy \mapsto ax + y is a bijection of Fq\mathbb F_q; for fixed yy, x↦ax+yx \mapsto ax + y is a bijection because a≠0a \ne 0 has an inverse. So each LaL_a is Latin. For a≠ba \ne b and a target pair (u,v)(u, v), the system ax+y=uax + y = u, bx+y=vbx + y = v gives (a−b)x=u−v(a - b)x = u - v, so x=(u−v)/(a−b)x = (u - v)/(a - b) and then y=u−axy = u - ax: exactly one cell. So LaL_a and LbL_b are orthogonal. □\square

For q=pmq = p^m with m>1m > 1, Fq\mathbb F_q is built as the polynomials over Zp\mathbb Z_p modulo an irreducible polynomial of degree mm; the code finds one by trial division. Integers modulo a composite nn do not work, because aa may have no inverse.

What is cited, not proved. Euler conjectured in 1782 that no pair of orthogonal Latin squares exists for n≡2(mod4)n \equiv 2 \pmod 4. Tarry checked n=6n = 6 by hand in 1900, and n=2n = 2 is immediate. Bose, Shrikhande and Parker (1960) proved that a pair exists for every other nn, so Euler's conjecture fails for every n≥10n \ge 10. A complete set of n−1n - 1 MOLS is equivalent to an affine plane of order nn, and it is unknown whether one exists for any nn that is not a prime power.

Theorem 5 (cyclic squares of even order have no mate). If nn is even, the cyclic square has no orthogonal mate.

Proof. A mate MM would split the cells into nn classes {(i,j):M(i,j)=s}\{(i, j) : M(i, j) = s\}, each holding one cell per row, one per column and, by orthogonality, one of each symbol of LL: a transversal. Take one transversal, cells (i,π(i))(i, \pi(i)) for a permutation π\pi. Its symbols are all of Zn\mathbb Z_n, so their sum is n(n−1)/2≡n/2(modn)n(n - 1)/2 \equiv n/2 \pmod n for even nn. But the sum is also ∑i(i+π(i))=n(n−1)≡0(modn)\sum_i(i + \pi(i)) = n(n - 1) \equiv 0 \pmod n. This is a contradiction. □\square

Codes and arrays. k−2k - 2 MOLS of order nn are the same object as an orthogonal array OA(n2,k,n,2)OA(n^2, k, n, 2): one row per cell, holding the row index, the column index and the k−2k - 2 symbols. Read as a code of length kk over nn symbols with n2n^2 words, it has minimum distance k−1k - 1 and meets the Singleton bound, so it is an MDS code. The squares La(x,y)=ax+yL_a(x, y) = ax + y give the codewords (x,y,ax+y)(x, y, ax + y), which are the evaluations of a linear code related to the Reed-Solomon code.

Examples and non-examples

Example: four treatments, days by operators. The rows are four days, the columns four operators, and the treatments A to D follow the square L1L_1 of F4\mathbb F_4 below. The responses:

operator 1 operator 2 operator 3 operator 4
day 1 A 30 B 32 C 31 D 31
day 2 B 37 A 34 D 36 C 28
day 3 C 29 D 31 A 31 B 30
day 4 D 37 C 31 B 37 A 25

The treatment means are 30, 34, 29.75 and 33.75, and the grand mean is 31.875.

source sum of squares df F p
days 117/4=29.25117/4 = 29.25 3 2.786 0.132
operators 269/4=67.25269/4 = 67.25 3 6.405 0.0267
treatments 257/4=64.25257/4 = 64.25 3 257/42=6.119257/42 = 6.119 0.0295
error 21 6

With F(3,6,0.95)=4.757F_{(3,6,0.95)} = 4.757, the treatments differ at the 5% level. A one-way ANOVA of the same 16 values by treatment alone puts days and operators into the error, SSW=117.5SSW = 117.5 on 12 degrees of freedom, and gives F=2.187F = 2.187, p=0.142p = 0.142.

Example: a Graeco-Latin square of order 3. F3\mathbb F_3 gives L1(x,y)=x+yL_1(x, y) = x + y and L2(x,y)=2x+yL_2(x, y) = 2x + y. Writing L1L_1 as A, B, C and L2L_2 as α, β, γ:

Aα Bβ Cγ
Bγ Cα Aβ
Cβ Aγ Bα

Each of the nine pairs occurs once. By Theorem 3 no third square can be added.

Example: a complete set of order 4. F4={0,1,ω,ω+1}\mathbb F_4 = \{0, 1, \omega, \omega + 1\} with ω2=ω+1\omega^2 = \omega + 1, coded 0, 1, 2, 3. The three squares La(x,y)=ax+yL_a(x, y) = ax + y have the rows

  • L1L_1: 0123, 1032, 2301, 3210;
  • LωL_\omega: 0123, 2301, 3210, 1032;
  • Lω+1L_{\omega+1}: 0123, 3210, 1032, 2301.

They are mutually orthogonal, and the exhaustive search in the test file confirms that no set of 4 MOLS of order 4 exists.

Non-example: order 2. Theorem 3 allows at most 2−1=12 - 1 = 1 square. Directly: after renaming symbols both squares are 01 / 10, and superimposed they show only the pairs 00 and 11. There is no Graeco-Latin square of order 2.

Non-example: the cyclic square of order 4. 0123 / 1230 / 2301 / 3012 is Latin but has no transversal (Theorem 5), so it has no orthogonal mate, while the square L1L_1 of F4\mathbb F_4, of the same order, has two mates.

Non-example: order 6. There is no pair of orthogonal Latin squares of order 6 (Tarry, 1900), so no Graeco-Latin design for six treatments; this is Euler's problem of the 36 officers.

Non-example: interaction. If the effect of a treatment depends on the day or the operator, the additive model fails and the interaction goes into the error with only (n−1)(n−2)(n - 1)(n - 2) degrees of freedom. With n=3n = 3 there are only 2. Small Latin squares are often replicated for this reason.

  • Randomized block design: blocking in one direction; a Latin square blocks in two.
  • Balanced incomplete block design: blocks smaller than the number of treatments; finite fields and affine planes give both kinds of design.
  • Orthogonal array: MOLS are orthogonal arrays of strength 2, and Latin squares are fractions of the n3n^3 factorial.
  • Factorial design: a Latin square is a one-nnth fraction of the n×n×nn \times n \times n factorial in rows, columns and treatments, aliasing the interactions with the main effects.
  • Sudoku: a Latin square of order 9 with the extra condition on the 3×33 \times 3 boxes; its completion is an exact cover problem.
  • Latin hypercube sampling: one sample in each row and column stratum, the same idea used for numerical integration.

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.

latin_square_design.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/latin-square-design/. The authors are listed in prov/AR1SZ9.jsonl.
"""Latin squares for experimental design: construction, randomization, orthogonal mates,
and the analysis of variance of a Latin square experiment.

A Latin square of order n is an n x n array on n symbols in which each symbol occurs once
in each row and once in each column. In a Latin square design, rows and columns are two
blocking factors and the symbols are the treatments.
"""

import math
import random
from collections.abc import Sequence
from itertools import product

Square = list[list[int]]


def cyclic(n: int) -> Square:
    """L(i, j) = (i + j) mod n, a Latin square for every n >= 1."""
    return [[(i + j) % n for j in range(n)] for i in range(n)]


def is_latin(sq: Sequence[Sequence[int]]) -> bool:
    n = len(sq)
    full = list(range(n))
    return (all(len(r) == n and sorted(r) == full for r in sq)
            and all(sorted(sq[i][j] for i in range(n)) == full for j in range(n)))


def are_orthogonal(a: Sequence[Sequence[int]], b: Sequence[Sequence[int]]) -> bool:
    """Superimposed, the two squares show each ordered pair of symbols exactly once."""
    n = len(a)
    return len({(a[i][j], b[i][j]) for i in range(n) for j in range(n)}) == n * n


def randomize(sq: Sequence[Sequence[int]], rng: random.Random) -> Square:
    """Permute rows, columns and symbols at random (the usual randomization of a design)."""
    n = len(sq)
    rows, cols, syms = (rng.sample(range(n), n) for _ in range(3))
    return [[syms[sq[rows[i]][cols[j]]] for j in range(n)] for i in range(n)]


# ---------------------------------------------------------------- finite fields


def _prime_power(q: int) -> tuple[int, int]:
    for p in range(2, q + 1):
        if q % p == 0:
            m, r = 0, q
            while r % p == 0:
                r //= p
                m += 1
            if r != 1:
                raise ValueError("q must be a prime power")
            return p, m
    raise ValueError("q must be a prime power >= 2")


def _poly_mod(a: list[int], f: list[int], p: int) -> list[int]:
    """a mod f over GF(p); coefficient lists, lowest degree first, f monic."""
    a = a[:]
    while len(a) >= len(f):
        c = a[-1] % p
        if c:
            shift = len(a) - len(f)
            for i, fi in enumerate(f):
                a[shift + i] = (a[shift + i] - c * fi) % p
        a.pop()
    return a


def _irreducible(p: int, m: int) -> list[int]:
    """The first monic irreducible polynomial of degree m over GF(p), by trial division."""
    for tail in product(range(p), repeat=m):
        f = list(tail) + [1]
        if m == 1:
            return f
        reducible = False
        for d in range(1, m // 2 + 1):
            for gt in product(range(p), repeat=d):
                if not any(_poly_mod(f, list(gt) + [1], p)):
                    reducible = True
                    break
            if reducible:
                break
        if not reducible:
            return f
    raise AssertionError("an irreducible polynomial exists for every degree")


def field(q: int) -> tuple[list[list[int]], list[list[int]]]:
    """Addition and multiplication tables of GF(q); element e codes the polynomial with
    the base-p digits of e as coefficients, so 0 and 1 are the field's 0 and 1."""
    p, m = _prime_power(q)
    f = _irreducible(p, m)
    digits = [[(e // p ** i) % p for i in range(m)] for e in range(q)]
    code = lambda c: sum((v % p) * p ** i for i, v in enumerate(c))
    add = [[code([x + y for x, y in zip(digits[a], digits[b])]) for b in range(q)] for a in range(q)]
    mul = []
    for a in range(q):
        row = []
        for b in range(q):
            prod_ = [0] * (2 * m - 1)
            for i, x in enumerate(digits[a]):
                for j, y in enumerate(digits[b]):
                    prod_[i + j] += x * y
            r = _poly_mod(prod_, f, p) if m > 1 else [prod_[0] % p]
            row.append(code(r + [0] * (m - len(r))))
        mul.append(row)
    return add, mul


def mols(q: int) -> list[Square]:
    """q - 1 mutually orthogonal Latin squares of prime power order q: L_a(x, y) = a x + y."""
    add, mul = field(q)
    return [[[add[mul[a][x]][y] for y in range(q)] for x in range(q)] for a in range(1, q)]


# ---------------------------------------------------------------- analysis


def latin_square_anova(y: Sequence[Sequence[float]], sq: Sequence[Sequence[int]]) -> dict[str, tuple[float, int]]:
    """Sums of squares and degrees of freedom of rows, columns, treatments and error
    for the additive model y_ij = mu + row_i + col_j + tau_(L(i, j)) + e_ij."""
    n = len(y)
    if n < 3 or not is_latin(sq):
        raise ValueError("need a Latin square of order n >= 3 (error df (n - 1)(n - 2))")
    total = math.fsum(v for r in y for v in r)
    g = total / (n * n)
    row_m = [math.fsum(r) / n for r in y]
    col_m = [math.fsum(y[i][j] for i in range(n)) / n for j in range(n)]
    trt_m = [0.0] * n
    for i in range(n):
        for j in range(n):
            trt_m[sq[i][j]] += y[i][j] / n
    ss = {
        "rows": n * math.fsum((m - g) ** 2 for m in row_m),
        "columns": n * math.fsum((m - g) ** 2 for m in col_m),
        "treatments": n * math.fsum((m - g) ** 2 for m in trt_m),
    }
    ss["error"] = math.fsum((y[i][j] - row_m[i] - col_m[j] - trt_m[sq[i][j]] + 2 * g) ** 2
                            for i in range(n) for j in range(n))
    df = {"rows": n - 1, "columns": n - 1, "treatments": n - 1, "error": (n - 1) * (n - 2)}
    return {key: (ss[key], df[key]) for key in ss}
test_latin_square_design.py 163 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/latin-square-design/. The authors are listed in prov/AR1SZ9.jsonl.

import random
from fractions import Fraction
from itertools import combinations, permutations

import pytest

from latin_square_design import are_orthogonal, cyclic, field, is_latin, latin_square_anova, mols, randomize


def all_latin_with_first_row(n: int) -> list[list[list[int]]]:
    """Every Latin square of order n whose first row is 0, 1, ..., n - 1 (backtracking)."""
    out = []
    perms = list(permutations(range(n)))

    def extend(rows):
        if len(rows) == n:
            out.append([list(r) for r in rows])
            return
        for p in perms:
            if all(p[j] != r[j] for r in rows for j in range(n)):
                extend(rows + [p])

    extend([tuple(range(n))])
    return out


def has_transversal(sq) -> bool:
    n = len(sq)
    return any(len({sq[i][p[i]] for i in range(n)}) == n for p in permutations(range(n)))


def test_cyclic_squares() -> None:
    for n in range(1, 16):
        assert is_latin(cyclic(n))


def test_field_axioms_small_orders() -> None:
    for q in (2, 3, 4, 5, 7, 8, 9, 16, 25, 27):
        add, mul = field(q)
        for a in range(q):
            assert add[a][0] == a and mul[a][1] == a and mul[a][0] == 0
            assert sorted(add[a]) == list(range(q))
            if a:
                assert sorted(mul[a]) == list(range(q))  # no zero divisors: an inverse exists
        rng = random.Random(q)
        for _ in range(200):
            a, b, c = (rng.randrange(q) for _ in range(3))
            assert mul[a][add[b][c]] == add[mul[a][b]][mul[a][c]]
            assert mul[mul[a][b]][c] == mul[a][mul[b][c]] and mul[a][b] == mul[b][a]


def test_complete_sets_of_mols() -> None:
    for q in (2, 3, 4, 5, 7, 8, 9):
        squares = mols(q)
        assert len(squares) == q - 1
        assert all(is_latin(s) for s in squares)
        assert all(are_orthogonal(a, b) for a, b in combinations(squares, 2))


def test_example_squares() -> None:
    assert mols(3) == [[[0, 1, 2], [1, 2, 0], [2, 0, 1]], [[0, 1, 2], [2, 0, 1], [1, 2, 0]]]
    assert mols(4)[0] == [[0, 1, 2, 3], [1, 0, 3, 2], [2, 3, 0, 1], [3, 2, 1, 0]]


def max_mols(n: int) -> int:
    """The size of the largest set of MOLS of order n, by exhaustive search over squares
    with first row 0, ..., n - 1 (renaming symbols keeps orthogonality)."""
    sq = all_latin_with_first_row(n)
    best = 1
    adj = {i: {j for j in range(len(sq)) if j != i and are_orthogonal(sq[i], sq[j])} for i in range(len(sq))}

    def grow(clique, cand):
        nonlocal best
        best = max(best, len(clique))
        for v in sorted(cand):
            if v > (clique[-1] if clique else -1):
                grow(clique + [v], cand & adj[v])

    grow([], set(range(len(sq))))
    return best


def test_bound_n_minus_one_is_reached_and_not_beaten() -> None:
    assert len(all_latin_with_first_row(3)) == 2
    assert len(all_latin_with_first_row(4)) == 24
    assert max_mols(3) == 2 and max_mols(4) == 3
    assert max_mols(2) == 1


def test_cyclic_even_squares_have_no_transversal() -> None:
    for n in (2, 4, 6):
        assert not has_transversal(cyclic(n))
    for n in (3, 5, 7):
        assert has_transversal(cyclic(n))


def test_randomize_keeps_latin() -> None:
    rng = random.Random(1)
    for n in range(1, 9):
        assert is_latin(randomize(cyclic(n), rng))


def exact_rss(cols, y) -> Fraction:
    k = len(cols)
    m = [[sum(Fraction(a) * b for a, b in zip(cols[i], cols[j])) for j in range(k)]
         + [sum(Fraction(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)]
    return sum((v - sum(beta[i] * cols[i][t] for i in range(k))) ** 2 for t, v in enumerate(y))


def test_anova_against_least_squares() -> None:
    rng = random.Random(2)
    for n in (3, 4, 5):
        sq = randomize(cyclic(n), rng)
        y = [[rng.randint(0, 40) for _ in range(n)] for _ in range(n)]
        flat = [y[i][j] for i in range(n) for j in range(n)]
        ind = lambda f: [[1 if f(i, j) == lev else 0 for i in range(n) for j in range(n)] for lev in range(1, n)]
        one = [[1] * (n * n)]
        rows, cols, trts = ind(lambda i, j: i), ind(lambda i, j: j), ind(lambda i, j: sq[i][j])
        full = exact_rss(one + rows + cols + trts, flat)
        table = latin_square_anova(y, sq)
        assert abs(table["error"][0] - float(full)) < 1e-9
        # orthogonality: each factor's SS is its drop in RSS whatever else is in the model
        assert abs(table["treatments"][0] - float(exact_rss(one + rows + cols, flat) - full)) < 1e-9
        assert abs(table["treatments"][0] - float(exact_rss(one, flat) - exact_rss(one + trts, flat))) < 1e-9
        assert table["error"][1] == (n - 1) * (n - 2)


EXAMPLE_Y = [[30, 32, 31, 31], [37, 34, 36, 28], [29, 31, 31, 30], [37, 31, 37, 25]]


def test_example() -> None:
    sq = mols(4)[0]
    assert sq == [[0, 1, 2, 3], [1, 0, 3, 2], [2, 3, 0, 1], [3, 2, 1, 0]]
    table = latin_square_anova(EXAMPLE_Y, sq)
    expected = {"rows": Fraction(117, 4), "columns": Fraction(269, 4), "treatments": Fraction(257, 4), "error": Fraction(21)}
    for key, value in expected.items():
        assert abs(table[key][0] - float(value)) < 1e-9 and table[key][1] == (3 if key != "error" else 6)
    means = [Fraction(sum(EXAMPLE_Y[i][j] for i in range(4) for j in range(4) if sq[i][j] == s), 4) for s in range(4)]
    assert means == [30, 34, Fraction(119, 4), Fraction(135, 4)]
    assert (expected["treatments"] / 3) / (expected["error"] / 6) == Fraction(257, 42)
    # the one-way analysis of the same data, ignoring rows and columns
    groups = [[Fraction(EXAMPLE_Y[i][j]) for i in range(4) for j in range(4) if sq[i][j] == s] for s in range(4)]
    ssw = sum((v - m) ** 2 for g, m in zip(groups, means) for v in g)
    assert ssw == Fraction(117, 4) + Fraction(269, 4) + 21
    assert abs(float((expected["treatments"] / 3) / (ssw / 12)) - 2.1872) < 1e-4


def test_errors() -> None:
    with pytest.raises(ValueError):
        latin_square_anova([[1.0, 2.0], [3.0, 4.0]], cyclic(2))
    with pytest.raises(ValueError):
        field(6)

References

  1. The Design of Experiments, the chapter on the Latin square (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.4 (more than one blocking component: Latin squares), starting on p. 157, and Appendix 4B (Latin, Graeco-Latin and hyper-Graeco-Latin squares)
  3. Douglas C. Montgomery, Design and Analysis of Experiments, tenth edition, Wiley, 2019, Chapter 4 (the Latin square design and the Graeco-Latin square design; chapter-level locator)
  4. R. C. Bose, S. S. Shrikhande and E. T. Parker, Further results on the construction of mutually orthogonal Latin squares and the falsity of Euler's conjecture, Canadian Journal of Mathematics 12, 1960, pp. 189 to 203 (a pair of orthogonal Latin squares exists for every order except 2 and 6)
  5. J. H. van Lint and R. M. Wilson, A Course in Combinatorics, second edition, Cambridge University Press, 2001, the chapters on Latin squares and on orthogonal Latin squares (general locator, chapter numbers not confirmed)

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/AR1SZ9/text.yaml