Algorithm Search⌘K

Algorithmadvanced

QPBO

Also called quadratic pseudo-boolean optimization, roof duality.

Minimize a non-submodular binary pairwise energy by a min cut on a doubled graph, labeling part of the variables with values that some optimum shares, and giving a lower bound.

Time
O(F + n + m) worst · average · best
Space
O(n + m) extra
Where
F = the time of one max flow on 2n + 2 nodes and 2n + 2m edges; m = the number of pair terms; n = the number of variables
Properties
deterministicnot exactofflineiterative
Origin
Peter L. Hammer, Pierre Hansen, Bruno Simeone, 1984

QPBO (quadratic pseudo-Boolean optimization) is a method for energies of binary variables with unary and pairwise terms when some pairwise terms are not submodular, so that a single minimum cut cannot minimize them (the Kolmogorov-Zabih theorem). It doubles the variables: next to each xpx_p it adds xˉp\bar x_p, meant to be 1−xp1 - x_p, and writes a new energy of the 2n2n variables that is submodular and equals the old energy when xˉ=1−x\bar x = 1 - x. One minimum cut minimizes the new energy. Where the solution has xˉp=1−xp\bar x_p = 1 - x_p, the variable pp gets a label; elsewhere it is left unlabeled. The labeled values are persistent: some minimizer of the original energy has exactly those values. The minimum of the new energy is also a lower bound on the original minimum. The method is the roof duality of Hammer, Hansen and Simeone (1984); its bound equals that of the linear programming relaxation. In vision it solves the nonregular moves of fusion and stereo methods, and in general it fixes part of the variables of a hard problem for free.

In plain words

You have many yes or no questions, and a cost for each answer and for each pair of answers. If every pair prefers to agree, a cut in a graph gives the best answers at once. When some pairs prefer to disagree, that trick fails. QPBO keeps two copies of each question, one for the answer and one for its opposite, and writes the costs so that every pair in the new problem prefers to agree. The cut then solves the new problem. Where the two copies give consistent answers, you can trust them: some best solution uses those answers. Where they do not, the method says "I do not know", and you must decide those questions another way.

The problem

Input. An energy of nn binary variables

E(x)=∑pθp(xp)+∑(p,q)θpq(xp,xq),E(x) = \sum_p \theta_p(x_p) + \sum_{(p,q)} \theta_{pq}(x_p, x_q),

with real values and mm pair terms. A pair term is submodular if θpq(0,0)+θpq(1,1)≤θpq(0,1)+θpq(1,0)\theta_{pq}(0,0) + \theta_{pq}(1,1) \le \theta_{pq}(0,1) + \theta_{pq}(1,0); the others are not.

Output. A partial labeling: a set of variables with values in {0,1}\{0, 1\} such that some global minimizer of EE has these values, and a lower bound on min⁡E\min E.

Minimizing EE is NP-hard in general (it contains maximum cut), so a method that labels all variables in polynomial time on every input is not expected.

The algorithm

  1. QPBO(θ)
  2. 1for each variable p, make two nodes: p for x_p, and p̄ for x̄_p (meant to be 1 - x_p)
  3. 2for each p add ½ θ_p(x_p) + ½ θ_p(1 - x̄_p)
  4. 3for each pair term θ_pq do
  5. 4if θ_pq is submodular then add ½ θ_pq(x_p, x_q) + ½ θ_pq(1 - x̄_p, 1 - x̄_q)
  6. 5else add ½ θ_pq(x_p, 1 - x̄_q) + ½ θ_pq(1 - x̄_p, x_q)
  7. 6(x, x̄) ← a minimizer of the new energy Ẽ by one minimum cut on 2n + 2 nodes
  8. 7for each p: if x̄_p = 1 - x_p then label p with x_p, else leave p unlabeled
  9. 8return the partial labeling and the lower bound Ẽ(x, x̄)

