Algorithm Search⌘K

Algorithmadvanced

Cycle formulation for kidney exchange

Also called Abraham-Blum-Sandholm kidney exchange solver.

Solves kidney exchange with cycle length at most L by an integer program with one variable per short cycle, using branch and price.

Time
2^(O(n + C)) worst
Space
O(C^2 + n (n + C)) extra
Where
C = the number of cycles with at most L pairs (at most n^L); L = the bound on the cycle length; n = the number of pairs
Properties
deterministiciterative
Origin
David J. Abraham, Avrim Blum, Tuomas Sandholm, 2007

The cycle formulation is the standard integer program for the kidney exchange problem. It has one binary variable xcx_c for each directed cycle cc of at most LL pairs in the compatibility graph, and one constraint for each pair: the chosen cycles must not share it. This is a set packing problem over the short cycles. Its LP relaxation is strong, but the number of cycles grows like nLn^L, so Abraham, Blum and Sandholm (2007) solved it by branch and price: each LP uses only a few cycles and adds a new one when the LP duals show that it can improve the solution. The worst case is exponential, since the problem is NP-hard for L≥3L \ge 3.

In plain words

List every short loop of pairs that could swap kidneys. The task is to choose loops that share no pair and give the most transplants. A computer can solve the relaxed problem where a loop may be "half chosen" quickly, and the answer is a good upper bound. If the relaxed answer chooses whole loops only, it is the best answer. If not, pick a half-chosen loop and try two cases: take it, or ban it. To keep the relaxed problems small, start with a few loops and add a loop only when the prices of the pairs, which come from the relaxed problem, say that the loop is worth more than the pairs it uses.

The problem

The input is a directed graph on nn pairs, with an arc (i,j)(i, j) when the donor of pair ii can give to the patient of pair jj, a bound L≥2L \ge 2, and integer arc weights wijw_{ij} (all 1 to count transplants). Let C\mathcal{C} be the set of directed cycles with at most LL pairs, and wcw_c the total weight of the arcs of cc. The cycle formulation is

max⁡∑c∈Cwcxcsubject to∑c∋vxc≤1 for every pair v,xc∈{0,1}.\max \sum_{c \in \mathcal{C}} w_c x_c \quad \text{subject to} \quad \sum_{c \ni v} x_c \le 1 \text{ for every pair } v, \quad x_c \in \{0, 1\}.

The LP relaxation replaces xc∈{0,1}x_c \in \{0, 1\} by xc≥0x_c \ge 0. Its dual has a price yv≥0y_v \ge 0 for each pair and asks ∑v∈cyv≥wc\sum_{v \in c} y_v \ge w_c for every cycle cc.

