Algorithm Search⌘K

Algorithmadvanced

Top trading cycles and chains

Also called TTCC.

Extends top trading cycles to kidney exchange with a deceased-donor waiting list by also trading along chains that end in the list. With a suitable chain rule it is efficient and strategyproof.

Time
O(n^2 + L) worst
Space
O(n) extra
Where
L = the total length of the preference lists; n = the number of patient-donor pairs
Properties
deterministiciterative
Origin
Alvin E. Roth, Tayfun Sonmez, M. Utku Unver, 2004

Top trading cycles and chains (TTCC) is a mechanism for kidney exchange. Each patient has a willing donor whose kidney does not fit, and the pair can trade with other pairs as in a housing market. In addition, a patient can accept the option ww: high priority on the waiting list for a kidney from a deceased donor, in return for its donor giving a kidney to a patient on that list. Roth, Sonmez and Unver (2004) extended top trading cycles to this setting. Cycles of pairs trade as before. When no cycle is left, the mechanism picks a ww-chain: a path of pairs where each patient gets the next pair's kidney and the last patient gets ww, and the kidney at the start of the chain goes to the waiting list. With chain rule e (pick the chain that starts at the pair of highest priority, and keep it), the result is Pareto efficient and strategyproof. A run with rounds takes O(n2+L)O(n^2 + L) time.

In plain words

Each patient points either to the donor kidney it likes best among those still free, or to the waiting list. Kidneys point to their own patients. If there is a loop, its patients swap kidneys and leave, exactly as in top trading cycles. If there is no loop, every path of arrows ends at the waiting list. Pick one such path by a fixed rule. Each patient on it gets the kidney it points to, the last one goes to the top of the waiting list, and the donor at the start of the path gives to the waiting list. Repeat until every patient is served.

The problem

There are nn pairs. Pair ii has patient tit_i and donor kidney kik_i. Patient tit_i has a strict ranking of the kidneys and the option ww. The list contains kik_i, which stands for no exchange: the patient keeps its own donor and stays on the waiting list as before. Items after kik_i are never used. A fixed priority order of the pairs is given. The output gives each patient a kidney or ww, with each kidney going to at most one patient, and also lists the kidneys that go to the deceased-donor waiting list.

The algorithm

A pair is ACTIVE while its patient has no assignment, TAIL if its patient is assigned but its kidney is still free, and DONE when both are settled. A kidney is free while its pair is ACTIVE or TAIL.

  1. TTCC(lists, priority, keep)
  2. 1for each pair i do ptr[i] ← 1; state[i] ← ACTIVE
  3. 2for each pair i do x[i] ← NIL
  4. 3while some pair is ACTIVE do
  5. 4for each ACTIVE pair i do move ptr[i] forward to the first free kidney or w; target[i] ← that item
  6. 5if the arcs i → target[i] between ACTIVE pairs contain cycles then
  7. 6for each cycle, each pair i on it gets x[i] ← target[i] and becomes DONE
  8. 7else
  9. 8a ← the ACTIVE pair that comes first in priority
  10. 9follow targets from a through ACTIVE pairs: a = q1, q2, …, qm, until target[qm] is w or the kidney of a TAIL pair z
  11. 10for each ql, x[ql] ← target[ql]; q2, …, qm become DONE, and so does z if it exists
  12. 11if keep then a becomes TAIL else a becomes DONE and kidney a goes to the waiting list
  13. 12the kidneys of the TAIL pairs go to the waiting list; return x

Line L5 looks for cycles in a functional graph in which some arcs leave the ACTIVE pairs: arcs to ww and arcs to the free kidneys of TAIL pairs. When there is no cycle, every path from an ACTIVE pair leaves the ACTIVE pairs, so line L9 stops. The path q1,…,qmq_1, \dots, q_m with the tail kidney kak_a is the ww-chain that starts at pair aa. With keep\text{keep} true, this is chain rule e of Roth, Sonmez and Unver: the kidney kak_a stays free, so later patients can still get it. With keep\text{keep} false it is rule d: the chain is removed, and kak_a goes to the waiting list at once.

