Algorithm Search⌘K

Algorithmadvanced

Alpha-expansion

Also called expansion move algorithm, Boykov-Veksler-Zabih expansion.

Minimize a multi-label energy with a metric pairwise term by repeated min cuts, each letting any set of sites switch to one label alpha. Within 2c of the optimum, so 2 for Potts.

Time
O(k L (F + n + m)) worst · averageO(L (F + n + m)) best
Space
O(n + m) extra
Where
F = the time of one max flow on n + 2 nodes and n + m edges; L = the number of labels; k = the number of cycles over the labels; m = the number of neighbor pairs; n = the number of sites
Properties
deterministicnot exactofflineiterative
Origin
Yuri Boykov, Olga Veksler, Ramin Zabih, 2001

Alpha-expansion is a method for labeling problems: give each of nn sites one of LL labels so that a sum of costs is small. Each site pays a cost for its own label, and each neighbor pair pays a cost VV that depends on the two labels, for example a fixed penalty when they differ. The method improves a labeling by moves. An α\alpha-expansion move picks one label α\alpha and lets any subset of the sites change to α\alpha at once, while the other sites keep their labels. There are 2n2^n such subsets, but when VV is a metric the best one is found exactly by one minimum cut, because the energy of the move is a regular binary energy (the Kolmogorov-Zabih theorem). The algorithm cycles over the labels until no move lowers the energy. Finding the best labeling is NP-hard already for the Potts model with three labels, but the result of alpha-expansion is within a factor 2c2c of the optimum, where cc is the ratio of the largest to the smallest cost of two different labels, so within 2 for Potts. It is a standard method for MAP inference in Markov random fields on images and meshes: stereo, segmentation, image stitching and mesh segmentation.

In plain words

Each pixel needs a label, such as a depth or a color class. A label that fits the pixel is cheap, and two neighbors with different labels pay a penalty. Start with any labeling. Now pick one label and ask: which pixels should switch to this label, all at once, to lower the total cost the most? Any group of pixels may switch, which is far more than trying one pixel at a time, and a minimum cut in a graph finds the best group exactly. Do this for each label in turn, and repeat the whole round until no label helps. The answer is not always the best one, but it cannot be worse than twice the best for the simple penalty.

The problem

Input. A set of nn sites, a set N\mathcal{N} of mm neighbor pairs with weights wpq≥0w_{pq} \ge 0, a set of LL labels, data costs Dp(ℓ)≥0D_p(\ell) \ge 0, and a metric VV on the labels: V(a,b)=0V(a, b) = 0 exactly when a=ba = b, V(a,b)=V(b,a)≥0V(a, b) = V(b, a) \ge 0, and V(a,b)≤V(a,c)+V(c,b)V(a, b) \le V(a, c) + V(c, b).

Output. A labeling ff with small energy

E(f)=∑pDp(fp)+∑(p,q)∈Nwpq V(fp,fq),E(f) = \sum_p D_p(f_p) + \sum_{(p,q) \in \mathcal{N}} w_{pq}\, V(f_p, f_q),

which no α\alpha-expansion improves, for any label α\alpha. An α\alpha-expansion of ff is any labeling gg with gp∈{fp,α}g_p \in \{f_p, \alpha\} for all pp.

Examples of metrics are the Potts model V(a,b)=λ[a≠b]V(a,b) = \lambda [a \ne b] and the truncated linear distance V(a,b)=min⁡(∣a−b∣,K)V(a,b) = \min(|a - b|, K) on ordered labels. The truncated quadratic min⁡((a−b)2,K)\min((a - b)^2, K) is not a metric; it is only a semimetric, which suits alpha-beta swap.

