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.
- Solves
- Kidney exchange problem
- 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
- Model
- Real RAM
- Properties
- deterministiciterative
- Evidence
- Proof sketchCode in 1 languages
- 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 for each directed cycle of at most 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 , 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 .
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 pairs, with an arc when the donor of pair can give to the patient of pair , a bound , and integer arc weights (all 1 to count transplants). Let be the set of directed cycles with at most pairs, and the total weight of the arcs of . The cycle formulation is
The LP relaxation replaces by . Its dual has a price for each pair and asks for every cycle .
The algorithm
KIDNEY-EXCHANGE-BRANCH-AND-PRICE(G, L, w)- 1
best ← 0; best_set ← ∅ - 2
push the root node (fixed ← ∅, forbidden ← ∅, columns ← ∅) - 3
while the stack is not empty do - 4
pop a node; V' ← the pairs not on a fixed cycle - 5
repeat: solve the LP over the columns, on the pairs of V'; get x and the duals y - 6
add every cycle c of G[V'] with at most L pairs, not forbidden, with w_c − Σ_{v∈c} y_v > 0 - 7
until no cycle is added - 8
if w(fixed) + ⌊LP value⌋ ≤ best then discard the node - 9
else if x is integral then best ← w(fixed) + LP value; best_set ← fixed ∪ {c : x_c = 1} - 10
else c ← a cycle with fractional x_c of largest value - 11
push (fixed, forbidden ∪ {c}) and then (fixed ∪ {c}, forbidden) - 12
return best and best_set
Lines L5 to L7 are column generation. The LP over a subset of the cycles (the restricted master) gives duals . A cycle with positive reduced cost violates the dual, so adding it can raise the LP value. When no cycle has positive reduced cost, 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 , which is exact. Line L8 uses that the weights are integers, so an LP bound of 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 . The short cycles are the swaps , and , each worth 2.
- Root. The LP starts with no columns, so , and all three swaps have reduced cost 2. They enter. The LP optimum is with value 3, and the duals are : each swap now has reduced cost , so pricing adds nothing. The bound is 3, and is fractional.
- Branch on the swap . 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 .
- The child that forbids has the swaps and . Both use pair 1, so its LP value is 2, and : 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 the cycle is also a column, the LP gives it , and the root is already integral with value 3.
Correctness
Bounds. At each node, the LP over all allowed cycles of is a relaxation of the node's integer program, and column generation reaches its optimum value, by the duality argument above. So 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 or does not. The cycle 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 , and the search ends.
Leaves. If 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 be the set of directed cycles of with at most pairs, with integer weights . A packing is a set of pairwise vertex-disjoint cycles of , and its weight is the sum of . A node of the search is given by a set of fixed cycles (pairwise disjoint) and a set of forbidden cycles. Its feasible set is the set of packings with and . Let be the pairs not on a cycle of , and the cycles of inside that are not in . A packing is feasible for the node exactly when with a packing of cycles of .
For the node, let be the linear program subject to for and . Its dual is subject to for and .
Claim 1 (column generation ends at the optimum of ). The loop of lines L5 to L7 stops, and its last restricted LP has the optimal value of . Proof. Each round that does not stop adds at least one cycle of the finite set that is not yet a column, so there are at most rounds. Every restricted LP is feasible () and bounded (each ), so it has an optimal solution and optimal duals , with equal values. When the loop stops, every has : for the new candidates this is the stopping test, and for the columns it is dual feasibility of the restricted LP. So is feasible for the dual of . Extending by zeros gives a feasible solution of with the same value as . By weak duality both are optimal.
Claim 2 (the node bound). Every feasible packing of the node has weight at most . Proof. The indicator vector of satisfies the constraints of , so . The weight is an integer, so .
Claim 3 (integral leaves). If the final of a node is integral, then is a feasible packing of the node with the largest weight among them, equal to . Proof. An integral with selects disjoint cycles of , which are also disjoint from the cycles of because they lie inside . Its weight is , which by Claim 2 is the largest possible.
Claim 4 (branching splits the feasible set). At line L11, has . The feasible set of the node is the disjoint union of the feasible sets of the child and the child . Proof. is a column, so it lies inside and is not in ; in particular is a set of disjoint cycles. A feasible packing either contains , and is feasible for the second child, or does not, and is feasible for the first.
Termination. By Claim 4, each child has one more cycle in than its parent, and . So every path in the search tree has at most branchings, and the tree has at most nodes. Each node ends by Claim 1. So the algorithm stops.
Correctness. Let be a maximum weight packing, with weight . The variable is always the weight of a packing that was found, by Claim 3, so , and is that packing. We show that at the end.
The root's feasible set is the set of all packings, so it contains . Follow the nodes whose feasible set contains : by Claim 4, when such a node branches, exactly one child contains , and that child is pushed and later popped, since the loop runs until the stack is empty. The chain ends at a node that contains and does not branch. At there are two cases.
- Line L8 discards . Then , and by Claim 2, at that moment.
- Line L9 records . By Claim 3, becomes the largest weight of a feasible packing of , which is at least .
In both cases from that moment on, and never decreases, since line L9 only runs when the new value is larger than the old one (line L8 failed). So at the end and is a maximum weight packing.
Cost. By termination there are at most nodes. At each node the cycles of are enumerated in time, where is the largest out-degree, and there are at most rounds of column generation. Each restricted LP has at most rows and columns plus slacks, and the simplex method with Bland's rule never repeats a basis, so it makes at most pivots of polynomial cost. The total is arithmetic operations. With , the bound is exponential, as expected for an NP-hard problem.
Complexity
The problem is NP-hard for , so no polynomial bound is expected. The search tree has depth at most , so at most nodes. Each node solves LPs with at most columns and rows; the simplex method with Bland's rule visits at most one basis per subset of the columns, and pricing adds at least one column per round, so a node does at most rounds. All of this is in the worst case, with . Enumerating the cycles costs for maximum out-degree , which is the method of elementary cycle enumeration cut at depth . 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 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 .
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.
- . 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 or similar, and for other barter markets where items trade in short cycles. For use maximum weight matching. For an unbounded 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 , the cycles do not fit in memory. Generate them by pricing.
- Floating point duals. A reduced cost of 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 prunes many more nodes than the raw LP value.
Implementations
The Python version takes the number of pairs, the list of arcs, 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.
# 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 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
- 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
- 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.
| Ladder | Level | What the next level needs |
|---|---|---|
| Human proof | H1 sketch |
|
| Lean | L0 no Lean part |
|
| Code (python) | I0 not checked yet |
|
| Visual | V0 none |
|
| Writing | W2 basic |
|
Tag HATF0Q Edit this page History Report an error Markdown