Line L4 keeps a submodular term on the original variables and copies it, complemented, on the doubled ones. Line L5 links a non-submodular term between xpx_p and xˉq\bar x_q and between xˉp\bar x_p and xqx_q: replacing one argument by the complement of its twin turns "prefer to disagree" into "prefer to agree". Every term of E~\tilde E is then regular, and the graph of the theorem page represents it. The code multiplies everything by 2 to keep integer costs in integers.

Example

Take three variables with the frustrated triangle, each pair paying 1 when the two values agree, and a fourth variable tied to x0x_0:

  • θ01=θ12=θ02=[xp=xq]\theta_{01} = \theta_{12} = \theta_{02} = [x_p = x_q], which are not submodular (1+1>0+01 + 1 > 0 + 0);
  • θ03=[x0≠x3]\theta_{03} = [x_0 \ne x_3], which is submodular;
  • θ3(0)=0\theta_3(0) = 0, θ3(1)=3\theta_3(1) = 3, and no other unary costs.

Every labeling of the triangle has at least one agreeing pair, so min⁡E=1\min E = 1, reached by (0,0,1,0)(0,0,1,0), (0,1,0,0)(0,1,0,0) and (0,1,1,0)(0,1,1,0). QPBO finds the minimizer x=(0,0,0,0)x = (0,0,0,0), xˉ=(0,0,0,1)\bar x = (0,0,0,1) of 2E~2\tilde E, with 2E~=12\tilde E = 1.

variable xpx_p xˉp\bar x_p result
0, 1, 2 0 0 unlabeled
3 0 1 labeled 0

The lower bound is E~=0.5≤1\tilde E = 0.5 \le 1, and x3=0x_3 = 0 holds in every minimizer, as persistency promises. The triangle stays unlabeled, because on an odd cycle of disagreeing pairs the doubled energy can reach a smaller value with x=xˉx = \bar x than any real labeling. In a second example with a chain x0,x1,x2x_0, x_1, x_2, a strong unary cost θ0=(0,4)\theta_0 = (0, 4), a non-submodular term on (x0,x1)(x_0, x_1) that pays 2 when they agree, and a submodular term on (x1,x2)(x_1, x_2) that pays 3 when they differ, QPBO labels all three variables, (0,1,1)(0, 1, 1), which is the minimizer with E=0E = 0.

Correctness

The full proof is in proofs/correctness.md. First, each term of E~\tilde E is regular: a submodular term keeps its sign under complementing both arguments, and a non-submodular term becomes regular when exactly one argument is complemented. Second, E~(x,1−x)=E(x)\tilde E(x, 1 - x) = E(x), so min⁡E~≤min⁡E\min \tilde E \le \min E. Third, persistency. The map σ(x,xˉ)=(1−xˉ,1−x)\sigma(x, \bar x) = (1 - \bar x, 1 - x) leaves E~\tilde E unchanged, and E~\tilde E is submodular on {0,1}2n\{0,1\}^{2n}. From the minimizer aa found by the cut, a∨σ(a)a \vee \sigma(a) is also a minimizer that agrees with aa on the labeled variables and is (1,1)(1,1) on the others. For any minimizer zz of EE, two steps of submodularity with b=(z,1−z)b = (z, 1 - z) give a point (z′,1−z′)(z', 1 - z') of no larger energy, where z′z' takes the QPBO values on the labeled variables and the values of zz elsewhere. So z′z' is also a minimizer.

Proof: Correctness of QPBOfull

Let E(x)=∑pθp(xp)+∑(p,q)θpq(xp,xq)E(x) = \sum_p \theta_p(x_p) + \sum_{(p,q)} \theta_{pq}(x_p, x_q) for x∈{0,1}nx \in \{0,1\}^n, with arbitrary real pair terms. Call a pair term submodular if θpq(0,0)+θpq(1,1)≤θpq(0,1)+θpq(1,0)\theta_{pq}(0,0) + \theta_{pq}(1,1) \le \theta_{pq}(0,1) + \theta_{pq}(1,0). Lines L1 to L5 build the energy E~\tilde E of 2n2n binary variables y=(x,xˉ)y = (x, \bar x):