Example

Five pairs with priority 1, 2, 3, 4, 5. Patient 1 ranks k2≻k1k_2 \succ k_1, patient 2 ranks k1≻k2k_1 \succ k_2, patient 3 ranks k1≻w≻k3k_1 \succ w \succ k_3, patient 4 ranks k3≻k4k_3 \succ k_4, and patient 5 ranks k3≻k4≻w≻k5k_3 \succ k_4 \succ w \succ k_5.

With rule e:

round targets of the ACTIVE pairs action
1 1 → k2k_2, 2 → k1k_1, 3 → k1k_1, 4 → k3k_3, 5 → k3k_3 cycle 1, 2: patients 1 and 2 swap
2 3 → ww, 4 → k3k_3, 5 → k3k_3 no cycle; chain from pair 3: patient 3 gets ww, pair 3 becomes TAIL
3 4 → k3k_3, 5 → k3k_3 no cycle; chain from pair 4: patient 4 gets k3k_3, pair 3 is DONE, pair 4 becomes TAIL
4 5 → k4k_4 no cycle; chain from pair 5: patient 5 gets k4k_4, pair 4 is DONE, pair 5 becomes TAIL

At the end k5k_5 goes to the waiting list. Four patients get a living donor kidney, patient 3 gets ww, and the waiting list gets k5k_5.

With rule d, round 2 removes the chain of pair 3, so k3k_3 goes to the waiting list at once. In round 3 patient 4 points to its own kidney, a cycle of length one, so it gets no exchange. Then patient 5 finds k3k_3 and k4k_4 gone and gets ww, and k5k_5 goes to the waiting list. Only two patients get a living donor kidney. The tests check both runs.

Edge cases. A single pair whose patient prefers ww gets ww, and its kidney goes to the waiting list. If no patient ranks ww above its own kidney, no chain ever forms and TTCC is top trading cycles.

Correctness

The output is feasible: line L4 only points to free kidneys, line L6 gives each cycle the kidneys of the cycle, and line L10 gives each patient of the chain the kidney of the next pair or the kidney of a TAIL pair, which then becomes DONE. Each kidney goes to one patient or to the waiting list, and the number of patients with ww equals the number of kidneys given to the list. The result is individually rational, since a patient never points past its own kidney, which stays free while its pair is ACTIVE.

Roth, Sonmez and Unver (2004) proved two properties. If every chain selected before the last round stays in the procedure, so that its tail kidney remains free, the result is Pareto efficient (their Theorem 1); rule e is such a rule. With rules a, d, e and f, truth-telling is a dominant strategy for each patient (their Theorem 2). Rule d is strategyproof but not efficient. Let patient 1 rank only k1k_1, patient 2 rank w≻k2w \succ k_2, and patient 3 rank k2≻k3k_2 \succ k_3. Rule d sends k2k_2 to the waiting list with the chain of pair 2, and patient 3 keeps k3k_3. Rule e keeps k2k_2 free and gives it to patient 3, which is better for patient 3 and the same for the others.

The proof file shows that the algorithm terminates and returns a feasible, individually rational outcome, and that it follows the TTCC procedure with the chosen rule.

Proof: TTCC terminates and returns a feasible, individually rational outcome of the TTCC procedurefull

Pair ii has patient tit_i and kidney kik_i, for i=1,…,ni = 1, \dots, n. Each list ranks kidneys and ww strictly and contains kik_i. A kidney is free while its pair is ACTIVE or TAIL. An outcome gives each patient a kidney or ww, with each kidney given to at most one patient; together with it the algorithm returns the set KwK_w of kidneys that go to the waiting list.

