Algorithmadvanced
Fedorov exchange algorithm
Also called Fedorov algorithm, point exchange algorithm.
Builds an exact D-optimal design by swapping a design point for a candidate point whenever the swap increases the determinant of the information matrix.
- Time
- O((T + 1)(p^3 + n p^2 + N n p)) worstΘ(p^3 + n p^2 + N n p) best
- Space
- Θ(n + p^2) extra
- Where
- N = the number of runs; T = the number of exchanges made; n = the number of candidate points; p = the number of model parameters
- Model
- Real RAM
- Properties
- deterministicnot exactofflineiterative
- Evidence
- Proof sketchCode in 1 languages
- Origin
- Valerii V. Fedorov, 1972
The Fedorov exchange algorithm builds a D-optimal design with a fixed number of runs , chosen from a finite list of candidate settings. It starts from any design whose information matrix is nonsingular. In each pass it looks at every pair of a design point and a candidate , and computes in closed form the factor by which would change if replaced . It makes the best exchange and repeats until no exchange raises the determinant. It is a local search, a form of hill climbing, on a problem that is NP-hard in general (see optimal experimental design), so the result is a local optimum. In practice it is run from several random starts.
In plain words
You have a budget of runs and a list of settings you could use. You start with any plan that lets the model be fitted. Then you look for one swap: take out one run and put in a run at another setting, so that the plan gets better. There is a quick formula that says how much better each swap would make the plan, so you do not need to refit anything to compare swaps. You do the best swap and look again. When no swap helps, you stop. The plan you end with cannot be improved by one swap, but a better plan that needs several swaps at once can still exist, so people restart from several plans and keep the best.
The problem
Input. A list of candidate vectors (the regression functions at the candidate settings), a number of runs , a starting design: a list of candidate indices whose is nonsingular, and a threshold .
Output. A design (repeats allowed) from which no single exchange of a design point for a candidate raises by a factor larger than .
Notation. , , and . Here is the variance of the fitted mean at , and is the leverage of the design point . Exchanging for multiplies the determinant by
The first two terms say: bring in a point of high variance, take out a point of low variance. The bracket corrects for the overlap of the two points. It is at least 0 by the Cauchy-Schwarz inequality in the inner product given by .
The algorithm
FEDOROV-EXCHANGE(F[1..n], start[1..N], ε)- 1
D ← start; M ← Σ_{i=1..N} F[D[i]] F[D[i]]ᵀ ▷ must be nonsingular - 2
repeat - 3
A ← M⁻¹ - 4
for each design position i and candidate j: Δ(i, j) ← d(j) - d(D[i]) - (d(j)·d(D[i]) - d(j, D[i])²) ▷ d(u, v) = F[u]ᵀ A F[v]- 5
(i*, j*) ← a pair with the largest Δ - 6
if Δ(i*, j*) ≤ ε: return D - 7
M ← M - F[D[i*]] F[D[i*]]ᵀ + F[j*] F[j*]ᵀ; D[i*] ← j*
Line L4 computes once per candidate and once per design point, so each costs one dot product of length . Line L3 can be replaced by two Sherman-Morrison updates of after each exchange, which cost instead of .
Example
Quadratic regression, , , candidates (9 points), , start . Then (the square of the Vandermonde determinant ) and
With , every design point has leverage , so , and is the Lagrange basis polynomial of through the design points. For it is :
| candidate | |||||||||
|---|---|---|---|---|---|---|---|---|---|
| 8 | 161/64 | 0 | 0 |
The largest over all pairs is 8. It is reached by four pairs; the scan order picks , and becomes . In the second pass, for the design , the best exchange is with , and becomes . In the third pass every , and the algorithm returns . An exhaustive search over the 165 multisets of 3 candidates confirms that 4 is the largest determinant, and on , which is the equivalence condition of the Kiefer-Wolfowitz theorem for the approximate design with weights .
A local optimum. For the second-order model in two factors, , with runs on the grid , the best design has (by exhaustive search over 3003 designs). The design has , and no single exchange improves it, so the algorithm stops there when it reaches it. From 100 random nonsingular starts (seed 20261114), 94 runs ended at 256 and 6 at 64, with at most 3 exchanges per run. For , with the same seed, all 100 runs reached the best value 960, with at most 4 exchanges per run.
Correctness
The proof is in proofs/correctness.md. By the matrix determinant lemma (the Sherman-Morrison formula page) applied twice, adding multiplies by , and removing from the result multiplies it by ; the product is . So the algorithm makes an exchange only when it multiplies by more than . The determinant stays positive, so stays invertible. A design cannot appear twice because the determinant strictly increases, and there are finitely many designs, so the loop stops. When it stops, no single exchange raises the determinant by more than the factor . For the number of exchanges is at most , where and are the starting and the largest determinants.
The algorithm does not prove global optimality. The certificate for that is the approximate theory: if over the region, the exact design is also an optimal approximate design and therefore globally D-optimal among exact designs with runs; otherwise, the D-efficiency against the approximate optimum is a lower bound for its efficiency among exact designs with runs.
Proof: Each Fedorov exchange multiplies the determinant by 1 + Delta, so the algorithm increases it strictly, stops, and returns a design that no single exchange improvesfull
The arithmetic is exact. The candidates are vectors , a design is a list of candidate indices, with , and the start has . For an invertible , write , and .
Lemma 1 (matrix determinant lemma). For an invertible symmetric and a vector , for . If , then
Proof. , and has the eigenvalue on and 1 on the -dimensional space orthogonal to , so its determinant is . With and this gives the first claim. The second is the Sherman-Morrison formula: multiply the right side by and expand.
Lemma 2 (the exchange ratio). Let be positive definite and let . Then
Proof. Let and , and let . By Lemma 1 with , , and since is positive definite, so
is invertible, so Lemma 1 with applied to gives
Expanding the bracket gives . The formula holds also when ; then is singular.
Line L4 computes for every pair from (line L3), and line L7 forms exactly the matrix of Lemma 2 for the chosen pair, so after line L7, for the new list .
Lemma 3 (invariant). At the start of every pass, and . Every exchange multiplies by a factor larger than .
Proof. By induction on the passes. The claim holds before the first pass. In a pass, is invertible by the hypothesis, so line L3 is defined. The algorithm exchanges only if , and then by Lemma 2 the new determinant is .
Theorem (termination). The algorithm stops after at most exchanges. If , it stops after at most exchanges, with the starting determinant and the largest determinant of a design.
Proof. depends only on the multiset of indices in . By Lemma 3 it strictly increases at each exchange, so no multiset appears twice. There are multisets of size from candidates, which bounds the number of designs visited. If , after exchanges , which gives the second bound.
Theorem (correctness). The returned design has , and for every position and candidate , the design obtained by replacing by has . With , no single exchange increases the determinant.
Proof. The first claim is Lemma 3. The algorithm returns at line L6 only when the largest over all pairs is at most , and by Lemma 2, for every pair.
What is not claimed. The returned design is a local optimum for one exchange, not a global one. The page gives a design with for the second-order model in two factors with 6 runs on , where the global optimum is 256 and the algorithm stops at 64. Global optimality of an exact design follows only from an outside certificate, for example , which by the Kiefer-Wolfowitz theorem makes the design optimal even among approximate designs.
Complexity
One pass costs for , for at all candidates, for at the design points, and for all cross terms: with . With Sherman-Morrison updates instead of line L3, the term drops to per exchange. The number of passes has no good bound in general; in exact arithmetic it is at most the number of designs, , and with a threshold it is at most . In practice it is small: in the runs above, at most 5. Extra space is for and for the values .
Properties
- Monotone. strictly increases at every exchange.
- Invariant to the parametrization. Replacing by with nonsingular multiplies every determinant by , so the ratios and the whole run do not change.
- Local optimality. The result is optimal with respect to one exchange. It depends on the start and on the order in which ties are broken.
- Exact arithmetic. With rational candidates and , every quantity is rational and the run is exact, as in the implementation.
- No refitting. The responses are not used. The whole run depends only on the candidate vectors, the start and .
Variants and improvements
- Modified Fedorov (Cook and Nachtsheim 1980). Visit the design points in turn and make the best exchange for each, so that one pass can make up to exchanges. It needs about the same work per pass and fewer passes.
- Wynn-Mitchell and DETMAX (Mitchell 1974). Add the point of largest variance and then remove the point of smallest variance; DETMAX allows longer excursions through designs of points before it returns to .
- -exchange. Consider only the design points of lowest leverage for removal, which cuts the cost of a pass.
- Coordinate exchange (Meyer and Nachtsheim 1995). Change one coordinate of one design point at a time over its levels, without a candidate list. The candidate list grows exponentially with the number of factors, so this is the method used in most design software for many factors.
- Approximate designs. Adding weight at the point of largest variance, without removing a point, is the vertex direction method of Wynn (1970) and Fedorov (1972), the same iteration as Khachiyan's algorithm for the minimum volume enclosing ellipsoid. It converges to the approximate optimum.
- Other criteria. The same exchange idea works for A-, I- and other criteria, with an update formula for each.
When to use it
Use it when the region is irregular, the model is not one of the standard ones, or the run budget does not fit a classical design: a constrained region, a mixture with bounds, a model with selected interaction terms, or an odd number of runs. For a first-order model on a cube or a standard second-order model, classical designs such as a factorial design or the central composite designs of response surface methodology are already D-optimal or close to it. With many factors, use coordinate exchange instead of a candidate list.
Pitfalls
- Local optima. One run proves nothing about global optimality. Use many random starts, and compare with the approximate optimum.
- Singular starts. The start must have a nonsingular ; with close to random starts are often singular and must be redrawn.
- The candidate list. The result is only as good as the list. A coarse grid misses the optimum: for a cubic model on the D-optimal support is and , which a grid of step cannot contain.
- Floating point. With floats, Δ values near 0 can make the loop cycle between designs of equal determinant. Use , such as .
- Model dependence. The design is optimal for the assumed model only. The D-optimal 3-run design for a quadratic model, , leaves no degrees of freedom to detect a cubic term or to estimate .
Implementations
Each implementation follows the pseudocode above. A comment @line links a line of code to a line of the pseudocode. Point at a line of the pseudocode to see the matching code. The build runs the native tests of each language.
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/fedorov-exchange-algorithm/. The authors are listed in prov/75MV1N.jsonl.
"""Fedorov's exchange algorithm for exact D-optimal designs.
An exact design is a list of N points taken from a finite candidate list C,
repeats allowed. With regression functions f(x) in R^p, its information
matrix is M = sum_i f(x_i) f(x_i)^T. One exchange replaces a design point x_i
by a candidate x. With A = M^(-1) and d(u, v) = f(u)^T A f(v), d(u) = d(u, u),
det M' / det M = 1 + Delta(x_i, x),
Delta(x_i, x) = d(x) - d(x_i) - (d(x) d(x_i) - d(x, x_i)^2).
Each pass takes the exchange with the largest Delta and stops when no Delta
exceeds eps. With Fraction inputs and eps = 0 all arithmetic is exact and the
determinant rises strictly at each exchange, so the loop stops after finitely
many exchanges.
"""
from fractions import Fraction
from typing import NamedTuple
class ExchangeResult(NamedTuple):
design: list # indices into the candidate list, length N
det: object # det M of the final design
exchanges: list # (position, old index, new index, Delta) for each exchange
def info_matrix(rows):
"""M = sum of r r^T over the rows r."""
p = len(rows[0])
m = [[0] * p for _ in range(p)]
for r in rows:
for i in range(p):
ri = r[i]
for j in range(p):
m[i][j] += ri * r[j]
return m
def determinant(m):
"""Determinant by Gaussian elimination with partial pivoting."""
a = [row[:] for row in m]
n = len(a)
d = 1
for c in range(n):
p = max(range(c, n), key=lambda r: abs(a[r][c]))
if a[p][c] == 0:
return 0 * d
if p != c:
a[c], a[p] = a[p], a[c]
d = -d
d = d * a[c][c]
for r in range(c + 1, n):
f = a[r][c] / a[c][c]
if f != 0:
for k in range(c, n):
a[r][k] -= f * a[c][k]
return d
def inverse(m):
"""Inverse by Gauss-Jordan elimination with partial pivoting."""
n = len(m)
one = m[0][0] * 0 + 1
a = [list(row) + [one if i == j else one * 0 for j in range(n)] for i, row in enumerate(m)]
for c in range(n):
p = max(range(c, n), key=lambda r: abs(a[r][c]))
if a[p][c] == 0:
raise ValueError("singular information matrix")
a[c], a[p] = a[p], a[c]
pv = a[c][c]
a[c] = [v / pv for v in a[c]]
for r in range(n):
if r != c and a[r][c] != 0:
f = a[r][c]
a[r] = [x - f * y for x, y in zip(a[r], a[c])]
return [row[n:] for row in a]
def mat_vec(a, v):
return [sum(ai * vi for ai, vi in zip(row, v)) for row in a]
def dot(u, v):
return sum(ui * vi for ui, vi in zip(u, v))
def delta(a, fi, fx):
"""Delta(x_i, x) for A = M^(-1), fi = f(x_i), fx = f(x)."""
afi = mat_vec(a, fi)
di = dot(fi, afi)
dx = dot(fx, mat_vec(a, fx))
dix = dot(fx, afi)
return dx - di - (dx * di - dix * dix)
def fedorov_exchange(candidates, start, eps=0, max_exchanges=10000):
"""Run Fedorov's exchange algorithm.
candidates: list of regression vectors f(x) for the candidate points.
start: list of N candidate indices whose information matrix is nonsingular.
eps: stop when the best Delta is at most eps (use 0 with Fractions).
"""
design = list(start) # @line L1
m = info_matrix([candidates[j] for j in design]) # @line L1
if determinant(m) == 0:
raise ValueError("the starting design has a singular information matrix")
log = []
while len(log) < max_exchanges: # @line L2
a = inverse(m) # @line L3
dc = [dot(fx, mat_vec(a, fx)) for fx in candidates] # @line L4
best = None
for i, j0 in enumerate(design): # @line L4
afi = mat_vec(a, candidates[j0])
di = dc[j0]
for j, fx in enumerate(candidates):
dix = dot(fx, afi)
dl = dc[j] - di - (dc[j] * di - dix * dix) # @line L4
if best is None or dl > best[0]:
best = (dl, i, j) # @line L5
dl, i, j = best # @line L5
if dl <= eps: # @line L6
break
old = design[i]
fo, fn = candidates[old], candidates[j]
p = len(fo)
for r in range(p):
for c in range(p):
m[r][c] += fn[r] * fn[c] - fo[r] * fo[c] # @line L7
design[i] = j # @line L7
log.append((i, old, j, dl))
return ExchangeResult(design, determinant(m), log)
def polynomial_row(x, degree):
"""f(x) = (1, x, ..., x^degree)."""
return [x ** k for k in range(degree + 1)]
def quadratic_surface_row(x1, x2):
"""f(x) = (1, x1, x2, x1 x2, x1^2, x2^2), the second-order model in two factors."""
return [x1 * 0 + 1, x1, x2, x1 * x2, x1 * x1, x2 * x2]
if __name__ == "__main__":
grid = [Fraction(k, 4) for k in range(-4, 5)]
cands = [polynomial_row(x, 2) for x in grid]
res = fedorov_exchange(cands, [grid.index(Fraction(-1, 2)), grid.index(0), grid.index(Fraction(1, 2))])
print("design", [str(grid[j]) for j in res.design], "det", res.det)
for i, old, new, dl in res.exchanges:
print("swap", grid[old], "->", grid[new], "Delta", dl)
test_fedorov_exchange_algorithm.py 122 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/fedorov-exchange-algorithm/. The authors are listed in prov/75MV1N.jsonl.
import itertools
import random
from fractions import Fraction
import pytest
from fedorov_exchange_algorithm import (
delta, determinant, dot, fedorov_exchange, info_matrix, inverse, mat_vec,
polynomial_row, quadratic_surface_row,
)
GRID = [Fraction(k, 4) for k in range(-4, 5)]
QUAD = [polynomial_row(x, 2) for x in GRID]
SQUARE = [(Fraction(a), Fraction(b)) for a in (-1, 0, 1) for b in (-1, 0, 1)]
SURFACE = [quadratic_surface_row(*p) for p in SQUARE]
def brute_force_max_det(cands, n):
return max(determinant(info_matrix([cands[j] for j in d]))
for d in itertools.combinations_with_replacement(range(len(cands)), n))
def random_start(rng, cands, n):
while True:
s = [rng.randrange(len(cands)) for _ in range(n)]
if determinant(info_matrix([cands[j] for j in s])) != 0:
return s
def test_worked_example():
start = [GRID.index(Fraction(-1, 2)), GRID.index(0), GRID.index(Fraction(1, 2))]
res = fedorov_exchange(QUAD, start)
assert sorted(GRID[j] for j in res.design) == [-1, 0, 1]
assert res.det == 4
assert [e[3] for e in res.exchanges] == [8, Fraction(55, 9)]
def test_quadratic_three_runs_find_minus_one_zero_one():
assert brute_force_max_det(QUAD, 3) == 4
rng = random.Random(1)
for _ in range(3):
res = fedorov_exchange(QUAD, random_start(rng, QUAD, 3))
assert sorted(GRID[j] for j in res.design) == [-1, 0, 1]
assert res.det == 4
def test_determinant_ratio_formula_exact():
rng = random.Random(7)
for _ in range(200):
cands = SURFACE if rng.random() < 0.5 else QUAD
n = len(cands[0]) + rng.randrange(3)
s = random_start(rng, cands, n)
m = info_matrix([cands[j] for j in s])
a = inverse(m)
i, j = rng.randrange(n), rng.randrange(len(cands))
t = list(s)
t[i] = j
m2 = info_matrix([cands[k] for k in t])
assert determinant(m2) == determinant(m) * (1 + delta(a, cands[s[i]], cands[j]))
def test_each_exchange_raises_determinant():
rng = random.Random(3)
for _ in range(20):
s = random_start(rng, SURFACE, 8)
d0 = determinant(info_matrix([SURFACE[j] for j in s]))
res = fedorov_exchange(SURFACE, s)
prod = Fraction(1)
for _, _, _, dl in res.exchanges:
assert dl > 0
prod *= 1 + dl
assert res.det == d0 * prod
def test_stops_at_one_exchange_optimum():
rng = random.Random(5)
s = random_start(rng, SURFACE, 7)
res = fedorov_exchange(SURFACE, s)
d = res.det
for i in range(len(res.design)):
for j in range(len(SURFACE)):
t = list(res.design)
t[i] = j
assert determinant(info_matrix([SURFACE[k] for k in t])) <= d
def test_second_order_surface_against_brute_force():
best = brute_force_max_det(SURFACE, 6)
assert best == 256
rng = random.Random(20261114)
found = [fedorov_exchange(SURFACE, random_start(rng, SURFACE, 6)).det for _ in range(10)]
assert max(found) == best
assert all(f <= best for f in found)
def test_equivalence_theorem_at_the_optimum():
res = fedorov_exchange(QUAD, [0, 1, 2])
m = info_matrix([QUAD[j] for j in res.design])
a = inverse(m)
n = len(res.design)
dn = [n * dot(f, mat_vec(a, f)) for f in QUAD]
assert max(dn) == 3
assert {GRID[j] for j, v in enumerate(dn) if v == 3} == {-1, 0, 1}
def test_floating_point_with_threshold():
grid = [k / 10 for k in range(-10, 11)]
cands = [polynomial_row(x, 3) for x in grid]
start = [grid.index(v) for v in (-0.5, -0.2, 0.3, 0.6)]
res = fedorov_exchange(cands, start, eps=1e-9)
pts = sorted(grid[j] for j in res.design)
exact = brute_force_max_det(cands, 4)
assert res.det == pytest.approx(exact, rel=1e-9)
assert pts[0] == -1.0 and pts[-1] == 1.0
def test_singular_start_rejected():
with pytest.raises(ValueError):
fedorov_exchange(QUAD, [0, 0, 1])
History
The approximate theory of Kiefer (1959) and Kiefer and Wolfowitz (1960) gave the optimality conditions. Wynn (1970) and Fedorov (1972) turned them into the iteration that adds the point of largest variance, and Fedorov (1972) gave the exchange for a fixed number of runs, with the closed-form ratio of determinants. Mitchell (1974) gave DETMAX, Cook and Nachtsheim (1980) compared the exchange methods and gave the modified Fedorov algorithm, and Meyer and Nachtsheim (1995) gave coordinate exchange.
References
- V. V. Fedorov, Theory of Optimal Experiments, translated and edited by W. J. Studden and E. M. Klimko, Academic Press, 1972, The whole book (the exchange procedure for designs with a fixed number of runs and the determinant ratio of one exchange; general locator)
- R. Dennis Cook and Christopher J. Nachtsheim, A comparison of algorithms for constructing exact D-optimal designs, Technometrics 22(3), 1980, pp. 315 to 324, The whole paper (the comparison of exchange algorithms and the modified Fedorov algorithm)
- Toby J. Mitchell, An algorithm for the construction of D-optimal experimental designs, Technometrics 16(2), 1974, pp. 203 to 210, The whole paper (the DETMAX algorithm and its excursions)
- Ruth K. Meyer and Christopher J. Nachtsheim, The coordinate-exchange algorithm for constructing exact optimal experimental designs, Technometrics 37(1), 1995, pp. 60 to 69, The whole paper (exchange of one coordinate at a time without a candidate list)
- Henry P. Wynn, The sequential generation of D-optimum experimental designs, Annals of Mathematical Statistics 41(5), 1970, pp. 1655 to 1664, The whole paper (adding the point of largest variance; the approximate design version)
- A. C. Atkinson, A. N. Donev and R. D. Tobias, Optimum Experimental Designs, with SAS, Oxford University Press, 2007, Chapter 12 (algorithms for the construction of exact D-optimum designs)
About this page
The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.
| Ladder | Level | What the next level needs |
|---|---|---|
| Human proof | H1 sketch |
|
| Lean | L0 no Lean part |
|
| Code (python) | I0 not checked yet |
|
| Visual | V0 none |
|
| Writing | W2 basic |
|
Tag 75MV1N Edit this page History Report an error Markdown