E~(x,xˉ)=12∑p[θp(xp)+θp(1−xˉp)]+12∑subm.[θpq(xp,xq)+θpq(1−xˉp,1−xˉq)]+12∑non-subm.[θpq(xp,1−xˉq)+θpq(1−xˉp,xq)].\tilde E(x, \bar x) = \tfrac12 \sum_p \big[\theta_p(x_p) + \theta_p(1 - \bar x_p)\big] + \tfrac12 \sum_{\text{subm.}} \big[\theta_{pq}(x_p, x_q) + \theta_{pq}(1 - \bar x_p, 1 - \bar x_q)\big] + \tfrac12 \sum_{\text{non-subm.}} \big[\theta_{pq}(x_p, 1 - \bar x_q) + \theta_{pq}(1 - \bar x_p, x_q)\big].

We prove: (1) E~\tilde E is regular, so line L6 finds a minimizer (x∗,xˉ∗)(x^*, \bar x^*) by one cut; (2) E~(x,1−x)=E(x)\tilde E(x, 1 - x) = E(x), so min⁡E~≤min⁡E\min \tilde E \le \min E; (3) persistency: if zz minimizes EE, then the labeling z′z' with zp′=xp∗z'_p = x^*_p for every labeled pp (those with xˉp∗=1−xp∗\bar x^*_p = 1 - x^*_p) and zp′=zpz'_p = z_p otherwise also minimizes EE.

1. E~\tilde E is regular

Each term of E~\tilde E depends on at most two variables. For a term g(u,v)g(u, v) write Δg=g(0,0)+g(1,1)−g(0,1)−g(1,0)\Delta g = g(0,0) + g(1,1) - g(0,1) - g(1,0); the term is regular when Δg≤0\Delta g \le 0. Let A,B,C,DA, B, C, D be the values of θpq\theta_{pq} at (0,0),(0,1),(1,0),(1,1)(0,0), (0,1), (1,0), (1,1), so Δθpq=A+D−B−C\Delta \theta_{pq} = A + D - B - C.

  • θpq(xp,xq)\theta_{pq}(x_p, x_q) has Δ=A+D−B−C\Delta = A + D - B - C.
  • θpq(1−xˉp,1−xˉq)\theta_{pq}(1 - \bar x_p, 1 - \bar x_q), as a function of (xˉp,xˉq)(\bar x_p, \bar x_q), takes the values D,C,B,AD, C, B, A, so Δ=D+A−C−B\Delta = D + A - C - B.
  • θpq(xp,1−xˉq)\theta_{pq}(x_p, 1 - \bar x_q), as a function of (xp,xˉq)(x_p, \bar x_q), takes the values B,A,D,CB, A, D, C, so Δ=B+C−A−D\Delta = B + C - A - D.
  • θpq(1−xˉp,xq)\theta_{pq}(1 - \bar x_p, x_q), as a function of (xˉp,xq)(\bar x_p, x_q), takes the values C,D,A,BC, D, A, B, so Δ=C+B−A−D\Delta = C + B - A - D.

Line L4 uses the first two when A+D≤B+CA + D \le B + C, and line L5 the last two when A+D>B+CA + D > B + C. In both cases Δ≤0\Delta \le 0. So E~\tilde E is in the class F2\mathcal{F}^2 and regular, and by the Kolmogorov-Zabih theorem the graph of the code, with 2n+22n + 2 nodes, represents 2E~2\tilde E; a minimum cut gives a minimizer. The code doubles every value to stay in integers.

2. The diagonal and the lower bound