We prove that the algorithm stops, that it carries out the TTCC procedure of Roth, Sonmez and Unver with chain rule e (if keep is true) or d (if keep is false), and that its outcome is feasible and individually rational. The efficiency of rule e and the strategyproofness of rules d and e are the theorems of Roth, Sonmez and Unver (2004); we cite them and do not prove them here.

Claim 1 (free kidneys only shrink, and pointers stay in range). A pair never becomes ACTIVE again after it stops being ACTIVE, and a DONE pair never changes state. So a kidney that is not free never becomes free again. While pair ii is ACTIVE, its own kidney kik_i is free, so the scan of line L4 stops at or before kik_i, at the first free kidney or ww on the list. This is the best free item of tit_i. Proof. The only state changes are ACTIVE to DONE (lines L6 and L10), ACTIVE to TAIL or DONE (line L11), and TAIL to DONE (line L10). Entries before ptr[i]\text{ptr}[i] were skipped because their kidneys were not free, and they stay not free. □\square

Claim 2 (the arcs of a round). In a round, each ACTIVE pair ii has one arc, to the pair that owns target[i]\text{target}[i], or to ww. If the target is a kidney, its pair is ACTIVE or TAIL, by Claim 1. Restricted to the ACTIVE pairs, this is a functional graph in which some arcs leave the set: to ww or to TAIL pairs. The cycles of line L5 are exactly the cycles of this graph, and they are the cycles of the TTCC procedure in this round. Proof. The search of line L5 follows each arc from each ACTIVE pair that it has not yet seen, colouring the pairs of the current walk. It stops at ww, at a TAIL pair, or at a pair that has a colour. If that pair is on the current walk, the end of the walk from it is a cycle, and every cycle is found this way when the search first enters it. □\square

Claim 3 (chains). If line L5 finds no cycle, the walk of line L9 from aa visits distinct ACTIVE pairs and stops at a pair qmq_m whose target is ww or the kidney of a TAIL pair. The sequence ka,ta=tq1,kq2,tq2,…,tqmk_a, t_a = t_{q_1}, k_{q_2}, t_{q_2}, \dots, t_{q_m}, followed by ww or by the TAIL kidney, is the ww-chain that starts at pair aa. Proof. A repeated ACTIVE pair would close a cycle among the ACTIVE pairs, which line L5 did not find, so the walk visits distinct pairs and stops after at most nn steps. It can only stop where line L9 says. With a TAIL pair zz at the end, its patient already has its item and its free kidney is the end of an earlier kept chain, so the new chain continues the earlier one, which ends in ww, as in the procedure with kept chains. Line L8 picks the ACTIVE pair of highest priority, which is the chain choice of rules d and e. □\square

Termination. Every round either removes at least one cycle (line L6) or changes at least the pair aa from ACTIVE to TAIL or DONE (line L11). By Claim 1 no pair becomes ACTIVE again, so there are at most nn rounds, and each round is finite by Claims 1 and 3.

Feasibility. We show that each kidney ends up given to exactly one patient or in KwK_w.

  • In line L6, the patients of a cycle get the kidneys of the next pairs on the cycle. These kidneys are free and belong to the cycle itself, and all pairs of the cycle become DONE, so no later round uses them.
  • In line L10, patient qlq_l gets the kidney of ql+1q_{l+1} for l<ml < m, and these pairs become DONE. If the chain ends at a TAIL pair zz, patient qmq_m gets kzk_z, which was free, and zz becomes DONE. If it ends at ww, patient qmq_m gets ww. Kidney kak_a is not given in this round: with rule d it goes to KwK_w and aa is DONE, and with rule e pair aa becomes TAIL and kak_a stays free.
  • Line L12 puts the kidneys of the remaining TAIL pairs into KwK_w.

