Algorithm Search⌘K

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
Properties
deterministicnot exactofflineiterative
Origin
Valerii V. Fedorov, 1972

The Fedorov exchange algorithm builds a D-optimal design with a fixed number of runs NN, chosen from a finite list of candidate settings. It starts from any design whose information matrix M=X⊤XM = X^\top X is nonsingular. In each pass it looks at every pair of a design point xix_i and a candidate xx, and computes in closed form the factor 1+Δ(xi,x)1 + \Delta(x_i, x) by which det⁡M\det M would change if xx replaced xix_i. 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 nn candidate vectors f(c1),…,f(cn)∈Rpf(c_1), \dots, f(c_n) \in \mathbb R^p (the regression functions at the candidate settings), a number of runs N≥pN \ge p, a starting design: a list of NN candidate indices whose X⊤XX^\top X is nonsingular, and a threshold ε≥0\varepsilon \ge 0.

Output. A design x1,…,xNx_1, \dots, x_N (repeats allowed) from which no single exchange of a design point for a candidate raises det⁡X⊤X\det X^\top X by a factor larger than 1+ε1 + \varepsilon.

Notation. M=X⊤X=∑i=1Nf(xi)f(xi)⊤M = X^\top X = \sum_{i=1}^Nf(x_i)f(x_i)^\top, A=M−1A = M^{-1}, d(u,v)=f(u)⊤Af(v)d(u, v) = f(u)^\top Af(v) and d(u)=d(u,u)d(u) = d(u, u). Here d(x)σ2d(x)\sigma^2 is the variance of the fitted mean at xx, and d(xi)d(x_i) is the leverage of the design point xix_i. Exchanging xix_i for xx multiplies the determinant by