The algorithm

  1. ALPHA-EXPANSION(D, V, N, f)
  2. 1repeat
  3. 2success ← false
  4. 3for each label α do
  5. 4build the binary energy B(x) = E(g(x)), where g(x)_p = α if x_p = 1 and f_p if x_p = 0
  6. 5x ← a minimizer of B by one minimum cut
  7. 6f' ← g(x)
  8. 7if E(f') < E(f) then f ← f'; success ← true
  9. 8until success = false
  10. 9return f

For a pair (p,q)(p, q), the move energy has the four values wV(fp,fq)w V(f_p, f_q), wV(fp,α)w V(f_p, \alpha), wV(α,fq)w V(\alpha, f_q) and wV(α,α)=0w V(\alpha, \alpha) = 0 for (xp,xq)=(0,0),(0,1),(1,0),(1,1)(x_p, x_q) = (0,0), (0,1), (1,0), (1,1). It is regular when V(fp,fq)≤V(fp,α)+V(α,fq)V(f_p, f_q) \le V(f_p, \alpha) + V(\alpha, f_q), which is the triangle inequality. Line L5 builds the graph of the theorem page: an edge p→qp \to q of capacity w(V(fp,α)+V(α,fq)−V(fp,fq))w(V(f_p, \alpha) + V(\alpha, f_q) - V(f_p, f_q)) for each pair, and an edge from the source or to the sink for the linear part of each site. Boykov, Veksler and Zabih built a different graph, with an extra node on each pair whose ends have different labels; both give the same minimum. The code checks regularity and stops with an error on a nonregular pair term, which happens when VV is not a metric.

Example

Take four sites in a row, labels 0, 1, 2, the Potts model with λ=4\lambda = 4, and the data costs

site D(0)D(0) D(1)D(1) D(2)D(2)
0 0 5 1
1 2 6 0
2 6 0 5
3 0 2 5

Start from the best label of each site, f=(0,2,1,0)f = (0, 2, 1, 0), with E=0+3⋅4=12E = 0 + 3 \cdot 4 = 12.

cycle α\alpha best α\alpha-expansion EE accepted
1 0 (0,0,0,0)(0, 0, 0, 0) 8 yes
1 1 (0,0,1,1)(0, 0, 1, 1) 8 no
1 2 (0,0,0,0)(0, 0, 0, 0) 8 no
2 0, 1, 2 no move below 8 8 no

The algorithm stops after two cycles at (0,0,0,0)(0, 0, 0, 0) with E=8E = 8. The optimum is (2,2,1,1)(2, 2, 1, 1) with E=1+0+0+2+4=7E = 1 + 0 + 0 + 2 + 4 = 7. From (0,0,0,0)(0,0,0,0), no single move reaches it, because it uses two new labels. Every 2-expansion that changes a site costs at least 10, for example (2,2,2,0)(2, 2, 2, 0), and the best 1-expansion (0,0,1,1)(0, 0, 1, 1) only ties at 8. The ratio 8/78/7 is well below the bound 2.

Correctness

The full proof is in proofs/correctness.md. It has three parts. First, the binary energy of line L4 equals the energy of the labeling it describes, and its pair terms are regular by the triangle inequality, so the cut of line L5 gives the best expansion. Second, each accepted move lowers the energy strictly and there are finitely many labelings, so the loop stops, and in the last cycle no label gives an improving expansion. Third, the bound of Theorem 6.1 of Boykov, Veksler and Zabih: compare the output f^\hat f with the expansion that copies an optimal labeling f∗f^* on the sites where fp∗=αf^*_p = \alpha. Each such comparison bounds the energy of f^\hat f on those sites and their pairs. Summed over α\alpha, every pair with fp∗≠fq∗f^*_p \ne f^*_q appears twice and pays at most cc times its cost in f∗f^*, which gives E(f^)≤ED(f∗)+2c EV(f∗)≤2c E(f∗)E(\hat f) \le E_D(f^*) + 2c\, E_V(f^*) \le 2c\, E(f^*).

Proof: Correctness of alpha-expansionfull

The energy is E(f)=∑pDp(fp)+∑(p,q)∈NwpqV(fp,fq)E(f) = \sum_p D_p(f_p) + \sum_{(p,q) \in \mathcal{N}} w_{pq} V(f_p, f_q) with weights wpq≥0w_{pq} \ge 0. We prove three facts: each move of lines L4 to L6 returns a labeling of least energy among all α\alpha-expansions of ff; the loop stops at a labeling f^\hat f that no expansion move improves; and if VV is a metric and Dp≥0D_p \ge 0, then E(f^)≤2c E(f∗)E(\hat f) \le 2c\, E(f^*) for an optimal f∗f^*, where c=max⁡a≠bV(a,b)/min⁡a≠bV(a,b)c = \max_{a \ne b} V(a,b) / \min_{a \ne b} V(a,b).

A metric here is a function with V(a,b)=0V(a,b) = 0 if and only if a=ba = b, V(a,b)=V(b,a)≥0V(a,b) = V(b,a) \ge 0, and V(a,b)≤V(a,c)+V(c,b)V(a,b) \le V(a,c) + V(c,b).

1. Each move is optimal in its move space

An α\alpha-expansion of ff is a labeling gg with gp∈{fp,α}g_p \in \{f_p, \alpha\} for every pp. Write g=g(x)g = g(x) with xp=1x_p = 1 if gp=αg_p = \alpha and xp=0x_p = 0 if gp=fpg_p = f_p; when fp=αf_p = \alpha both values give the same label. Line L4 builds the binary energy

B(x)=∑pUp(xp)+∑(p,q)∈Nθpq(xp,xq),B(x) = \sum_p U_p(x_p) + \sum_{(p,q) \in \mathcal{N}} \theta_{pq}(x_p, x_q),

with Up(0)=Dp(fp)U_p(0) = D_p(f_p), Up(1)=Dp(α)U_p(1) = D_p(\alpha), and θpq(a,b)=wpqV(ℓp(a),ℓq(b))\theta_{pq}(a, b) = w_{pq} V(\ell_p(a), \ell_q(b)) where ℓp(0)=fp\ell_p(0) = f_p and ℓp(1)=α\ell_p(1) = \alpha. By construction B(x)=E(g(x))B(x) = E(g(x)) for every xx.

Each pairwise term is regular:

θpq(0,0)+θpq(1,1)=wpq (V(fp,fq)+V(α,α))≤wpq (V(fp,α)+V(α,fq))=θpq(0,1)+θpq(1,0),\theta_{pq}(0,0) + \theta_{pq}(1,1) = w_{pq}\,(V(f_p, f_q) + V(\alpha, \alpha)) \le w_{pq}\,(V(f_p, \alpha) + V(\alpha, f_q)) = \theta_{pq}(0,1) + \theta_{pq}(1,0),

by V(α,α)=0V(\alpha, \alpha) = 0 and the triangle inequality. So BB is in the class F2\mathcal{F}^2 and regular, and by the Kolmogorov-Zabih theorem it is represented by the graph that the code builds: for each pair term, the edge p→qp \to q of capacity θ(0,1)+θ(1,0)−θ(0,0)−θ(1,1)≥0\theta(0,1) + \theta(1,0) - \theta(0,0) - \theta(1,1) \ge 0, and for the coefficient λp\lambda_p of xpx_p in the remaining linear part, an edge s→ps \to p of capacity λp\lambda_p if λp>0\lambda_p > 0 or an edge p→tp \to t of capacity −λp-\lambda_p if λp<0\lambda_p < 0. A minimum cut gives a minimizer xx of BB with xp=0x_p = 0 on the source side (the last paragraph of the proof on the theorem page). Line L6 returns g(x)g(x), which therefore has the least energy among all α\alpha-expansions of ff.

2. Termination and local optimality

Line L7 replaces ff only by a labeling of strictly smaller energy. There are LnL^n labelings, so there are finitely many replacements, and some cycle of lines L3 to L7 has no replacement. Then line L8 stops. In that last cycle ff did not change, so for every label α\alpha the optimal α\alpha-expansion of ff has energy at least E(f)E(f). Since ff is itself an α\alpha-expansion of ff (with x=0x = 0), no α\alpha-expansion has smaller energy than ff, for any α\alpha. With integer energies there are at most E(f0)−min⁡E+1E(f_0) - \min E + 1 cycles.

3. The bound E(f^)≤2c E(f∗)E(\hat f) \le 2c\, E(f^*)

Let f^\hat f be the output and f∗f^* an optimal labeling. For a label α\alpha let Pα={p:fp∗=α}P_\alpha = \{p : f^*_p = \alpha\}, and let fαf^\alpha be the α\alpha-expansion of f^\hat f with fpα=αf^\alpha_p = \alpha for p∈Pαp \in P_\alpha and fpα=f^pf^\alpha_p = \hat f_p otherwise. Split the pairs into IαI_\alpha (both ends in PαP_\alpha), BαB_\alpha (exactly one end in PαP_\alpha) and the rest. For a set QQ of sites and a set MM of pairs write EQD(f)=∑p∈QDp(fp)E^D_Q(f) = \sum_{p \in Q} D_p(f_p) and EMV(f)=∑(p,q)∈MwpqV(fp,fq)E^V_M(f) = \sum_{(p,q) \in M} w_{pq} V(f_p, f_q).

By part 2, E(f^)≤E(fα)E(\hat f) \le E(f^\alpha). The labelings f^\hat f and fαf^\alpha agree outside PαP_\alpha, so the terms of the sites outside PαP_\alpha and of the pairs with no end in PαP_\alpha cancel, and

EPαD(f^)+EIα∪BαV(f^)≤EPαD(fα)+EIαV(fα)+EBαV(fα).E^D_{P_\alpha}(\hat f) + E^V_{I_\alpha \cup B_\alpha}(\hat f) \le E^D_{P_\alpha}(f^\alpha) + E^V_{I_\alpha}(f^\alpha) + E^V_{B_\alpha}(f^\alpha).

On PαP_\alpha, fα=α=f∗f^\alpha = \alpha = f^*, so the first two terms on the right equal EPαD(f∗)E^D_{P_\alpha}(f^*) and EIαV(f∗)E^V_{I_\alpha}(f^*). For a pair of BαB_\alpha with p∈Pαp \in P_\alpha and q∉Pαq \notin P_\alpha, we have fp∗=α≠fq∗f^*_p = \alpha \ne f^*_q, and V(fpα,fqα)=V(α,f^q)V(f^\alpha_p, f^\alpha_q) = V(\alpha, \hat f_q). If f^q=α\hat f_q = \alpha this is 0. Otherwise it is at most max⁡a≠bV≤cmin⁡a≠bV≤c V(α,fq∗)=c V(fp∗,fq∗)\max_{a \ne b} V \le c \min_{a \ne b} V \le c\, V(\alpha, f^*_q) = c\, V(f^*_p, f^*_q). So

EPαD(f^)+EIα∪BαV(f^)≤EPαD(f∗)+EIαV(f∗)+c EBαV(f∗).E^D_{P_\alpha}(\hat f) + E^V_{I_\alpha \cup B_\alpha}(\hat f) \le E^D_{P_\alpha}(f^*) + E^V_{I_\alpha}(f^*) + c\, E^V_{B_\alpha}(f^*).

Sum over all labels α\alpha. The sets PαP_\alpha partition the sites, so the data terms sum to ED(f^)E_D(\hat f) and ED(f∗)E_D(f^*). A pair with fp∗=fq∗f^*_p = f^*_q is in exactly one IαI_\alpha and in no BαB_\alpha; a pair with fp∗≠fq∗f^*_p \ne f^*_q is in exactly two sets BαB_\alpha and in no IαI_\alpha. On the left every pair appears at least once and V≥0V \ge 0, so the left sum is at least E(f^)E(\hat f). On the right the pairs of the first kind have V(fp∗,fq∗)=0V(f^*_p, f^*_q) = 0, and those of the second kind appear twice with the factor cc. Hence

E(f^)≤ED(f∗)+2c EV(f∗)≤2c E(f∗),E(\hat f) \le E_D(f^*) + 2c\, E_V(f^*) \le 2c\, E(f^*),

where the last step uses c≥1c \ge 1 and ED(f∗)≥0E_D(f^*) \ge 0. For the Potts model c=1c = 1 and the factor is 2. □\square

The bound needs only that f^\hat f is a local minimum for expansion moves, so it holds for any order of the labels and any start. It is Theorem 6.1 of Boykov, Veksler and Zabih (2001).

Complexity

The model is the real RAM; the tests use integer costs, so that the cuts and the comparisons are exact.

  • One move. Building the graph takes O(n+m)O(n + m) time, and the cut takes the time FF of one max-flow computation on n+2n + 2 nodes and at most n+mn + m edges. The code uses Edmonds-Karp for clarity; programs on images use the Boykov-Kolmogorov algorithm, whose speed on such grids is measured, not bounded.
  • One cycle. LL moves and LL energy evaluations, O(L(F+n+m))O(L(F + n + m)).
  • Number of cycles. With integer costs each accepted move lowers EE by at least 1, so k≤E(f0)−min⁡E+1k \le E(f_0) - \min E + 1. There is no better general bound. On image energies programs usually stop after a few cycles; this is an observation, not a bound.
  • Space. O(n+m)O(n + m) for the graph and the labeling.

Properties

  • Approximation. E(f^)≤2c E(f∗)E(\hat f) \le 2c\, E(f^*) for a metric VV and D≥0D \ge 0. For Potts, c=1c = 1. For truncated linear on the integer labels 0,…,L−10, \ldots, L - 1 with 1≤K≤L−11 \le K \le L - 1, c=Kc = K.
  • Strong moves. A local minimum for expansion moves is also a local minimum for single-site changes, the moves of ICM, because changing one site pp to α\alpha is an α\alpha-expansion.
  • Hard problem. Minimizing the Potts energy with L≥3L \ge 3 labels is NP-hard, by a reduction from the multiway cut problem (Section 7 and the Appendix of the paper). So an exact polynomial algorithm is not expected, and a guarantee like 2c2c is the realistic goal.
  • Two labels. For L=2L = 2, start from the labeling with all sites at 0. The move space of label 1 then contains every labeling, so one move gives the exact minimum.
  • Deterministic. For a fixed order of labels and fixed tie-breaking in the cut, the output is fixed. Different orders can stop at different local minima.

Variants and improvements

  • Graph with auxiliary nodes. The original construction puts an extra node on each pair with fp≠fqf_p \ne f_q. It gives the same move.
  • Swap moves. Alpha-beta swap needs only a semimetric but has no constant factor bound.
  • Fusion moves. Lempitsky, Rother, Roth and Blake (2010) combine the current labeling with any proposal labeling, not only a constant one; the move energy is then often nonregular and is solved by QPBO.
  • Primal-dual view. Komodakis and Tziritas (2007) explained expansion as a primal-dual method for the linear programming relaxation, and the FastPD code of Komodakis, Tziritas and Paragios reuses the dual solution between moves.
  • Reuse of flows. Consecutive cuts differ a little, so dynamic max-flow codes reuse the residual graph of the last cycle.
  • Ordered labels. For a convex VV on ordered labels, Ishikawa (2003) gives an exact solution by one cut on a graph with nLn L nodes.

When to use it

Use alpha-expansion for energies with a metric pairwise term, such as Potts or truncated linear: stereo with a smoothness prior (graph cut stereo), segmentation into several regions, image stitching and the segmentation of 3D meshes. In the comparison of Szeliski et al. (2008), expansion was among the best methods on most of the energies and much better than ICM. Use swap or loopy belief propagation when VV is not a metric, and TRW-S when a lower bound is needed.

Pitfalls

  • Nonmetric terms. With truncated quadratic or another semimetric, some move energies are not regular, and a cut does not give the best move. Truncating the nonregular terms makes the method run but voids the bound.
  • Negative data costs. The bound needs Dp≥0D_p \ge 0. Add a constant to each site to make the costs nonnegative; this changes the bound but not the moves.
  • Ties. Accept a move only if it lowers the energy strictly, or the loop can cycle between labelings of equal energy.
  • Floating point. Large and small costs together make the cut inexact. Scale costs to integers when possible.
  • The bound is loose. In practice the result is usually much closer to the optimum than 2c2c, but 2c2c is all that is proved. Do not quote the measured gap as a guarantee.

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.

alpha_expansion.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/alpha-expansion/. The authors are listed in prov/V82D4Y.jsonl.
"""Alpha-expansion for multi-label energies with a metric pairwise term.

The energy of a labeling f (a list with one label in 0 .. L - 1 per site) is

    E(f) = sum_p D[p][f[p]] + sum_{(p, q, w) in pairs} w * V[f[p]][f[q]],

with D[p][l] the data cost, pairs the neighbor pairs with weights w >= 0,
and V an L x L matrix. Each expansion move is solved exactly by one
minimum cut on the graph of the Kolmogorov-Zabih construction.
"""

from __future__ import annotations

from collections import deque
from typing import List, Optional, Sequence, Tuple

Pairs = Sequence[Tuple[int, int, float]]


def energy(D: Sequence[Sequence[float]], pairs: Pairs,
           V: Sequence[Sequence[float]], f: Sequence[int]) -> float:
    return (sum(D[p][f[p]] for p in range(len(D)))
            + sum(w * V[f[p]][f[q]] for (p, q, w) in pairs))


def _min_cut_source_side(nn: int, edges, s: int, t: int) -> List[bool]:
    """Edmonds-Karp max flow; return the nodes that s reaches at the end."""
    adj: List[List[int]] = [[] for _ in range(nn)]
    to: List[int] = []
    cap: List[float] = []
    for (u, v, c) in edges:
        adj[u].append(len(to))
        to.append(v)
        cap.append(c)
        adj[v].append(len(to))
        to.append(u)
        cap.append(0)
    while True:
        prev = [-1] * nn
        seen = [False] * nn
        seen[s] = True
        queue = deque([s])
        while queue and not seen[t]:
            u = queue.popleft()
            for e in adj[u]:
                if cap[e] > 0 and not seen[to[e]]:
                    seen[to[e]] = True
                    prev[to[e]] = e
                    queue.append(to[e])
        if not seen[t]:
            return seen
        path = []
        v = t
        while v != s:
            path.append(prev[v])
            v = to[prev[v] ^ 1]
        delta = min(cap[e] for e in path)
        for e in path:
            cap[e] -= delta
            cap[e ^ 1] += delta


def minimize_regular_binary(n: int, unary: Sequence[Tuple[float, float]],
                            terms: Sequence[Tuple[int, int, float, float, float, float]]
                            ) -> List[int]:
    """Minimize sum_p unary[p][x_p] + sum theta(x_p, x_q) over x in {0,1}^n.

    Each term is (p, q, A, B, C, D) with A = theta(0,0), B = theta(0,1),
    C = theta(1,0), D = theta(1,1), and must be regular: A + D <= B + C.
    x_p = 0 is the source side. Raises ValueError on a nonregular term.
    """
    s, t = n, n + 1
    lin = [u1 - u0 for (u0, u1) in unary]  # coefficient of x_p
    edges = []
    for (p, q, A, B, C, Dd) in terms:
        k = B + C - A - Dd
        if k < 0:
            raise ValueError("nonregular pairwise term: the move is not a cut")
        # theta = A + (C - A) x_p + (Dd - C) x_q + k (1 - x_p) x_q
        lin[p] += C - A
        lin[q] += Dd - C
        if k > 0:
            edges.append((p, q, k))
    for p in range(n):
        if lin[p] > 0:
            edges.append((s, p, lin[p]))  # paid when x_p = 1
        elif lin[p] < 0:
            edges.append((p, t, -lin[p]))  # paid when x_p = 0
    side = _min_cut_source_side(n + 2, edges, s, t)
    return [0 if side[p] else 1 for p in range(n)]


def expansion_move(D, pairs: Pairs, V, f: Sequence[int], alpha: int) -> List[int]:
    """The labeling of least energy among those that move any subset of
    sites to alpha and keep the others (one minimum cut)."""
    n = len(D)
    unary = [(D[p][f[p]], D[p][alpha]) for p in range(n)]  # @line L4
    terms = [(p, q, w * V[f[p]][f[q]], w * V[f[p]][alpha],  # @line L4
              w * V[alpha][f[q]], w * V[alpha][alpha]) for (p, q, w) in pairs]  # @line L4
    x = minimize_regular_binary(n, unary, terms)  # @line L5
    return [alpha if x[p] else f[p] for p in range(n)]  # @line L6


def alpha_expansion(D, pairs: Pairs, V, f: Optional[Sequence[int]] = None,
                    order: Optional[Sequence[int]] = None) -> Tuple[List[int], int]:
    """Run expansion moves over all labels until none lowers the energy.

    Returns (labeling, number of cycles). The start is f, or the labeling
    that takes the best data cost at each site.
    """
    L = len(V)
    if f is None:
        f = [min(range(L), key=lambda l: D[p][l]) for p in range(len(D))]
    f = list(f)
    order = list(range(L)) if order is None else list(order)
    e = energy(D, pairs, V, f)
    cycles = 0
    while True:  # @line L1
        cycles += 1
        success = False  # @line L2
        for alpha in order:  # @line L3
            g = expansion_move(D, pairs, V, f, alpha)  # @line L4
            eg = energy(D, pairs, V, g)  # @line L7
            if eg < e:  # @line L7
                f, e, success = g, eg, True  # @line L7
        if not success:  # @line L8
            return f, cycles  # @line L9


def is_metric(V: Sequence[Sequence[float]]) -> bool:
    L = len(V)
    for a in range(L):
        for b in range(L):
            if (V[a][b] == 0) != (a == b) or V[a][b] != V[b][a] or V[a][b] < 0:
                return False
            for c in range(L):
                if V[a][b] > V[a][c] + V[c][b]:
                    return False
    return True


def bound_factor(V: Sequence[Sequence[float]]) -> float:
    """c = max V / min V over pairs of distinct labels."""
    vals = [V[a][b] for a in range(len(V)) for b in range(len(V)) if a != b]
    return max(vals) / min(vals)


def potts(L: int, lam: float = 1) -> List[List[float]]:
    return [[0 if a == b else lam for b in range(L)] for a in range(L)]


def truncated_linear(L: int, k: float) -> List[List[float]]:
    return [[min(abs(a - b), k) for b in range(L)] for a in range(L)]


def grid_pairs(w: int, h: int, weight: float = 1) -> List[Tuple[int, int, float]]:
    """4-neighbor pairs of a w x h grid, site (u, v) has index v * w + u."""
    out = []
    for v in range(h):
        for u in range(w):
            if u + 1 < w:
                out.append((v * w + u, v * w + u + 1, weight))
            if v + 1 < h:
                out.append((v * w + u, (v + 1) * w + u, weight))
    return out
test_alpha_expansion.py 122 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/alpha-expansion/. The authors are listed in prov/V82D4Y.jsonl.

import itertools
import random

import pytest

from alpha_expansion import (
    alpha_expansion,
    bound_factor,
    energy,
    expansion_move,
    grid_pairs,
    is_metric,
    minimize_regular_binary,
    potts,
    truncated_linear,
)


def brute_optimum(D, pairs, V):
    n, L = len(D), len(V)
    return min(energy(D, pairs, V, f) for f in itertools.product(range(L), repeat=n))


def brute_move(D, pairs, V, f, alpha):
    n = len(D)
    best = None
    for x in itertools.product((0, 1), repeat=n):
        g = [alpha if x[p] else f[p] for p in range(n)]
        e = energy(D, pairs, V, g)
        if best is None or e < best:
            best = e
    return best


def random_instance(rng, n_max=8):
    w = rng.randint(1, 4)
    h = rng.randint(1, max(1, n_max // w))
    L = rng.randint(2, 4)
    while L ** (w * h) > 4096:
        h -= 1
    n = w * h
    D = [[rng.randint(0, 9) for _ in range(L)] for _ in range(n)]
    pairs = [(p, q, rng.randint(1, 3)) for (p, q, _) in grid_pairs(w, h)]
    V = potts(L, rng.randint(1, 4)) if rng.random() < 0.5 else truncated_linear(L, rng.randint(1, 3))
    return D, pairs, V


def test_binary_cut_against_brute_force():
    rng = random.Random(1)
    for _ in range(200):
        n = rng.randint(2, 7)
        unary = [(rng.randint(-5, 5), rng.randint(-5, 5)) for _ in range(n)]
        terms = []
        for _ in range(rng.randint(0, 2 * n)):
            p, q = rng.sample(range(n), 2)
            A, B, C = rng.randint(-3, 3), rng.randint(-3, 3), rng.randint(-3, 3)
            Dd = B + C - A - rng.randint(0, 4)
            terms.append((p, q, A, B, C, Dd))

        def e(x):
            return (sum(unary[p][x[p]] for p in range(n))
                    + sum((A, B, C, Dd)[2 * x[p] + x[q]] for (p, q, A, B, C, Dd) in terms))
        x = minimize_regular_binary(n, unary, terms)
        assert e(x) == min(e(y) for y in itertools.product((0, 1), repeat=n))


def test_nonregular_term_is_rejected():
    with pytest.raises(ValueError):
        minimize_regular_binary(2, [(0, 0), (0, 0)], [(0, 1, 1, 0, 0, 1)])


def test_move_is_optimal_in_its_space():
    rng = random.Random(2)
    for _ in range(150):
        D, pairs, V = random_instance(rng)
        L = len(V)
        f = [rng.randrange(L) for _ in D]
        alpha = rng.randrange(L)
        g = expansion_move(D, pairs, V, f, alpha)
        assert all(g[p] in (f[p], alpha) for p in range(len(D)))
        assert energy(D, pairs, V, g) == brute_move(D, pairs, V, f, alpha)


def test_bound_and_local_minimum():
    rng = random.Random(3)
    for _ in range(120):
        D, pairs, V = random_instance(rng)
        assert is_metric(V)
        L = len(V)
        f0 = [rng.randrange(L) for _ in D]
        f, _ = alpha_expansion(D, pairs, V, f0)
        ef = energy(D, pairs, V, f)
        assert ef <= energy(D, pairs, V, f0)
        opt = brute_optimum(D, pairs, V)
        assert opt <= ef <= 2 * bound_factor(V) * opt
        for alpha in range(L):
            assert brute_move(D, pairs, V, f, alpha) == ef


def test_worked_example():
    # Four sites in a row, Potts with lambda = 4, labels 0, 1, 2.
    D = [[0, 5, 1], [2, 6, 0], [6, 0, 5], [0, 2, 5]]
    pairs = [(0, 1, 1), (1, 2, 1), (2, 3, 1)]
    V = potts(3, 4)
    f0 = [0, 2, 1, 0]
    assert energy(D, pairs, V, f0) == 12
    assert expansion_move(D, pairs, V, f0, 0) == [0, 0, 0, 0]
    f, cycles = alpha_expansion(D, pairs, V, f0)
    assert f == [0, 0, 0, 0] and energy(D, pairs, V, f) == 8 and cycles == 2
    assert brute_optimum(D, pairs, V) == 7
    assert energy(D, pairs, V, [2, 2, 1, 1]) == 7


def test_truncated_quadratic_is_not_metric():
    V = [[min((a - b) ** 2, 4) for b in range(3)] for a in range(3)]
    assert not is_metric(V)
    D = [[0, 9, 9], [9, 9, 0]]
    with pytest.raises(ValueError):
        expansion_move(D, [(0, 1, 1)], V, [0, 2], 1)

History

Boykov, Veksler and Zabih introduced expansion and swap moves at ICCV 1999 and in the journal paper of 2001, with a graph for each move and the proof of the factor 2c2c. They also showed that the Potts energy is NP-hard to minimize. Kolmogorov and Zabih (2004) gave the general rule for which binary energies a cut can minimize, which explains the metric condition. Szeliski et al. (2008) compared the move algorithms with ICM, loopy belief propagation and TRW-S on a common benchmark of vision energies, and expansion became a default method for multi-label problems in vision and graphics.

References

  1. Yuri Boykov, Olga Veksler and Ramin Zabih, Fast approximate energy minimization via graph cuts, IEEE Transactions on Pattern Analysis and Machine Intelligence 23(11), 2001, 1222-1239, Section 3 (the move spaces and the expansion algorithm), Section 5 with Theorem 5.4 and Corollary 5.5 (the graph of an expansion move), Section 6.1 with Theorem 6.1 (the bound 2c), Section 7 and the Appendix (NP-hardness of the Potts energy), Section 8 (experiments)
  2. Vladimir Kolmogorov and Ramin Zabih, What energy functions can be minimized via graph cuts?, IEEE Transactions on Pattern Analysis and Machine Intelligence 26(2), 2004, 147-159, Theorem 4.1 and Section 4.1 (the graph for a regular binary energy, used here for each move)
  3. Richard Szeliski, Ramin Zabih, Daniel Scharstein, Olga Veksler, Vladimir Kolmogorov, Aseem Agarwala, Marshall Tappen and Carsten Rother, A comparative study of energy minimization methods for Markov random fields with smoothness-based priors, IEEE Transactions on Pattern Analysis and Machine Intelligence 30(6), 2008, 1068-1080, the comparison of expansion, swap, ICM, loopy belief propagation and TRW-S on stereo, segmentation, photomontage and denoising energies
  4. Andrew Blake, Pushmeet Kohli and Carsten Rother (editors), Markov Random Fields for Vision and Image Processing, MIT Press, 2011, Part I, Algorithms for inference of MAP estimates for MRFs (the chapters on graph cuts and move making algorithms)
  5. Richard Szeliski, Computer Vision, Algorithms and Applications, second edition, Springer, 2022, Chapter 4, Model fitting and optimization (Markov random fields, graph cuts and alpha-expansion)

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 proofH1 sketch
  • a full proof of time.average
  • 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