Every pair passes through these lines, since at the end no pair is ACTIVE. Only free kidneys are ever given, and a kidney stops being free when it is given or sent to KwK_w, so no kidney is used twice. A TAIL kidney is either given in a later chain (and its pair becomes DONE) or sent to KwK_w in line L12. So every kidney is given exactly once. Each chain that ends at ww gives ww to one patient and creates one tail kidney that eventually goes to a patient or to KwK_w; a chain that ends at a TAIL pair gives ww to nobody, uses the old tail kidney and creates one new tail kidney. Counting, the number of patients with ww equals ∣Kw∣|K_w|.

Individual rationality. Each patient tit_i gets target[i]\text{target}[i] from the round in which pair ii stops being ACTIVE. By Claim 1 this is its best free item at that time, which is at least as good as kik_i, because kik_i is still free then.

Agreement with top trading cycles. If no list has ww before the own kidney, no target is ever ww (Claim 1), and no pair ever becomes TAIL, since that needs a chain, which needs an arc to ww or to a TAIL pair. So every round has a cycle, and line L6 removes the cycles of the pointer graph of the remaining pairs, which is the round version of top trading cycles. ■\blacksquare

Cost. By termination there are at most nn rounds. In a round, line L4 costs O(n)O(n) plus the pointer moves, line L5 visits each ACTIVE pair once (O(n)O(n), plus the cost of cutting the cycle out of the walk, which is at most the length of the walk), and lines L8 to L11 cost O(n)O(n). By Claim 1 each pointer moves only forward inside its list, so all pointer moves together cost O(L)O(L). The total time is O(n2+L)O(n^2 + L) and the extra space is O(n)O(n).

Complexity

The model is the word RAM. Each round makes at least one ACTIVE pair TAIL or DONE, and no pair becomes ACTIVE again, so there are at most nn rounds. In a round, line L4 costs O(n)O(n) besides pointer moves, the cycle search of line L5 visits each ACTIVE pair once, in O(n)O(n) time, and lines L8 to L11 cost O(n)O(n). A kidney that is not free never becomes free again, so the pointers only move forward, at most LL steps in total. The total time is O(n2+L)O(n^2 + L) and the extra space is O(n)O(n).

Properties

  • Individually rational. No patient gets an item it ranks below its own donor's kidney.
  • Pareto efficient with rule e, and with every rule that keeps the selected chains until the last round (Theorem 1 of the 2004 paper).
  • Strategyproof with rules a, d, e and f (Theorem 2). The theorem does not cover rules b and c, which pick the longest chain.
  • Top trading cycles as a special case. If no patient ranks ww above its own kidney, every round removes cycles only, and the result is the top trading cycles allocation.
  • Cycles can be long. As in top trading cycles, nothing bounds the length of a cycle or a chain.

Variants and improvements

  • Chain selection rules. Rule a removes minimal chains one at a time, rules b and c take the longest chain and remove or keep it, rules d and e take the chain from the pair of highest priority and remove or keep it, and rule f is a priority rule that also takes blood types into account.
  • Bounded cycles. Clinics need short cycles, because all operations of a cycle take place at the same time. The optimization version with a length bound is the kidney exchange problem, solved in practice by the cycle formulation.
  • Pairwise exchange. If only swaps of two pairs are allowed and patients are indifferent among compatible kidneys, maximum matching gives an efficient outcome; Roth, Sonmez and Unver studied this case in 2005.

When to use it

Use TTCC as a model for kidney exchange with a connection to the deceased-donor list, where strategyproofness and efficiency for the patients are the goals, and where the lengths of cycles and chains are not a concern. In practice the length limit dominates, and clinics use integer programming on the kidney exchange problem instead.

Pitfalls

  • Removing chains too early. With rule d the tail kidney leaves at once, and patients that would want it later lose it; this is why rule d is not efficient.
  • Looking for chains while cycles exist. The procedure removes all cycles first. Picking a chain while a cycle exists can change the result and break the theorems.
  • Forgetting the tail kidney. With rule e the tail pair's patient is served, but its kidney is still free. It must go to the waiting list at the end, or the donor is lost.
  • Using it with a length bound. Cutting cycles and chains after the fact loses efficiency and strategyproofness.