The algorithm

  1. KIDNEY-EXCHANGE-BRANCH-AND-PRICE(G, L, w)
  2. 1best ← 0; best_set ← ∅
  3. 2push the root node (fixed ← ∅, forbidden ← ∅, columns ← ∅)
  4. 3while the stack is not empty do
  5. 4pop a node; V' ← the pairs not on a fixed cycle
  6. 5repeat: solve the LP over the columns, on the pairs of V'; get x and the duals y
  7. 6add every cycle c of G[V'] with at most L pairs, not forbidden, with w_c − Σ_{v∈c} y_v > 0
  8. 7until no cycle is added
  9. 8if w(fixed) + ⌊LP value⌋ ≤ best then discard the node
  10. 9else if x is integral then best ← w(fixed) + LP value; best_set ← fixed ∪ {c : x_c = 1}
  11. 10else c ← a cycle with fractional x_c of largest value
  12. 11push (fixed, forbidden ∪ {c}) and then (fixed ∪ {c}, forbidden)
  13. 12return best and best_set

Lines L5 to L7 are column generation. The LP over a subset of the cycles (the restricted master) gives duals yy. A cycle with positive reduced cost wc−∑v∈cyvw_c - \sum_{v \in c} y_v violates the dual, so adding it can raise the LP value. When no cycle has positive reduced cost, yy is feasible for the full dual, so by LP duality the restricted LP value is the value of the full LP relaxation of the node. Here the pricing step enumerates the short cycles of G[V′]G[V'], which is exact. Line L8 uses that the weights are integers, so an LP bound of 3.53.5 means at most 3. Line L11 branches on one cycle: the child that takes it is popped first.

Example

Three pairs with arcs in both directions between each two, and L=2L = 2. The short cycles are the swaps {1,2}\{1, 2\}, {1,3}\{1, 3\} and {2,3}\{2, 3\}, each worth 2.

  1. Root. The LP starts with no columns, so y=0y = 0, and all three swaps have reduced cost 2. They enter. The LP optimum is x=(1/2,1/2,1/2)x = (1/2, 1/2, 1/2) with value 3, and the duals are y=(1,1,1)y = (1, 1, 1): each swap now has reduced cost 2−2=02 - 2 = 0, so pricing adds nothing. The bound is 3, and xx is fractional.
  2. Branch on the swap {2,3}\{2, 3\}. The child that takes it has only pair 1 left, so its LP value is 0, and the solution is integral with value 2. Now best=2\text{best} = 2.
  3. The child that forbids {2,3}\{2, 3\} has the swaps {1,2}\{1, 2\} and {1,3}\{1, 3\}. Both use pair 1, so its LP value is 2, and 0+2≤20 + 2 \le 2: it is discarded.

The answer is one swap, 2 transplants, after 3 nodes. The gap between 3 and 2 is the integrality gap of this instance. With L=3L = 3 the cycle 1→2→3→11 \to 2 \to 3 \to 1 is also a column, the LP gives it x=1x = 1, and the root is already integral with value 3.

Correctness

Bounds. At each node, the LP over all allowed cycles of G[V′]G[V'] is a relaxation of the node's integer program, and column generation reaches its optimum value, by the duality argument above. So w(fixed)+⌊LP value⌋w(\text{fixed}) + \lfloor \text{LP value} \rfloor bounds every solution in the subtree, and line L8 never discards a better solution.

Branching. The two children split the solutions of a node: every packing either uses cc or does not. The cycle cc is fractional, so it is not forbidden and not fixed already, and each child has one more fixed or forbidden cycle. So the depth is at most CC, and the search ends.

Leaves. If xx is integral, it is a packing of cycles with the LP value, and no packing of the node is better. Together with the bounds, the best leaf found is optimal. The proof file gives the details.

Proof: Branch and price on the cycle formulation returns a maximum weight packing of short cyclesfull

Let C\mathcal{C} be the set of directed cycles of GG with at most LL pairs, with integer weights wc≥1w_c \ge 1. A packing is a set of pairwise vertex-disjoint cycles of C\mathcal{C}, and its weight is the sum of wcw_c. A node of the search is given by a set FF of fixed cycles (pairwise disjoint) and a set BB of forbidden cycles. Its feasible set is the set of packings PP with F⊆PF \subseteq P and P∩B=∅P \cap B = \emptyset. Let V′V' be the pairs not on a cycle of FF, and C′\mathcal{C}' the cycles of C\mathcal{C} inside V′V' that are not in BB. A packing PP is feasible for the node exactly when P=F∪QP = F \cup Q with QQ a packing of cycles of C′\mathcal{C}'.

For the node, let LP′\text{LP}' be the linear program max⁡∑c∈C′wcxc\max \sum_{c \in \mathcal{C}'} w_c x_c subject to ∑c∋vxc≤1\sum_{c \ni v} x_c \le 1 for v∈V′v \in V' and x≥0x \ge 0. Its dual is min⁡∑v∈V′yv\min \sum_{v \in V'} y_v subject to ∑v∈cyv≥wc\sum_{v \in c} y_v \ge w_c for c∈C′c \in \mathcal{C}' and y≥0y \ge 0.

Claim 1 (column generation ends at the optimum of LP′\text{LP}'). The loop of lines L5 to L7 stops, and its last restricted LP has the optimal value of LP′\text{LP}'. Proof. Each round that does not stop adds at least one cycle of the finite set C′\mathcal{C}' that is not yet a column, so there are at most ∣C′∣+1|\mathcal{C}'| + 1 rounds. Every restricted LP is feasible (x=0x = 0) and bounded (each xc≤1x_c \le 1), so it has an optimal solution xx and optimal duals y≥0y \ge 0, with equal values. When the loop stops, every c∈C′c \in \mathcal{C}' has wc−∑v∈cyv≤0w_c - \sum_{v \in c} y_v \le 0: for the new candidates this is the stopping test, and for the columns it is dual feasibility of the restricted LP. So yy is feasible for the dual of LP′\text{LP}'. Extending xx by zeros gives a feasible solution of LP′\text{LP}' with the same value as ∑vyv\sum_v y_v. By weak duality both are optimal. □\square

Claim 2 (the node bound). Every feasible packing P=F∪QP = F \cup Q of the node has weight at most w(F)+⌊LP′⌋w(F) + \lfloor \text{LP}' \rfloor. Proof. The indicator vector of QQ satisfies the constraints of LP′\text{LP}', so w(Q)≤LP′w(Q) \le \text{LP}'. The weight w(Q)w(Q) is an integer, so w(Q)≤⌊LP′⌋w(Q) \le \lfloor \text{LP}' \rfloor. □\square

Claim 3 (integral leaves). If the final xx of a node is integral, then P=F∪{c:xc=1}P = F \cup \{c : x_c = 1\} is a feasible packing of the node with the largest weight among them, equal to w(F)+LP′w(F) + \text{LP}'. Proof. An integral xx with ∑c∋vxc≤1\sum_{c \ni v} x_c \le 1 selects disjoint cycles of C′\mathcal{C}', which are also disjoint from the cycles of FF because they lie inside V′V'. Its weight is w(F)+LP′w(F) + \text{LP}', which by Claim 2 is the largest possible. □\square

Claim 4 (branching splits the feasible set). At line L11, c∈C′c \in \mathcal{C}' has 0<xc<10 < x_c < 1. The feasible set of the node is the disjoint union of the feasible sets of the child (F,B∪{c})(F, B \cup \{c\}) and the child (F∪{c},B)(F \cup \{c\}, B). Proof. cc is a column, so it lies inside V′V' and is not in BB; in particular F∪{c}F \cup \{c\} is a set of disjoint cycles. A feasible packing either contains cc, and is feasible for the second child, or does not, and is feasible for the first. □\square

Termination. By Claim 4, each child has one more cycle in F∪BF \cup B than its parent, and F∪B⊆CF \cup B \subseteq \mathcal{C}. So every path in the search tree has at most ∣C∣|\mathcal{C}| branchings, and the tree has at most 2∣C∣+12^{|\mathcal{C}| + 1} nodes. Each node ends by Claim 1. So the algorithm stops.

Correctness. Let P∗P^* be a maximum weight packing, with weight OPT\text{OPT}. The variable best\text{best} is always the weight of a packing that was found, by Claim 3, so best≤OPT\text{best} \le \text{OPT}, and best_set\text{best\_set} is that packing. We show that best=OPT\text{best} = \text{OPT} at the end.

The root's feasible set is the set of all packings, so it contains P∗P^*. Follow the nodes whose feasible set contains P∗P^*: by Claim 4, when such a node branches, exactly one child contains P∗P^*, and that child is pushed and later popped, since the loop runs until the stack is empty. The chain ends at a node NN that contains P∗P^* and does not branch. At NN there are two cases.

  • Line L8 discards NN. Then w(F)+⌊LP′⌋≤bestw(F) + \lfloor \text{LP}' \rfloor \le \text{best}, and by Claim 2, OPT=w(P∗)≤best\text{OPT} = w(P^*) \le \text{best} at that moment.
  • Line L9 records NN. By Claim 3, best\text{best} becomes the largest weight of a feasible packing of NN, which is at least w(P∗)=OPTw(P^*) = \text{OPT}.

In both cases best≥OPT\text{best} \ge \text{OPT} from that moment on, and best\text{best} never decreases, since line L9 only runs when the new value is larger than the old one (line L8 failed). So at the end best=OPT\text{best} = \text{OPT} and best_set\text{best\_set} is a maximum weight packing. ■\blacksquare

Cost. By termination there are at most 2∣C∣+12^{|\mathcal{C}| + 1} nodes. At each node the cycles of G[V′]G[V'] are enumerated in O(ndL−1)O(n d^{L-1}) time, where dd is the largest out-degree, and there are at most ∣C∣+1|\mathcal{C}| + 1 rounds of column generation. Each restricted LP has at most nn rows and ∣C∣|\mathcal{C}| columns plus nn slacks, and the simplex method with Bland's rule never repeats a basis, so it makes at most 2n+∣C∣2^{n + |\mathcal{C}|} pivots of polynomial cost. The total is 2O(n+∣C∣)2^{O(n + |\mathcal{C}|)} arithmetic operations. With ∣C∣≤nL|\mathcal{C}| \le n^L, the bound is exponential, as expected for an NP-hard problem.

Complexity

The problem is NP-hard for L≥3L \ge 3, so no polynomial bound is expected. The search tree has depth at most CC, so at most 2C+12^{C+1} nodes. Each node solves LPs with at most CC columns and nn rows; the simplex method with Bland's rule visits at most one basis per subset of the n+Cn + C columns, and pricing adds at least one column per round, so a node does at most CC rounds. All of this is 2O(n+C)2^{O(n + C)} in the worst case, with C≤nLC \le n^L. Enumerating the cycles costs O(ndL−1)O(n d^{L-1}) for maximum out-degree dd, which is the method of elementary cycle enumeration cut at depth LL. In practice the LP bound of the cycle formulation is very close to the optimum, and the tree stays small.

The model is the real RAM for the arithmetic of the LP; the implementation uses exact rational numbers.

Properties

  • Exact. It returns an optimal packing, not an approximation.
  • Strong relaxation. The LP relaxation only mixes short cycles, so a fractional solution cannot use long cycles. On real pools its bound is usually very close to the optimum, which keeps the search tree small.
  • Columns, not rows. The formulation has nn constraints and many variables, which is the case where column generation pays off.
  • Weights. Any integer weights work, so medical priorities and the chance of success can be folded into ww.

Variants and improvements

  • Chains. Altruistic donors start chains. The cycle formulation adds one variable per chain of bounded length, or treats a chain as a cycle through a dummy arc back to the altruistic donor.
  • Pricing by search. Real pools have too many cycles to enumerate. Pricing then searches for a positive reduced cost cycle with the duals as vertex costs, which is a bounded length cycle problem, solved by dynamic programming or by heuristics followed by an exact check.
  • Other formulations. Edge formulations and position-indexed formulations have polynomially many variables and are easier to set up, but their LP bounds are usually weaker.
  • L=2L = 2. For swaps only, the LP is the matching LP, and a maximum matching algorithm is faster.

When to use it

Use it for the clearing step of a kidney exchange program with L=3L = 3 or similar, and for other barter markets where items trade in short cycles. For L=2L = 2 use maximum weight matching. For an unbounded LL use the assignment problem. For a mechanism with incentive properties and no length bound, see top trading cycles and chains.

Pitfalls

  • Enumerating all cycles up front. With thousands of pairs and L=3L = 3, the cycles do not fit in memory. Generate them by pricing.
  • Floating point duals. A reduced cost of 10−1210^{-12} can make column generation loop or stop early. Use a tolerance with care, or exact arithmetic for small cases.
  • Branching on arcs or pairs naively. Branching on a single arc variable gives unbalanced trees. Branch on cycles, as here, or on pairs, and make sure that the pricing step respects the branch.
  • Forgetting the floor. With integer weights, the bound ⌊LP⌋\lfloor \text{LP} \rfloor prunes many more nodes than the raw LP value.

Implementations

The Python version takes the number of pairs, the list of arcs, LL and optional integer weights, and returns the optimal value, the chosen cycles and the root LP bound with the node count. It uses the shared exact LP helper in Fraction, so the duals are exact. The tests compare the value with a brute force search over all packings of short cycles on random graphs with up to 8 pairs, check the cycle enumeration against a search over vertex sequences, and check the examples on this page.

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.

agtlp.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Shared helper of the algorithmic game theory pages of https://algorithm.tamnd.com/. The authors are listed in prov/.
"""Exact linear programming in Fraction, by the two-phase simplex method with Bland's rule.

lp_max(c, A_ub, b_ub, A_eq=None, b_eq=None) maximizes c x subject to A_ub x <= b_ub,
A_eq x = b_eq and x >= 0. lp_min does the same for minimization. Free variables must be
split by the caller (x = x+ - x-). Every input number is converted to Fraction, so the
result is exact: there is no tolerance anywhere.

Both functions return (status, x, value, dual). status is "optimal", "infeasible" or
"unbounded". When status is not "optimal", x, value and dual are None. dual has one entry
per constraint, the A_ub rows first and then the A_eq rows. It is the vector of shadow
prices: the value is sum_i b_i dual_i (strong duality). For lp_max, dual_i >= 0 on the
A_ub rows and A^T dual >= c. For lp_min, dual_i <= 0 on the A_ub rows and A^T dual <= c.
The entries for the A_eq rows have no sign condition.

Bland's rule (the smallest improving column enters, and among the rows with the smallest
ratio the one with the smallest basic variable leaves) makes the method finite on every
input, degenerate inputs included. There is no game algorithm in this module.
"""

from fractions import Fraction


def _frac(v):
    return v if isinstance(v, Fraction) else Fraction(v)


def _pivot(T, obj, basis, r, j):
    p = T[r][j]
    row = [v / p for v in T[r]]
    T[r] = row
    for k in range(len(T)):
        f = T[k][j]
        if k != r and f != 0:
            T[k] = [a - f * b for a, b in zip(T[k], row)]
    f = obj[j]
    if f != 0:
        obj[:] = [a - f * b for a, b in zip(obj, row)]
    basis[r] = j


def _simplex(T, obj, basis, ncols):
    """Maximize. obj[j] is the reduced cost of column j and obj[-1] is minus the value."""
    while True:
        enter = next((j for j in range(ncols) if obj[j] > 0), None)
        if enter is None:
            return "optimal"
        best = None
        for r, row in enumerate(T):
            a = row[enter]
            if a > 0:
                key = (row[-1] / a, basis[r])
                if best is None or key < best[0]:
                    best = (key, r)
        if best is None:
            return "unbounded"
        _pivot(T, obj, basis, best[1], enter)


def _objective_row(cost, T, basis):
    obj = list(cost) + [Fraction(0)]
    for r, j in enumerate(basis):
        f = obj[j]
        if f != 0:
            obj = [a - f * b for a, b in zip(obj, T[r])]
    return obj


def _any_solution(M, rhs, nvars):
    """Return one solution y of M y = rhs (a consistent system), with the free variables 0."""
    rows = [list(M[k]) + [rhs[k]] for k in range(len(M))]
    pivots = []
    r = 0
    for col in range(nvars):
        p = next((k for k in range(r, len(rows)) if rows[k][col] != 0), None)
        if p is None:
            continue
        rows[r], rows[p] = rows[p], rows[r]
        pv = rows[r][col]
        rows[r] = [v / pv for v in rows[r]]
        for k in range(len(rows)):
            f = rows[k][col]
            if k != r and f != 0:
                rows[k] = [a - f * b for a, b in zip(rows[k], rows[r])]
        pivots.append(col)
        r += 1
        if r == len(rows):
            break
    y = [Fraction(0)] * nvars
    for k, col in enumerate(pivots):
        y[col] = rows[k][-1]
    return y


def _matrix(A, width, name):
    A = [[_frac(v) for v in row] for row in (A or [])]
    if any(len(row) != width for row in A):
        raise ValueError(name + " must have one column per variable")
    return A


def lp_max(c, A_ub, b_ub, A_eq=None, b_eq=None):
    """Maximize c x subject to A_ub x <= b_ub, A_eq x = b_eq and x >= 0, exactly."""
    c = [_frac(v) for v in c]
    n = len(c)
    A_ub = _matrix(A_ub, n, "A_ub")
    A_eq = _matrix(A_eq, n, "A_eq")
    b_ub = [_frac(v) for v in (b_ub or [])]
    b_eq = [_frac(v) for v in (b_eq or [])]
    if len(b_ub) != len(A_ub) or len(b_eq) != len(A_eq):
        raise ValueError("b_ub and b_eq must have one entry per row")
    m1, m2 = len(A_ub), len(A_eq)
    m = m1 + m2
    width = n + m1
    # Rows in the original orientation, with a slack column for each A_ub row.
    orig = [A_ub[i] + [Fraction(int(k == i)) for k in range(m1)] for i in range(m1)]
    orig += [A_eq[i] + [Fraction(0)] * m1 for i in range(m2)]
    rhs = b_ub + b_eq
    # A row gets an artificial variable if it is an equation or if its right side is negative.
    need = [i >= m1 or rhs[i] < 0 for i in range(m)]
    nart = sum(need)
    T, basis = [], []
    a = 0
    for i in range(m):
        sign = -1 if rhs[i] < 0 else 1
        row = [sign * v for v in orig[i]] + [Fraction(0)] * nart + [sign * rhs[i]]
        if need[i]:
            row[width + a] = Fraction(1)
            basis.append(width + a)
            a += 1
        else:
            basis.append(n + i)
        T.append(row)
    if nart:
        # Phase 1: maximize minus the sum of the artificial variables.
        obj = _objective_row([Fraction(0)] * width + [Fraction(-1)] * nart, T, basis)
        _simplex(T, obj, basis, width + nart)
        if obj[-1] != 0:
            return "infeasible", None, None, None
        keep = []
        for r in range(m):
            if basis[r] >= width:
                j = next((j for j in range(width) if T[r][j] != 0), None)
                if j is None:
                    continue  # the row is a combination of the other rows
                _pivot(T, [Fraction(0)] * (width + nart + 1), basis, r, j)
            keep.append(r)
        T = [T[r][:width] + [T[r][-1]] for r in keep]
        basis = [basis[r] for r in keep]
    # Phase 2: the original objective, without the artificial columns.
    cost = c + [Fraction(0)] * m1
    obj = _objective_row(cost, T, basis)
    if _simplex(T, obj, basis, width) == "unbounded":
        return "unbounded", None, None, None
    x = [Fraction(0)] * n
    for r, j in enumerate(basis):
        if j < n:
            x[j] = T[r][-1]
    value = sum((ci * xi for ci, xi in zip(c, x)), Fraction(0))
    # The dual solves y^T A_B = c_B, where A_B holds the basic columns of the original rows.
    M = [[orig[i][j] for i in range(m)] for j in basis]
    dual = _any_solution(M, [cost[j] for j in basis], m)
    return "optimal", x, value, dual


def lp_min(c, A_ub, b_ub, A_eq=None, b_eq=None):
    """Minimize c x subject to A_ub x <= b_ub, A_eq x = b_eq and x >= 0, exactly."""
    status, x, value, dual = lp_max([-_frac(v) for v in c], A_ub, b_ub, A_eq, b_eq)
    if status != "optimal":
        return status, None, None, None
    return status, x, -value, [-v for v in dual]
kidney_exchange_cycle_formulation.py 109 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/kidney-exchange-cycle-formulation/. The authors are listed in prov/HATF0Q.jsonl.

from fractions import Fraction
from typing import Iterable, Optional

from agtlp import lp_max

Cycle = tuple[int, ...]


def short_cycles(n: int, succ: list[list[int]], L: int, alive: Optional[set[int]] = None) -> list[Cycle]:
    """Every directed cycle with at most L vertices, each listed once from its smallest vertex.

    O(n * d^(L-1)) time for maximum out-degree d.
    """
    alive = set(range(n)) if alive is None else alive
    out: list[Cycle] = []

    def extend(path: list[int], on: set[int]) -> None:
        s, v = path[0], path[-1]
        for u in succ[v]:
            if u == s:
                out.append(tuple(path))
            elif u > s and u in alive and u not in on and len(path) < L:
                path.append(u)
                on.add(u)
                extend(path, on)
                on.discard(u)
                path.pop()

    for s in sorted(alive):
        extend([s], {s})
    return out


def _master(cols: list[Cycle], weight: dict[Cycle, int], verts: list[int]):
    """Solve max sum w_c x_c subject to sum of x_c over the columns at v <= 1, x >= 0."""
    if not cols:
        return [], Fraction(0), {v: Fraction(0) for v in verts}
    row = {v: k for k, v in enumerate(verts)}
    A = [[0] * len(cols) for _ in verts]
    for j, c in enumerate(cols):
        for v in c:
            A[row[v]][j] = 1
    status, x, value, dual = lp_max([weight[c] for c in cols], A, [1] * len(verts))
    assert status == "optimal"
    return x, value, {v: dual[row[v]] for v in verts}


def kidney_exchange(
    n: int, arcs: Iterable[tuple[int, int]], L: int, w: Optional[dict[tuple[int, int], int]] = None
) -> tuple[int, list[Cycle], dict]:
    """Maximum weight packing of vertex-disjoint cycles with at most L vertices.

    This is the cycle formulation of Abraham, Blum and Sandholm (2007), solved by branch and
    price: each node solves the LP relaxation by column generation, with exact pricing by
    enumeration of the short cycles and the LP duals, and branches on a fractional cycle
    (take it, or forbid it). Pairs are 0, ..., n - 1, an arc (i, j) means that the donor of
    pair i can give to the patient of pair j, and w gives integer arc weights (default 1, so
    the value is the number of transplants). Returns (value, cycles, stats), with stats the
    root LP bound and the number of nodes. The worst case is exponential (the problem is
    NP-hard for L >= 3); each LP is solved exactly in Fraction.
    """
    arcs = list(arcs)
    w = {a: 1 for a in arcs} if w is None else w
    succ: list[list[int]] = [[] for _ in range(n)]
    for i, j in arcs:
        if i != j:
            succ[i].append(j)

    def weight_of(c: Cycle) -> int:
        return sum(w[(c[k], c[(k + 1) % len(c)])] for k in range(len(c)))

    weight: dict[Cycle, int] = {}
    best, best_set = 0, []  # @line L1
    stack = [((), frozenset(), [])]  # @line L2  (fixed cycles, forbidden cycles, columns)
    stats = {"nodes": 0, "root_lp": None}
    while stack:  # @line L3
        fixed, forbidden, cols = stack.pop()  # @line L4
        stats["nodes"] += 1
        used = {v for c in fixed for v in c}
        verts = [v for v in range(n) if v not in used]
        cands = [c for c in short_cycles(n, succ, L, set(verts)) if c not in forbidden]
        for c in cands:
            if c not in weight:
                weight[c] = weight_of(c)
        cols = [c for c in cols if c not in forbidden and not used.intersection(c)]
        while True:
            x, value, y = _master(cols, weight, verts)  # @line L5
            have = set(cols)
            new = [c for c in cands if c not in have and weight[c] - sum(y[v] for v in c) > 0]  # @line L6
            if not new:  # @line L7
                break
            cols = cols + new
        if stats["root_lp"] is None:
            stats["root_lp"] = value
        base = sum(weight[c] for c in fixed)
        if base + (value.numerator // value.denominator) <= best:  # @line L8
            continue
        frac = [(x[j], c) for j, c in enumerate(cols) if 0 < x[j] < 1]
        if not frac:  # @line L9
            best = base + int(value)
            best_set = list(fixed) + [c for j, c in enumerate(cols) if x[j] == 1]
            continue
        c = max(frac)[1]  # @line L10
        stack.append((fixed, forbidden | {c}, [d for d in cols if d != c]))  # @line L11
        stack.append((fixed + (c,), forbidden, [d for d in cols if not set(d).intersection(c)]))
    return best, sorted(best_set), stats  # @line L12
test_kidney_exchange_cycle_formulation.py 107 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/kidney-exchange-cycle-formulation/. The authors are listed in prov/HATF0Q.jsonl.

import random
import unittest
from fractions import Fraction
from itertools import permutations

from kidney_exchange_cycle_formulation import kidney_exchange, short_cycles


def cycles_by_permutations(n, arcs, L):
    """Reference cycle list: try every sequence of distinct vertices."""
    A = set(arcs)
    out = set()
    for k in range(2, L + 1):
        for seq in permutations(range(n), k):
            if seq[0] == min(seq) and all((seq[t], seq[(t + 1) % k]) in A for t in range(k)):
                out.add(seq)
    return out


def brute_force(n, arcs, L, w=None):
    """Best packing of disjoint short cycles by trying every subset of compatible cycles."""
    w = {a: 1 for a in arcs} if w is None else w
    cyc = sorted(cycles_by_permutations(n, arcs, L))
    wt = [sum(w[(c[k], c[(k + 1) % len(c)])] for k in range(len(c))) for c in cyc]
    best = 0

    def rec(k, used, val):
        nonlocal best
        best = max(best, val)
        for t in range(k, len(cyc)):
            if not used.intersection(cyc[t]):
                rec(t + 1, used | set(cyc[t]), val + wt[t])

    rec(0, set(), 0)
    return best


def check_solution(test, n, arcs, L, w, value, cycles):
    w = {a: 1 for a in arcs} if w is None else w
    A = set(arcs)
    seen = set()
    total = 0
    for c in cycles:
        test.assertTrue(2 <= len(c) <= L)
        test.assertFalse(seen.intersection(c))
        seen.update(c)
        for k in range(len(c)):
            a = (c[k], c[(k + 1) % len(c)])
            test.assertIn(a, A)
            total += w[a]
    test.assertEqual(total, value)


class TestKidneyExchange(unittest.TestCase):
    def test_page_examples(self):
        arcs = [(0, 1), (1, 2), (2, 0), (1, 0), (2, 3), (3, 2), (3, 4), (4, 3)]
        self.assertEqual(kidney_exchange(5, arcs, 2)[:2], (4, [(0, 1), (2, 3)]))
        self.assertEqual(kidney_exchange(5, arcs, 3)[:2], (5, [(0, 1, 2), (3, 4)]))
        # three mutual pairs: the root LP is 3 with all 2-cycles at 1/2, the optimum is 2
        tri = [(0, 1), (1, 0), (1, 2), (2, 1), (2, 0), (0, 2)]
        value, cyc, stats = kidney_exchange(3, tri, 2)
        self.assertEqual((value, stats["root_lp"], stats["nodes"]), (2, Fraction(3), 3))
        self.assertEqual(len(cyc), 1)
        self.assertEqual(kidney_exchange(3, tri, 3)[:2], (3, [(0, 1, 2)]))

    def test_edge_cases(self):
        self.assertEqual(kidney_exchange(0, [], 3)[:2], (0, []))
        self.assertEqual(kidney_exchange(1, [], 3)[:2], (0, []))
        self.assertEqual(kidney_exchange(2, [(0, 1)], 3)[:2], (0, []))
        self.assertEqual(kidney_exchange(2, [(0, 1), (1, 0)], 2)[:2], (2, [(0, 1)]))
        # a 4-cycle is not allowed with L = 3
        ring = [(0, 1), (1, 2), (2, 3), (3, 0)]
        self.assertEqual(kidney_exchange(4, ring, 3)[0], 0)
        self.assertEqual(kidney_exchange(4, ring, 4)[0], 4)

    def test_cycle_enumeration(self):
        rng = random.Random(2)
        for _ in range(40):
            n = rng.randint(1, 6)
            arcs = [(i, j) for i in range(n) for j in range(n) if i != j and rng.random() < 0.4]
            succ = [[] for _ in range(n)]
            for i, j in arcs:
                succ[i].append(j)
            for L in (2, 3, 4):
                got = short_cycles(n, succ, L)
                self.assertEqual(len(got), len(set(got)))
                self.assertEqual(set(got), cycles_by_permutations(n, arcs, L))

    def test_against_brute_force(self):
        rng = random.Random(7)
        for _ in range(120):
            n = rng.randint(1, 8)
            p = rng.choice([0.2, 0.35, 0.5])
            arcs = [(i, j) for i in range(n) for j in range(n) if i != j and rng.random() < p]
            L = rng.choice([2, 3, 4])
            w = {a: rng.randint(1, 5) for a in arcs} if rng.random() < 0.5 else None
            value, cycles, stats = kidney_exchange(n, arcs, L, w)
            self.assertEqual(value, brute_force(n, arcs, L, w))
            check_solution(self, n, arcs, L, w, value, cycles)
            self.assertGreaterEqual(stats["root_lp"], value)  # the LP is an upper bound


if __name__ == "__main__":
    unittest.main()

History

Abraham, Blum and Sandholm (2007) showed that the problem is NP-hard for L≥3L \ge 3 and solved it at the scale of a national program by branch and price on the cycle formulation. Biro, Manlove and Rizzi (2009) settled its approximability for short cycles. Later work added chains and compact formulations.

References

  1. David J. Abraham, Avrim Blum and Tuomas Sandholm, Clearing algorithms for barter exchange markets, enabling nationwide kidney exchanges, Proceedings of the 8th ACM Conference on Electronic Commerce (EC 2007), 295 to 304, the cycle formulation, its solution by branch and price, and the pricing of cycles with the LP duals
  2. Peter Biro, David F. Manlove and Romeo Rizzi, Maximum weight cycle packing in directed graphs, with application to kidney exchange programs, Discrete Mathematics, Algorithms and Applications 1(4), 499 to 517 (2009), the complexity of cycle packing with short cycles

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.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
  • at least three sources
  • a scene preset for the example