Put xˉ=1−x\bar x = 1 - x. Then 1−xˉp=xp1 - \bar x_p = x_p for every pp, and every bracket becomes twice the matching term of EE. So E~(x,1−x)=E(x)\tilde E(x, 1 - x) = E(x), and min⁡E~≤min⁡xE~(x,1−x)=min⁡E\min \tilde E \le \min_x \tilde E(x, 1 - x) = \min E. Line L8 returns E~(x∗,xˉ∗)=min⁡E~\tilde E(x^*, \bar x^*) = \min \tilde E, which is therefore a lower bound on min⁡E\min E.

3. Persistency

Symmetry. Let σ(x,xˉ)=(1−xˉ,1−x)\sigma(x, \bar x) = (1 - \bar x, 1 - x). Each bracket of E~\tilde E is mapped onto itself by σ\sigma: the unary bracket becomes θp(1−xˉp)+θp(xp)\theta_p(1 - \bar x_p) + \theta_p(x_p); the submodular bracket becomes θpq(1−xˉp,1−xˉq)+θpq(xp,xq)\theta_{pq}(1 - \bar x_p, 1 - \bar x_q) + \theta_{pq}(x_p, x_q); the other bracket becomes θpq(1−xˉp,xq)+θpq(xp,1−xˉq)\theta_{pq}(1 - \bar x_p, x_q) + \theta_{pq}(x_p, 1 - \bar x_q). So E~(σ(y))=E~(y)\tilde E(\sigma(y)) = \tilde E(y).

Submodularity. For y,y′∈{0,1}2ny, y' \in \{0,1\}^{2n} let y∧y′y \wedge y' and y∨y′y \vee y' be the componentwise minimum and maximum. A function of two binary variables with Δ≤0\Delta \le 0 satisfies g(a∧a′)+g(a∨a′)≤g(a)+g(a′)g(a \wedge a') + g(a \vee a') \le g(a) + g(a'): if a≤a′a \le a' or a′≤aa' \le a both sides are equal, and otherwise {a,a′}={(0,1),(1,0)}\{a, a'\} = \{(0,1), (1,0)\} and the inequality is Δg≤0\Delta g \le 0. Summing over the terms, E~(y∧y′)+E~(y∨y′)≤E~(y)+E~(y′)\tilde E(y \wedge y') + \tilde E(y \vee y') \le \tilde E(y) + \tilde E(y').

Let a=(x∗,xˉ∗)a = (x^*, \bar x^*) be the minimizer of line L6, and let m=E~(a)m = \tilde E(a).