Implementations

The Python version takes the lists as lists of kidney indices with −1-1 for ww, each containing the own kidney, an optional priority order and a flag for rule e or rule d. It returns the item of each patient and the kidneys that go to the waiting list. The tests check the example, the inefficiency of rule d, feasibility and individual rationality on random cases, efficiency of rule e against a brute force search over all outcomes, strategyproofness for both rules over all false lists of three pairs, and agreement with top trading cycles when no patient lists ww before its own kidney.

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.

top_trading_cycles_and_chains.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/top-trading-cycles-and-chains/. The authors are listed in prov/4BQP88.jsonl.

from typing import Optional, Sequence

W = -1  # the waiting list option: priority on the deceased-donor waiting list

ACTIVE, TAIL, DONE = 0, 1, 2


def top_trading_cycles_and_chains(
    prefs: Sequence[Sequence[int]],
    priority: Optional[Sequence[int]] = None,
    keep: bool = True,
) -> tuple[list[int], list[int]]:
    """Top trading cycles and chains (Roth, Sonmez and Unver 2004).

    Pair i has patient i and donor kidney i. prefs[i] is the strict ranking of patient i,
    best first, over kidneys 0, ..., n - 1 and the option W = -1. It must contain i (keep
    the own kidney, that is, no exchange); entries after i are never used. priority is the
    order of the pairs for the chain selection rule (default 0, 1, ..., n - 1).
    keep=True is chain rule e: the selected w-chain stays, and the kidney at its tail stays
    available. keep=False is chain rule d: the chain is removed and its tail kidney goes to
    the waiting list at once.
    Returns (x, waitlist): x[i] is the kidney that patient i gets, or W, and waitlist is
    the sorted list of the kidneys that go to the deceased-donor waiting list.
    There are at most n rounds and each costs O(n) besides the pointer moves, which only go
    forward, so the time is O(n^2 + total list length) and the extra space is O(n).
    """
    n = len(prefs)
    for i, lst in enumerate(prefs):
        if len(set(lst)) != len(lst) or any(not -1 <= h < n for h in lst) or i not in lst:
            raise ValueError("each list must rank kidneys and W without repeats and contain the own kidney")
    order = list(range(n)) if priority is None else list(priority)
    if sorted(order) != list(range(n)):
        raise ValueError("priority must be an order of the pairs")
    ptr = [0] * n  # @line L1
    state = [ACTIVE] * n
    x: list[int] = [W] * n  # @line L2
    waitlist: list[int] = []
    active = n
    while active > 0:  # @line L3
        target = [W] * n
        for i in range(n):  # @line L4
            if state[i] == ACTIVE:
                while prefs[i][ptr[i]] != W and state[prefs[i][ptr[i]]] == DONE:
                    ptr[i] += 1
                target[i] = prefs[i][ptr[i]]
        cycles = []
        color = [0] * n  # 0 not seen, 1 on the current walk, 2 finished
        for s in range(n):
            if state[s] != ACTIVE or color[s] != 0:
                continue
            walk = []
            v = s
            while v != W and state[v] == ACTIVE and color[v] == 0:
                color[v] = 1
                walk.append(v)
                v = target[v]
            if v != W and state[v] == ACTIVE and color[v] == 1:
                cycles.append(walk[walk.index(v):])
            for u in walk:
                color[u] = 2
        if cycles:  # @line L5
            for cyc in cycles:  # @line L6
                for i in cyc:
                    x[i] = target[i]
                    state[i] = DONE
                active -= len(cyc)
        else:  # @line L7
            a = next(i for i in order if state[i] == ACTIVE)  # @line L8
            path = [a]  # @line L9
            while target[path[-1]] != W and state[target[path[-1]]] == ACTIVE:
                path.append(target[path[-1]])
            end = target[path[-1]]  # W, or the kidney of a TAIL pair
            for q in path:  # @line L10
                x[q] = target[q]
            for q in path[1:]:
                state[q] = DONE
            if end != W:
                state[end] = DONE
            active -= len(path)
            if keep:  # @line L11
                state[a] = TAIL
            else:
                state[a] = DONE
                waitlist.append(a)
    waitlist.extend(i for i in range(n) if state[i] == TAIL)  # @line L12
    return x, sorted(waitlist)