det⁡M′det⁡M=1+Δ(xi,x),Δ(xi,x)=d(x)−d(xi)−(d(x)d(xi)−d(x,xi)2).\frac{\det M'}{\det M} = 1 + \Delta(x_i, x), \qquad \Delta(x_i, x) = d(x) - d(x_i) - \bigl(d(x)d(x_i) - d(x, x_i)^2\bigr).

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 AA.

The algorithm

  1. FEDOROV-EXCHANGE(F[1..n], start[1..N], ε)
  2. 1D ← start; M ← Σ_{i=1..N} F[D[i]] F[D[i]]ᵀ ▷ must be nonsingular
  3. 2repeat
  4. 3A ← M⁻¹
  5. 4for each design position i and candidate j:
  6. Δ(i, j) ← d(j) - d(D[i]) - (d(j)·d(D[i]) - d(j, D[i])²) ▷ d(u, v) = F[u]ᵀ A F[v]
  7. 5(i*, j*) ← a pair with the largest Δ
  8. 6if Δ(i*, j*) ≤ ε: return D
  9. 7M ← M - F[D[i*]] F[D[i*]]ᵀ + F[j*] F[j*]ᵀ; D[i*] ← j*

Line L4 computes d(j)d(j) once per candidate and AF[D[i]]AF[D[i]] once per design point, so each Δ\Delta costs one dot product of length pp. Line L3 can be replaced by two Sherman-Morrison updates of AA after each exchange, which cost Θ(p2)\Theta(p^2) instead of Θ(p3)\Theta(p^3).

Example

Quadratic regression, f(x)=(1,x,x2)f(x) = (1, x, x^2), p=N=3p = N = 3, candidates −1,−34,…,1-1, -\frac34, \dots, 1 (9 points), ε=0\varepsilon = 0, start {−12,0,12}\{-\frac12, 0, \frac12\}. Then det⁡M=1/16\det M = 1/16 (the square of the Vandermonde determinant 12⋅1⋅12\frac12 \cdot 1 \cdot \frac12) and

A=M−1=(10−4020−4024).A = M^{-1} = \begin{pmatrix} 1 & 0 & -4 \\ 0 & 2 & 0 \\ -4 & 0 & 24 \end{pmatrix}.

With N=pN = p, every design point has leverage d(xi)=1d(x_i) = 1, so Δ(xi,x)=d(x,xi)2−1\Delta(x_i, x) = d(x, x_i)^2 - 1, and d(x,xi)d(x, x_i) is the Lagrange basis polynomial of xix_i through the design points. For xi=−12x_i = -\frac12 it is 2x(x−12)2x(x - \frac12):

candidate xx −1-1 −34-\frac34 −12-\frac12 −14-\frac14 00 14\frac14 12\frac12 34\frac34 11
Δ(−12,x)\Delta(-\frac12, x) 8 161/64 0 −55/64-55/64 −1-1 −63/64-63/64 −1-1 −55/64-55/64 0

The largest Δ\Delta over all pairs is 8. It is reached by four pairs; the scan order picks −12→−1-\frac12 \to -1, and det⁡M\det M becomes 9⋅116=9169 \cdot \frac1{16} = \frac9{16}. In the second pass, for the design {−1,0,12}\{-1, 0, \frac12\}, the best exchange is 12→1\frac12 \to 1 with Δ=55/9\Delta = 55/9, and det⁡M\det M becomes 916⋅649=4\frac9{16} \cdot \frac{64}9 = 4. In the third pass every Δ≤0\Delta \le 0, and the algorithm returns {−1,0,1}\{-1, 0, 1\}. An exhaustive search over the 165 multisets of 3 candidates confirms that 4 is the largest determinant, and 3 d(x)=3−92x2(1−x2)≤33\,d(x) = 3 - \frac92x^2(1 - x^2) \le 3 on [−1,1][-1, 1], which is the equivalence condition of the Kiefer-Wolfowitz theorem for the approximate design with weights 1/31/3.

A local optimum. For the second-order model in two factors, f=(1,x1,x2,x1x2,x12,x22)f = (1, x_1, x_2, x_1x_2, x_1^2, x_2^2), with N=6N = 6 runs on the grid {−1,0,1}2\{-1, 0, 1\}^2, the best design has det⁡X⊤X=256\det X^\top X = 256 (by exhaustive search over 3003 designs). The design {(−1,1),(0,1),(−1,0),(0,−1),(1,1),(1,0)}\{(-1, 1), (0, 1), (-1, 0), (0, -1), (1, 1), (1, 0)\} has det⁡X⊤X=64\det X^\top X = 64, 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 N=7N = 7, 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 f(x)f(x) multiplies det⁡M\det M by 1+d(x)1 + d(x), and removing f(xi)f(x_i) from the result multiplies it by 1−d(xi)+d(x,xi)2/(1+d(x))1 - d(x_i) + d(x, x_i)^2/(1 + d(x)); the product is 1+Δ(xi,x)1 + \Delta(x_i, x). So the algorithm makes an exchange only when it multiplies det⁡M\det M by more than 1+ε≥11 + \varepsilon \ge 1. The determinant stays positive, so MM 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 1+ε1 + \varepsilon. For ε>0\varepsilon > 0 the number of exchanges is at most log⁡(Dmax⁡/D0)/log⁡(1+ε)\log(D_{\max}/D_0)/\log(1 + \varepsilon), where D0D_0 and Dmax⁡D_{\max} are the starting and the largest determinants.

The algorithm does not prove global optimality. The certificate for that is the approximate theory: if max⁡xN d(x)=p\max_xN\,d(x) = p over the region, the exact design is also an optimal approximate design and therefore globally D-optimal among exact designs with NN runs; otherwise, the D-efficiency (det⁡(X⊤X/N)/det⁡M∗)1/p(\det(X^\top X/N)/\det M^*)^{1/p} against the approximate optimum M∗M^* is a lower bound for its efficiency among exact designs with NN 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 f(c1),…,f(cn)∈Rpf(c_1), \dots, f(c_n) \in \mathbb R^p, a design is a list DD of NN candidate indices, MD=∑i=1Nf(xi)f(xi)⊤M_D = \sum_{i=1}^Nf(x_i)f(x_i)^\top with xi=cD[i]x_i = c_{D[i]}, and the start has det⁡MD>0\det M_D > 0. For an invertible MM, write A=M−1A = M^{-1}, d(u,v)=f(u)⊤Af(v)d(u, v) = f(u)^\top Af(v) and d(u)=d(u,u)d(u) = d(u, u).

Lemma 1 (matrix determinant lemma). For an invertible symmetric MM and a vector vv, det⁡(M+svv⊤)=det⁡M (1+s v⊤M−1v)\det(M + svv^\top) = \det M\,(1 + s\,v^\top M^{-1}v) for s=±1s = \pm1. If 1+s v⊤M−1v≠01 + s\,v^\top M^{-1}v \ne 0, then

(M+svv⊤)−1=M−1−s M−1vv⊤M−11+s v⊤M−1v.(M + svv^\top)^{-1} = M^{-1} - \frac{s\,M^{-1}vv^\top M^{-1}}{1 + s\,v^\top M^{-1}v}.

Proof. M+svv⊤=M(I+sM−1vv⊤)M + svv^\top = M(I + sM^{-1}vv^\top), and I+suw⊤I + suw^\top has the eigenvalue 1+sw⊤u1 + sw^\top u on uu and 1 on the (p−1)(p - 1)-dimensional space orthogonal to ww, so its determinant is 1+sw⊤u1 + sw^\top u. With u=M−1vu = M^{-1}v and w=vw = v this gives the first claim. The second is the Sherman-Morrison formula: multiply the right side by M+svv⊤M + svv^\top and expand. □\square

Lemma 2 (the exchange ratio). Let MM be positive definite and let M′=M−f(xi)f(xi)⊤+f(x)f(x)⊤M' = M - f(x_i)f(x_i)^\top + f(x)f(x)^\top. Then

det⁡M′=det⁡M (1+Δ(xi,x)),Δ(xi,x)=d(x)−d(xi)−(d(x)d(xi)−d(x,xi)2).\det M' = \det M\,\bigl(1 + \Delta(x_i, x)\bigr), \qquad \Delta(x_i, x) = d(x) - d(x_i) - \bigl(d(x)d(x_i) - d(x, x_i)^2\bigr).

Proof. Let g=f(xi)g = f(x_i) and h=f(x)h = f(x), and let K=M+hh⊤K = M + hh^\top. By Lemma 1 with s=1s = 1, det⁡K=det⁡M (1+d(x))\det K = \det M\,(1 + d(x)), and 1+d(x)≥11 + d(x) \ge 1 since AA is positive definite, so

K−1=A−Ahh⊤A1+d(x),g⊤K−1g=d(xi)−d(x,xi)21+d(x).K^{-1} = A - \frac{Ahh^\top A}{1 + d(x)}, \qquad g^\top K^{-1}g = d(x_i) - \frac{d(x, x_i)^2}{1 + d(x)}.

KK is invertible, so Lemma 1 with s=−1s = -1 applied to M′=K−gg⊤M' = K - gg^\top gives

det⁡M′=det⁡K (1−g⊤K−1g)=det⁡M [(1+d(x))(1−d(xi))+d(x,xi)2].\det M' = \det K\,(1 - g^\top K^{-1}g) = \det M\,\Bigl[(1 + d(x))(1 - d(x_i)) + d(x, x_i)^2\Bigr].

Expanding the bracket gives 1+d(x)−d(xi)−d(x)d(xi)+d(x,xi)2=1+Δ(xi,x)1 + d(x) - d(x_i) - d(x)d(x_i) + d(x, x_i)^2 = 1 + \Delta(x_i, x). The formula holds also when 1−g⊤K−1g=01 - g^\top K^{-1}g = 0; then M′M' is singular. □\square

Line L4 computes Δ\Delta for every pair from A=M−1A = M^{-1} (line L3), and line L7 forms exactly the matrix M′M' of Lemma 2 for the chosen pair, so after line L7, M=MDM = M_D for the new list DD.

Lemma 3 (invariant). At the start of every pass, M=MDM = M_D and det⁡MD≥det⁡Mstart>0\det M_D \ge \det M_{\text{start}} > 0. Every exchange multiplies det⁡MD\det M_D by a factor larger than 1+ε≥11 + \varepsilon \ge 1.

Proof. By induction on the passes. The claim holds before the first pass. In a pass, MM is invertible by the hypothesis, so line L3 is defined. The algorithm exchanges only if Δ(i∗,j∗)>ε\Delta(i^*, j^*) > \varepsilon, and then by Lemma 2 the new determinant is (1+Δ(i∗,j∗))det⁡MD>(1+ε)det⁡MD≥det⁡MD>0(1 + \Delta(i^*, j^*))\det M_D > (1 + \varepsilon)\det M_D \ge \det M_D > 0. □\square

Theorem (termination). The algorithm stops after at most (n+N−1N)−1\binom{n + N - 1}N - 1 exchanges. If ε>0\varepsilon > 0, it stops after at most log⁡(Dmax⁡/D0)/log⁡(1+ε)\log(D_{\max}/D_0)/\log(1 + \varepsilon) exchanges, with D0D_0 the starting determinant and Dmax⁡D_{\max} the largest determinant of a design.

Proof. det⁡MD\det M_D depends only on the multiset of indices in DD. By Lemma 3 it strictly increases at each exchange, so no multiset appears twice. There are (n+N−1N)\binom{n + N - 1}N multisets of size NN from nn candidates, which bounds the number of designs visited. If ε>0\varepsilon > 0, after TT exchanges Dmax⁡≥det⁡MD>(1+ε)TD0D_{\max} \ge \det M_D > (1 + \varepsilon)^TD_0, which gives the second bound. □\square

Theorem (correctness). The returned design DD has det⁡MD≥det⁡Mstart>0\det M_D \ge \det M_{\text{start}} > 0, and for every position ii and candidate jj, the design D′D' obtained by replacing D[i]D[i] by jj has det⁡MD′≤(1+ε)det⁡MD\det M_{D'} \le (1 + \varepsilon)\det M_D. With ε=0\varepsilon = 0, no single exchange increases the determinant.