Step 1. Let a′=a∨σ(a)a' = a \vee \sigma(a). By submodularity and symmetry, E~(a′)+E~(a∧σ(a))≤2m\tilde E(a') + \tilde E(a \wedge \sigma(a)) \le 2m, and both terms are at least mm, so E~(a′)=m\tilde E(a') = m. In coordinates, a′a' has xp′=max⁡(xp∗,1−xˉp∗)x'_p = \max(x^*_p, 1 - \bar x^*_p) and xˉp′=max⁡(xˉp∗,1−xp∗)\bar x'_p = \max(\bar x^*_p, 1 - x^*_p). For a labeled pp this is (xp∗,1−xp∗)(x^*_p, 1 - x^*_p), unchanged. For an unlabeled pp, (xp∗,xˉp∗)(x^*_p, \bar x^*_p) is (0,0)(0,0) or (1,1)(1,1), and both give (1,1)(1, 1).

Step 2. Let zz minimize EE and b=(z,1−z)b = (z, 1 - z), so E~(b)=E(z)\tilde E(b) = E(z). Let d=b∧a′d = b \wedge a'. Since E~(b∨a′)≥m=E~(a′)\tilde E(b \vee a') \ge m = \tilde E(a'), submodularity gives E~(d)≤E~(b)\tilde E(d) \le \tilde E(b).

Step 3. Let c=d∨σ(a′)c = d \vee \sigma(a'). Since E~(d∧σ(a′))≥m=E~(σ(a′))\tilde E(d \wedge \sigma(a')) \ge m = \tilde E(\sigma(a')), submodularity gives E~(c)≤E~(d)≤E~(b)\tilde E(c) \le \tilde E(d) \le \tilde E(b).

Coordinates of cc. σ(a′)\sigma(a') is (xp∗,1−xp∗)(x^*_p, 1 - x^*_p) at a labeled pp and (0,0)(0, 0) at an unlabeled pp. At a labeled pp, dd is (min⁡(zp,xp∗),min⁡(1−zp,1−xp∗))(\min(z_p, x^*_p), \min(1 - z_p, 1 - x^*_p)), and cc is (max⁡(min⁡(zp,xp∗),xp∗),max⁡(min⁡(1−zp,1−xp∗),1−xp∗))=(xp∗,1−xp∗)(\max(\min(z_p, x^*_p), x^*_p), \max(\min(1 - z_p, 1 - x^*_p), 1 - x^*_p)) = (x^*_p, 1 - x^*_p). At an unlabeled pp, dd is (zp,1−zp)(z_p, 1 - z_p) because a′a' is (1,1)(1,1) there, and cc is the same. So c=(z′,1−z′)c = (z', 1 - z').

Hence E(z′)=E~(c)≤E~(b)=E(z)=min⁡EE(z') = \tilde E(c) \le \tilde E(b) = E(z) = \min E, and z′z' is a minimizer of EE. □\square

Consequences

  • If every pair term is submodular, then E~(x,xˉ)=12[E(x)+E(1−xˉ)]\tilde E(x, \bar x) = \tfrac12 [E(x) + E(1 - \bar x)]. A minimizer has xx and 1−xˉ1 - \bar x both minimizing EE. If the minimizer of EE is unique, then xˉ∗=1−x∗\bar x^* = 1 - x^* and every variable is labeled with the optimum.
  • If every variable is labeled, x∗x^* itself is a minimizer of EE, by persistency with any zz.
  • The proof used only that aa is some minimizer of E~\tilde E. Different minimum cuts can label different sets; each set is persistent.

Complexity

The model is the real RAM; the tests use integer costs.

  • Time. Building E~\tilde E and its graph takes O(n+m)O(n + m) time. The graph has 2n+22n + 2 nodes and at most 2n+2m2n + 2m edges, so the time is that of one max-flow computation FF on a graph twice as large as for a submodular energy. The code uses Edmonds-Karp; vision codes use the Boykov-Kolmogorov algorithm.
  • Space. O(n+m)O(n + m).

Properties

  • Persistency. Labeled values agree with some global minimizer. Fixing them and solving the rest by any method loses nothing.
  • Lower bound. min⁡E~≤min⁡E\min \tilde E \le \min E, and the gap tells how far a heuristic solution can be from the optimum.
  • Exact for submodular energies. If all terms are submodular and the minimizer is unique, all variables are labeled. If there are several minimizers, a cut may leave some variables unlabeled.
  • LP equivalence. The roof dual bound equals the optimum of the standard linear programming relaxation of the quadratic 0-1 problem (Hammer, Hansen and Simeone 1984). So QPBO solves that relaxation by one cut.
  • Partial in general. On frustrated cycles, as in the example, many variables can stay unlabeled. How many depends on the strength of the non-submodular terms against the unary terms.
  • Invariance. Flipping the meaning of a variable (xp→1−xpx_p \to 1 - x_p) changes which terms are submodular, but not the labeled set. So any energy that becomes submodular after flipping some variables (a "bipartite" frustration pattern) is solved as well as a submodular one.

Variants and improvements

  • QPBO-P and QPBO-I. Rother, Kolmogorov, Lempitsky and Szummer (2007) proposed probing, which tries each value of an unlabeled variable and draws conclusions from both runs, and improvement, which takes any complete labeling and returns one of no larger energy by fixing the unlabeled variables to it.
  • Fusion moves. In multi-label problems, a move that combines the current labeling with a proposal is a binary energy that is often not submodular; QPBO solves it, and unlabeled sites keep their current label, which never raises the energy.
  • Higher order. Energies with terms of three or more variables are first reduced to pairwise form with extra variables, then given to QPBO.
  • Implication network. Boros and Hammer compute the same bound by a max flow on an implication network of 2n2n literals, the same idea in the language of 2-SAT and implication graphs.

When to use it

Use QPBO for binary pairwise energies with some non-submodular terms: image deconvolution, texture synthesis, learned pairwise terms, and the fusion moves of stereo and optical flow. It is fast, it never gives a wrong label, and its bound measures the quality of the rest. When most variables stay unlabeled, add probing, or use loopy belief propagation or simulated annealing on the remaining part. For energies that are already submodular, a plain cut is simpler and half the size.

Pitfalls

  • Unlabeled is not wrong. An unlabeled variable has no information from QPBO. Assigning it 0 by default is a heuristic; use QPBO-I to make sure that the energy does not rise.
  • Persistency is weak. The labeled values agree with some minimizer, not with every minimizer. Two runs with different cuts can label different sets, each correct.
  • Halves. The definition has factors 12\tfrac12. Doubling all costs avoids fractions; the lower bound is then half the cut value.
  • The frustrated case. Strong non-submodular terms on odd cycles, as in max-cut instances, leave almost everything unlabeled. QPBO does not make an NP-hard problem easy.

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.

qpbo.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/qpbo/. The authors are listed in prov/W42VES.jsonl.
"""QPBO: roof duality for binary pairwise energies by one minimum cut.

The energy of x in {0,1}^n is

    E(x) = sum_p unary[p][x_p] + sum_{(p, q, A, B, C, D)} theta_pq(x_p, x_q),

where a pair term is given by its four values A = theta(0,0), B = theta(0,1),
C = theta(1,0), D = theta(1,1). Pair terms need not be submodular.

QPBO doubles the variables: y = (x, xbar), where xbar_p stands for 1 - x_p.
The doubled energy Etilde is submodular, Etilde(x, 1 - x) = E(x), and its
minimum is a lower bound on min E. The variables p with xbar_p = 1 - x_p in
the minimizer found by the cut get a label, and some minimizer of E agrees
with all of them (persistency). All values are doubled inside, so integer
energies give exact integer arithmetic.
"""

from __future__ import annotations

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

Term = Tuple[int, int, float, float, float, float]


def energy(unary, terms: Sequence[Term], x: Sequence[int]) -> float:
    return (sum(unary[p][x[p]] for p in range(len(unary)))
            + sum((A, B, C, D)[2 * x[p] + x[q]] for (p, q, A, B, C, D) in terms))


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(nv: int, lin: List[float], terms) -> List[int]:
    """Minimize sum lin[i] y_i + sum theta(y_i, y_j) for regular terms
    (i, j, A, B, C, D), up to a constant; y_i = 0 is the source side."""
    lin = list(lin)
    s, t = nv, nv + 1
    edges = []
    for (i, j, A, B, C, D) in terms:
        k = B + C - A - D
        assert k >= 0
        lin[i] += C - A
        lin[j] += D - C
        if k > 0:
            edges.append((i, j, k))
    for i in range(nv):
        if lin[i] > 0:
            edges.append((s, i, lin[i]))
        elif lin[i] < 0:
            edges.append((i, t, -lin[i]))
    side = _min_cut_source_side(nv + 2, edges, s, t)
    return [0 if side[i] else 1 for i in range(nv)]


def doubled_energy(unary, terms: Sequence[Term], x, xbar) -> float:
    """2 * Etilde(x, xbar), the doubled energy of QPBO times two."""
    total = 0
    for p, (u0, u1) in enumerate(unary):
        total += (u0, u1)[x[p]] + (u0, u1)[1 - xbar[p]]
    for (p, q, A, B, C, D) in terms:
        th = (A, B, C, D)
        if A + D <= B + C:
            total += th[2 * x[p] + x[q]] + th[2 * (1 - xbar[p]) + (1 - xbar[q])]
        else:
            total += th[2 * x[p] + (1 - xbar[q])] + th[2 * (1 - xbar[p]) + x[q]]
    return total


def qpbo(unary: Sequence[Tuple[float, float]], terms: Sequence[Term]
         ) -> Tuple[List[Optional[int]], float]:
    """Return (partial labeling, lower bound on min E).

    The labeling has 0 or 1 for labeled variables and None for the others.
    """
    n = len(unary)
    # Variable i < n is x_i, variable n + i is xbar_i.  # @line L1
    lin = [0.0] * (2 * n)
    pair_terms = []
    for p, (u0, u1) in enumerate(unary):  # @line L2
        lin[p] += u1 - u0  # u(x_p), doubled and halved  # @line L2
        lin[n + p] += u0 - u1  # u(1 - xbar_p)  # @line L2
    for (p, q, A, B, C, D) in terms:  # @line L3
        if A + D <= B + C:  # @line L4
            pair_terms.append((p, q, A, B, C, D))  # theta(x_p, x_q)  # @line L4
            # theta(1 - xbar_p, 1 - xbar_q) as a function of (xbar_p, xbar_q)
            pair_terms.append((n + p, n + q, D, C, B, A))  # @line L4
        else:  # @line L5
            # theta(x_p, 1 - xbar_q) as a function of (x_p, xbar_q)
            pair_terms.append((p, n + q, B, A, D, C))  # @line L5
            # theta(1 - xbar_p, x_q) as a function of (xbar_p, x_q)
            pair_terms.append((n + p, q, C, D, A, B))  # @line L5
    y = _minimize_regular(2 * n, lin, pair_terms)  # @line L6
    x, xbar = y[:n], y[n:]
    labels: List[Optional[int]] = [x[p] if xbar[p] == 1 - x[p] else None  # @line L7
                                   for p in range(n)]  # @line L7
    bound = doubled_energy(unary, terms, x, xbar) / 2  # @line L8
    return labels, bound  # @line L8
test_qpbo.py 113 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/qpbo/. The authors are listed in prov/W42VES.jsonl.

import itertools
import random

from qpbo import doubled_energy, energy, qpbo


def all_minimizers(unary, terms):
    n = len(unary)
    vals = {x: energy(unary, terms, x) for x in itertools.product((0, 1), repeat=n)}
    best = min(vals.values())
    return best, [x for x, e in vals.items() if e == best]


def random_energy(rng, n, submodular_only=False):
    unary = [(rng.randint(-6, 6), rng.randint(-6, 6)) for _ in range(n)]
    terms = []
    for (p, q) in itertools.combinations(range(n), 2):
        if rng.random() < 0.5:
            A, B, C, D = (rng.randint(-5, 5) for _ in range(4))
            if submodular_only and A + D > B + C:
                A, B = B, A  # swap a pair of values to fix the sign
                if A + D > B + C:
                    D = B + C - A
            terms.append((p, q, A, B, C, D))
    return unary, terms


def test_doubled_energy_on_the_diagonal():
    rng = random.Random(1)
    for _ in range(50):
        n = rng.randint(1, 6)
        unary, terms = random_energy(rng, n)
        for x in itertools.product((0, 1), repeat=n):
            xbar = [1 - v for v in x]
            assert doubled_energy(unary, terms, x, xbar) == 2 * energy(unary, terms, x)


def test_persistency_and_bound():
    rng = random.Random(2)
    labeled_total = 0
    for _ in range(300):
        n = rng.randint(1, 9)
        unary, terms = random_energy(rng, n)
        labels, bound = qpbo(unary, terms)
        best, mins = all_minimizers(unary, terms)
        assert bound <= best
        labeled_total += sum(v is not None for v in labels)
        # Every minimizer stays a minimizer when the labeled values are imposed.
        for z in mins:
            z2 = tuple(labels[p] if labels[p] is not None else z[p] for p in range(n))
            assert energy(unary, terms, z2) == best
    assert labeled_total > 0


def test_doubled_minimum_is_found():
    rng = random.Random(3)
    for _ in range(60):
        n = rng.randint(1, 5)
        unary, terms = random_energy(rng, n)
        labels, bound = qpbo(unary, terms)
        brute = min(doubled_energy(unary, terms, x, xb)
                    for x in itertools.product((0, 1), repeat=n)
                    for xb in itertools.product((0, 1), repeat=n))
        assert 2 * bound == brute


def test_submodular_with_unique_minimum_is_fully_labeled():
    rng = random.Random(4)
    checked = 0
    for _ in range(300):
        n = rng.randint(1, 8)
        unary, terms = random_energy(rng, n, submodular_only=True)
        best, mins = all_minimizers(unary, terms)
        labels, bound = qpbo(unary, terms)
        assert bound == best
        if len(mins) == 1:
            checked += 1
            assert tuple(labels) == mins[0]
    assert checked > 50


def test_frustrated_triangle():
    # Each pair pays 1 when the two values agree; at least one pair agrees.
    terms = [(p, q, 1, 0, 0, 1) for (p, q) in ((0, 1), (1, 2), (0, 2))]
    unary = [(0, 0)] * 3
    labels, bound = qpbo(unary, terms)
    assert labels == [None, None, None]
    assert bound == 0
    assert all_minimizers(unary, terms)[0] == 1


def test_worked_example():
    # A path of three variables: one nonsubmodular pair and a strong unary.
    unary = [(0, 4), (0, 0), (0, 0)]
    terms = [(0, 1, 2, 0, 0, 2), (1, 2, 0, 3, 3, 0)]
    labels, bound = qpbo(unary, terms)
    assert labels == [0, 1, 1]
    assert bound == 0 and energy(unary, terms, (0, 1, 1)) == 0


def test_partial_example():
    # The frustrated triangle with a fourth variable tied to variable 0.
    terms = [(p, q, 1, 0, 0, 1) for (p, q) in ((0, 1), (1, 2), (0, 2))]
    terms.append((0, 3, 0, 1, 1, 0))
    unary = [(0, 0)] * 3 + [(0, 3)]
    labels, bound = qpbo(unary, terms)
    assert labels == [None, None, None, 0]
    assert bound == 0.5
    best, mins = all_minimizers(unary, terms)
    assert best == 1 and all(z[3] == 0 for z in mins)

History

Hammer, Hansen and Simeone (1984) defined the roof dual of a quadratic 0-1 function, showed that it equals the bound of the linear programming relaxation, and proved persistency. Boros and Hammer, with coauthors, developed the network flow computation of the bound and summarized the theory in their 2002 survey. Kolmogorov and Rother (2007) brought the method to vision under the name QPBO, with the doubled graph and an efficient code built on the Boykov-Kolmogorov max-flow algorithm, and Rother et al. (2007) added probing and improvement. QPBO then became the standard solver of fusion moves and of other nonregular binary moves.

References

  1. Peter L. Hammer, Pierre Hansen and Bruno Simeone, Roof duality, complementation and persistency in quadratic 0-1 optimization, Mathematical Programming 28(2), 1984, 121-155, the roof dual bound, its equality with the bound of the linear programming relaxation, and the persistency theorem
  2. Endre Boros and Peter L. Hammer, Pseudo-Boolean optimization, Discrete Applied Mathematics 123(1-3), 2002, 155-225, the parts on roof duality, the implication network and the computation of the roof dual by network flows
  3. Vladimir Kolmogorov and Carsten Rother, Minimizing nonsubmodular functions with graph cuts, a review, IEEE Transactions on Pattern Analysis and Machine Intelligence 29(7), 2007, 1274-1279, the construction of the doubled graph, the reading of the partial labeling, and the properties of the method
  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 chapter on optimizing non-submodular binary MRFs)

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