test_top_trading_cycles_and_chains.py 162 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/top-trading-cycles-and-chains/. The authors are listed in prov/4BQP88.jsonl.

import random
import unittest
from itertools import permutations, product

from top_trading_cycles_and_chains import W, top_trading_cycles_and_chains as ttcc


def all_lists(i, n):
    """Every list of patient i up to its own kidney: the entries after it never matter."""
    others = [h for h in range(n) if h != i] + [W]
    out = []
    for k in range(len(others) + 1):
        for s in permutations(others, k):
            out.append(list(s) + [i])
    return out


def random_list(rng, i, n):
    others = [h for h in range(n) if h != i] + [W]
    k = rng.randint(0, len(others))
    return rng.sample(others, k) + [i]


def rank(lst, h):
    """Position of h in the list; anything after the own kidney is worse than the own kidney."""
    return lst.index(h) if h in lst else len(lst)


def dominated(prefs, x):
    """Brute force: return an outcome that all patients weakly prefer and one strictly, or None.

    An outcome gives each patient a kidney or W; a kidney goes to at most one patient, and W
    can go to many. Only items up to the own kidney can be at least as good as x.
    """
    n = len(prefs)
    options = [lst[: lst.index(i) + 1] for i, lst in enumerate(prefs)]
    b = [rank(prefs[i], x[i]) for i in range(n)]
    for y in product(*options):
        ks = [h for h in y if h != W]
        if len(ks) != len(set(ks)):
            continue
        a = [rank(prefs[i], y[i]) for i in range(n)]
        if all(p <= q for p, q in zip(a, b)) and a != b:
            return y
    return None


def ttc_reference(prefs):
    """Plain top trading cycles by rounds, for lists in which W is never reached."""
    n = len(prefs)
    left = set(range(n))
    x = [None] * n
    while left:
        point = {i: next(h for h in prefs[i] if h in left) for i in left}
        gone = set()
        for s in left:
            seen = []
            i = s
            while i not in seen and i not in gone:
                seen.append(i)
                i = point[i]
            if i in seen:
                for k in seen[seen.index(i):]:
                    x[k] = point[k]
                    gone.add(k)
        left -= gone
    return x