Proof. The first claim is Lemma 3. The algorithm returns at line L6 only when the largest Δ\Delta over all pairs is at most ε\varepsilon, and by Lemma 2, det⁡MD′=(1+Δ(i,j))det⁡MD≤(1+ε)det⁡MD\det M_{D'} = (1 + \Delta(i, j))\det M_D \le (1 + \varepsilon)\det M_D for every pair. □\square

What is not claimed. The returned design is a local optimum for one exchange, not a global one. The page gives a design with det⁡X⊤X=64\det X^\top X = 64 for the second-order model in two factors with 6 runs on {−1,0,1}2\{-1, 0, 1\}^2, 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 max⁡xN d(x)=p\max_xN\,d(x) = p, which by the Kiefer-Wolfowitz theorem makes the design optimal even among approximate designs.

Complexity

One pass costs Θ(p3)\Theta(p^3) for AA, Θ(np2)\Theta(np^2) for d(x)d(x) at all candidates, Θ(Np2)\Theta(Np^2) for Af(xi)Af(x_i) at the design points, and Θ(Nnp)\Theta(Nnp) for all NnNn cross terms: Θ(p3+np2+Nnp)\Theta(p^3 + np^2 + Nnp) with N≤nN \le n. With Sherman-Morrison updates instead of line L3, the p3p^3 term drops to p2p^2 per exchange. The number of passes T+1T + 1 has no good bound in general; in exact arithmetic it is at most the number of designs, (n+N−1N)\binom{n + N - 1}N, and with a threshold ε\varepsilon it is at most 1+log⁡(Dmax⁡/D0)/log⁡(1+ε)1 + \log(D_{\max}/D_0)/\log(1 + \varepsilon). In practice it is small: in the runs above, at most 5. Extra space is Θ(p2)\Theta(p^2) for AA and Θ(n)\Theta(n) for the values d(x)d(x).

Properties

  • Monotone. det⁡M\det M strictly increases at every exchange.
  • Invariant to the parametrization. Replacing ff by TfTf with TT nonsingular multiplies every determinant by (det⁡T)2(\det T)^2, so the ratios 1+Δ1 + \Delta 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 ε=0\varepsilon = 0, 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 ε\varepsilon.

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 NN 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 N±kN \pm k points before it returns to NN.
  • kk-exchange. Consider only the kk 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 X⊤XX^\top X; with NN close to pp 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 [−1,1][-1, 1] the D-optimal support is ±1\pm1 and ±1/5\pm1/\sqrt5, which a grid of step 0.10.1 cannot contain.
  • Floating point. With floats, Δ values near 0 can make the loop cycle between designs of equal determinant. Use ε>0\varepsilon > 0, such as 10−910^{-9}.
  • Model dependence. The design is optimal for the assumed model only. The D-optimal 3-run design for a quadratic model, {−1,0,1}\{-1, 0, 1\}, leaves no degrees of freedom to detect a cubic term or to estimate σ2\sigma^2.

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.

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

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

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