class TestTopTradingCyclesAndChains(unittest.TestCase):
    def test_page_example(self):
        # pairs 1..5 of the page are 0..4 here
        prefs = [[1, 0], [0, 1], [0, W, 2], [2, 3], [2, 3, W, 4]]
        self.assertEqual(ttcc(prefs, keep=True), ([1, 0, W, 2, 3], [4]))
        self.assertEqual(ttcc(prefs, keep=False), ([1, 0, W, 3, W], [2, 4]))

    def test_rule_d_is_not_efficient(self):
        prefs = [[0], [W, 1], [1, 2]]
        x, wl = ttcc(prefs, keep=False)
        self.assertEqual((x, wl), ([0, W, 2], [1]))
        self.assertEqual(dominated(prefs, x), (0, W, 1))
        x, wl = ttcc(prefs, keep=True)
        self.assertEqual((x, wl), ([0, W, 1], [2]))
        self.assertIsNone(dominated(prefs, x))

    def test_edge_cases(self):
        self.assertEqual(ttcc([]), ([], []))
        self.assertEqual(ttcc([[0]]), ([0], []))
        self.assertEqual(ttcc([[W, 0]]), ([W], [0]))
        self.assertEqual(ttcc([[W, 0]], keep=False), ([W], [0]))
        with self.assertRaises(ValueError):
            ttcc([[1], [0]])
        with self.assertRaises(ValueError):
            ttcc([[0], [1]], priority=[0, 0])

    def test_without_w_it_is_ttc(self):
        rng = random.Random(3)
        for _ in range(100):
            n = rng.randint(1, 30)
            prefs = [rng.sample(range(n), n) for _ in range(n)]
            for keep in (True, False):
                self.assertEqual(ttcc(prefs, keep=keep), (ttc_reference(prefs), []))

    def test_outcome_structure(self):
        rng = random.Random(5)
        for _ in range(300):
            n = rng.randint(1, 12)
            prefs = [random_list(rng, i, n) for i in range(n)]
            pri = rng.sample(range(n), n)
            for keep in (True, False):
                x, wl = ttcc(prefs, pri, keep)
                given = [h for h in x if h != W]
                # each kidney goes to exactly one patient or to the waiting list
                self.assertEqual(sorted(given + wl), list(range(n)))
                self.assertEqual(x.count(W), len(wl))
                # individually rational
                for i in range(n):
                    self.assertLessEqual(rank(prefs[i], x[i]), rank(prefs[i], i))

    def test_rule_e_efficient(self):
        rng = random.Random(11)
        for _ in range(250):
            n = rng.randint(2, 4)
            prefs = [random_list(rng, i, n) for i in range(n)]
            pri = rng.sample(range(n), n)
            x, _ = ttcc(prefs, pri, keep=True)
            self.assertIsNone(dominated(prefs, x), (prefs, pri))

    def test_strategyproof_three_pairs(self):
        # every false list of the patient against a sample of true profiles, for rules d and e
        rng = random.Random(7)
        n = 3
        lists = [all_lists(i, n) for i in range(n)]
        for _ in range(60):
            prefs = [rng.choice(lists[i]) for i in range(n)]
            for keep in (True, False):
                x, _ = ttcc(prefs, keep=keep)
                for i in range(n):
                    for lie in lists[i]:
                        y, _ = ttcc(prefs[:i] + [lie] + prefs[i + 1:], keep=keep)
                        self.assertLessEqual(rank(prefs[i], x[i]), rank(prefs[i], y[i]))

    def test_strategyproof_random(self):
        rng = random.Random(8)
        for _ in range(120):
            n = 6
            prefs = [random_list(rng, i, n) for i in range(n)]
            pri = rng.sample(range(n), n)
            i = rng.randrange(n)
            for keep in (True, False):
                x, _ = ttcc(prefs, pri, keep)
                for _ in range(8):
                    lie = random_list(rng, i, n)
                    y, _ = ttcc(prefs[:i] + [lie] + prefs[i + 1:], pri, keep)
                    self.assertLessEqual(rank(prefs[i], x[i]), rank(prefs[i], y[i]))


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

History

Before 2004, kidney exchange was done in small numbers, mostly as swaps between two incompatible pairs and as exchanges with the waiting list. Roth, Sonmez and Unver (2004) modelled kidney exchange as a housing market with an extra option, introduced TTCC with six chain selection rules, and proved efficiency and strategyproofness for some of them. Their later work on pairwise and short exchanges led to the clearinghouses that now use bounded cycles and chains.

References

  1. Alvin E. Roth, Tayfun Sonmez and M. Utku Unver, Kidney exchange, Quarterly Journal of Economics 119(2), 457 to 488 (2004), the TTCC mechanism, the chain selection rules a to f, and Theorems 1 and 2 (efficiency for rules that keep the chains, strategyproofness for rules a, d, e and f)
  2. Lloyd Shapley and Herbert Scarf, On cores and indivisibility, Journal of Mathematical Economics 1(1), 23 to 37 (1974), the housing market and the top trading cycle algorithm that TTCC extends

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