Algorithmcore
Top trading cycles
Also called TTC, Gale's top trading cycles.
Each agent points to the owner of its favourite remaining house, and the agents on a cycle trade and leave. The result is the unique strict core allocation of a housing market.
- Solves
- House allocation problem
- Time
- O(n + L) worst
- Space
- O(n) extra
- Where
- L = the total length of the preference lists; n = the number of agents
- Model
- Word RAM
- Properties
- deterministiciterative
- Evidence
- Proof sketchCode in 1 languages
- Origin
- David Gale, Lloyd Shapley, Herbert Scarf, 1974
Top trading cycles (TTC) finds the outcome of a Shapley-Scarf housing market, where each agent owns one house and ranks all houses. Each agent points to the owner of the house it likes best among the houses still in the market. Since every agent points somewhere, the pointers contain a cycle, and the agents on it trade along the cycle: each gets the house it points to. They leave with their houses, and the rest repeat. The result is the unique allocation in the strict core, as the Roth-Postlewaite theorem states. It is individually rational, Pareto optimal, and no agent gains by a false ranking. With a walk that follows the pointers and never moves a list pointer back, it runs in time, where is the total length of the lists, so for complete lists.
In plain words
Everyone owns a house and has a favourite. Each person points at the owner of the house they like best. Follow the arrows from anyone: since there are finitely many people, you come back to someone you saw, and that closes a loop. The people in the loop swap houses so that each gets the house they pointed at, and they go home. The others point again among the houses that are left, and the process repeats until everyone is gone.
People in a loop get their favourite house among those left, and nobody can do better by lying about what they like.
The problem
There are agents , and agent owns house . Each agent has a strict ranking of the houses. A list may stop at the own house; the agent ranks the houses that it does not list below its own. The output is an allocation: a permutation with the house of agent .
The algorithm
TOP-TRADING-CYCLES(lists)- 1
for each agent i do ptr[i] ← 1 - 2
for each agent i do x[i] ← NIL - 3
for each agent s that is still in the market, in any order do - 4
path ← (s) - 5
while path is not empty do - 6
i ← the last agent on path - 7
while house list[i][ptr[i]] has left the market do ptr[i] ← ptr[i] + 1 - 8
j ← the owner of house list[i][ptr[i]] - 9
if j is on path then remove j, …, i from the end of path; each of them gets the house it points to, and all of them leave the market with their houses - 10
else append j to path - 11
return x
The path is a walk along the pointers. Line L7 moves the pointer of the last agent to its best house that is still in the market. Line L8 follows the pointer. If the owner is already on the path, the end of the path from to is a cycle, and line L9 makes it trade. After the trade the walk goes on from the agent that is now last, whose pointer may now point to a house that has left. Its own house is on its list and is still in the market, so line L7 always stops.
The textbook statement works in rounds: in each round all remaining agents point, and all cycles trade at once. The walk gives the same result, and it is faster because it does not rebuild the pointers in each round.
Example
Five agents. Agent 1 ranks , agent 2 ranks , agent 3 ranks , agent 4 ranks , and agent 5 ranks . The walk starts at agent 1.
| step | path | last agent points to | action |
|---|---|---|---|
| 1 | 1 | owner of , agent 3 | append 3 |
| 2 | 1, 3 | owner of , agent 2 | append 2 |
| 3 | 1, 3, 2 | owner of , agent 1, on the path | cycle 1, 3, 2: agent 1 gets , 3 gets , 2 gets |
| 4 | (empty) | start again at agent 4 | |
| 5 | 4 | has left, so , agent 5 | append 5 |
| 6 | 4, 5 | owner of , agent 4, on the path | cycle 4, 5: agent 4 gets , 5 gets |
The allocation is . Agents 1, 2 and 3 get their first choices. Agents 4 and 5 both wanted or , but went in the first cycle, so they trade with each other. A brute force check over all allocations and all coalitions shows that this is the only allocation that no coalition can weakly improve on.
Edge cases. An agent whose favourite house is its own forms a cycle of length one and keeps its house. If all agents rank their own house first, nobody trades. With one agent, the agent keeps its house.
Correctness
Each agent on the path, except the last one, points to the next agent on the path, and that agent's house is its best house still in the market. This holds because houses only leave, so a best remaining house stays the best while it remains. So when line L9 finds a cycle, each agent on it points to the owner of its best remaining house: it is a cycle of the pointer graph, a functional graph in which every agent has one outgoing arc.
Any order of removing such cycles gives the same allocation, and it is the unique allocation in the strict core. In outline: the agents of the first cycle get their first choices, so any other allocation that changes their houses is weakly blocked by that cycle alone. Then the agents of the second cycle get their best houses outside the first cycle, and so on. Conversely, a coalition that tries to block the result must contain an agent that wants a house of an earlier cycle, but the agents of the earlier cycles in the coalition need all those houses for themselves. The proof file gives both directions in full, and also the proof that no agent gains by a false list.
Proof: Top trading cycles gives the unique strict core allocation and is strategyprooffull
Agent owns house , for , and has a strict ranking of the houses. A list that stops at stands for any ranking that puts the unlisted houses below ; we show below that the algorithm never reads past , so the choice of these rankings does not matter. An allocation is a permutation , with the house of agent . A coalition weakly blocks if there is a permutation of the houses among the agents of with for all and for some . The strict core is the set of allocations that no coalition weakly blocks.
At any moment, call the agents and houses that have not left remaining; agent remains exactly when remains. The pointer graph has the remaining agents as nodes and an arc from to the owner of the best remaining house of . Every node has exactly one outgoing arc, so the graph has at least one cycle.
Claim 1 (pointers stay in range). Whenever line L7 runs for a remaining agent , it stops at an entry at or before , and the entry is the best remaining house of . Proof. Each list contains , which remains while remains. Houses only leave, so every entry before was already gone at an earlier time and is still gone. Line L7 skips gone houses and stops at the first remaining one, which is the best remaining house because the list is in order of preference.
Claim 2 (path invariant). At the start of each pass of line L5, the path consists of distinct remaining agents , and for each , points to , which is the best remaining house of . Proof. It holds when line L4 sets the path to one remaining agent. Line L10 appends after the last agent ; by Claim 1 and line L8, is the best remaining house of , and is not on the path. Line L9 removes a suffix and the houses of these agents only. The agents before on the path point to houses of agents on the path, and only the agent just before points into the removed part; it becomes the last agent, for which the invariant asks nothing. For the others, the house they point to remains, so it is still their best remaining house.
Claim 3 (each trade is a cycle of the pointer graph). When line L9 runs, the agents form a cycle of the pointer graph, and each gets the house of the next agent on the cycle. Proof. By Claim 2, each with points to , its best remaining house, and by Claim 1 and line L8, points to , its best remaining house.
Termination. An agent is appended to the path only when it is not on it, and it stays on the path until line L9 removes it, at which point it leaves the market. A left agent is never appended again, because line L8 only finds owners of remaining houses. So each agent is appended at most once. Each pass of line L5 appends one agent or removes at least one, so over the whole run there are at most passes. The loop of line L3 starts a walk only at a remaining agent, and the walk ends only when the path is empty, which happens only after the start agent leaves. So after the loop every agent has left, and by Claim 3 every agent got a house.
Cycle removal. Call a cycle removal any process that, starting with all agents, repeatedly picks a cycle of the current pointer graph, gives each agent on it the house of the next agent, and removes these agents and their houses. By Claim 3 and termination, the algorithm performs a cycle removal for every start order. Let be the result of a cycle removal with cycles in the order of removal, and let be the set of houses of the agents of . The houses given to are the houses of , so maps the agents of onto . Each agent of gets its best house outside .
Claim 4 ( is in the strict core). Proof. Suppose a coalition and a permutation of its houses weakly block . Since some agent is strictly better off, for some . Choose such an in the cycle with the smallest . The preferences are strict, so . The house is the best house of outside , so . Let . By the choice of , for every , so . These are houses in , and they are houses of agents of because only uses houses of . The houses of that belong to agents of are exactly the houses of , and there are of them. So is the set of all houses of . But is a house of an agent of in , that is, a house of , and , so gives the same house to and to an agent of . This contradicts that is a permutation.
Claim 5 (the strict core has at most the one element ). Proof. Let be in the strict core. We show by induction on that for all agents of . Assume it for . Then maps the agents of onto , so every agent of gets under a house outside . Each agent of gets under its best house outside , so . The allocation restricted to is a permutation of the houses of . If for some , then by strictness, and the coalition with weakly blocks , a contradiction. So on .
By Claims 4 and 5, every cycle removal, and so every run of the algorithm with any start order, returns the same allocation, the unique element of the strict core. In particular it equals the result of the textbook rounds, which is also a cycle removal. Taking in Claim 4 shows that (individual rationality), and with Claim 1 this shows that no agent gets a house that it lists after , so cutting a list after does not change the result. Taking as all agents shows that is Pareto optimal.
Claim 6 (strategyproofness). Fix agent and the lists of the others. Let be the result when reports its true list, and the result when it reports any other list that contains . Then . Proof. Both results can be computed by any cycle removal. Use this one: while the pointer graph has a cycle without , remove the cycle without that contains the smallest agent. The arcs of the agents other than , and so the cycles without , depend only on the remaining set and the lists of the others. By induction, the two runs remove the same cycles, in the same order, until they reach the same remaining set in which every cycle contains . A functional graph has a cycle in each weakly connected part, so the pointer graph on is connected with one cycle, through , and the path of arcs from any agent of leads to . Now points to the owner of its best house in according to its report, and the cycle is , then , then the path from back to . So gets its reported best house in . With the true list this is the truly best house in , and with the false list it is some house in . Hence .
Cost. By termination there are at most passes of line L5, each costing besides line L7 and the removals of line L9. Line L9 costs per removed agent, in total. By Claim 1, each pointer only moves forward inside its list, so line L7 costs in total, where is the total list length. The loop of line L3 costs . The total time is , and the extra space is .
Complexity
The model is the word RAM. An agent is appended to the path at most once, because it stays on the path until it leaves the market, and an agent on the path is never appended again. Each pass of line L5 either appends an agent or removes at least one, so there are at most passes. Line L7 only moves pointers forward, so its total cost is at most , the total list length, and line L9 costs per removed agent. The total time is , which is for complete lists and linear in the input size. The extra space is for the pointers, the path and the flags.
The round version recomputes all pointers and finds all cycles in each round. In a functional graph every cycle is a strongly connected component with more than one vertex or with a self-loop, so Tarjan's algorithm finds all cycles of a round in linear time, as does a simple walk with colours. A round costs besides the pointer moves, and there can be rounds, so besides the scans of the lists.
Properties
- Strict core, unique. The result is the only allocation that no coalition can weakly improve on by trading its own houses (Roth and Postlewaite 1977). It is also the only competitive allocation.
- Individually rational and Pareto optimal. These follow from the strict core for the coalitions of one agent and of all agents.
- Strategyproof. No agent gets a better house by a false list (Roth 1982). The result is even group strategyproof: no group can misreport so that all its members are at least as well off and one is better off (Bird 1984).
- Characterized. Ma (1994) showed that TTC is the only rule on housing markets that is individually rational, Pareto optimal and strategyproof.
- Independent of the order. The walk can start at any agent and the cycles can trade in any order.
Variants and improvements
- House allocation with random owners. Give the houses to the agents uniformly at random as endowments, then run TTC. Abdulkadiroglu and Sonmez (1998) proved that this gives the same lottery over matchings as random serial dictatorship.
- Kidney exchange. Top trading cycles and chains lets a patient-donor pair point to the waiting list for a deceased donor, and then also trades along chains that end at the list.
- School choice. In the TTC rule for the school choice problem, students point to schools and schools point to the student with the highest priority, and the cycles trade seats.
- Ties. With indifferences the strict core can be empty, and a fixed tie-break inside TTC can lose Pareto optimality. Rules for ties first trade inside groups of equally good houses; they are more involved.
When to use it
Use TTC when the agents already own the objects and must not lose by taking part: tenants who trade rooms, pairs in a kidney exchange, students with a seat that they keep unless they trade it. It is the only rule that is individually rational, efficient and strategyproof at once. When nobody owns the objects, use serial dictatorship or a random order instead.
Pitfalls
- Pointing at houses instead of owners. The graph has agents as nodes, and an arc goes to the owner of the wanted house. Each agent still owns the house it started with until its cycle trades.
- Long cycles. A cycle can contain every agent. In a kidney exchange all transplants of a cycle must take place at the same time, so long cycles are not practical, and a length bound turns the problem into the NP-hard kidney exchange problem.
- Ties broken in a fixed way. With indifferences, a fixed tie-break gives a strategyproof rule, but the result need not be Pareto optimal.
- Rebuilding every round. Recomputing all pointers each round wastes time; keep the pointers and move them forward only.
Implementations
The Python version takes the lists as lists of house indices (agent owns house ), each containing the own house, and an optional start order for the walk. It returns with the house of agent . The tests compare the result with the strict core found by brute force over all allocations and coalitions, for every profile with three agents and random profiles with four, check strategyproofness over all false lists, and compare with the round version and other start orders.
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/.
"""Preference profiles, majority relations and brute force axiom checkers.
The candidates are 0, ..., m - 1. A ranking is a tuple of all m candidates, best first:
(2, 0, 1) means that 2 is preferred to 0 and 0 to 1. A profile is a tuple of n rankings,
one per voter. An approval ballot is a frozenset of candidates, and an approval profile is
a tuple of n ballots.
A rule is a function rule(profile, m). A resolute rule returns one candidate (an int); a
correspondence returns a nonempty frozenset of candidates. The checkers accept both: they
turn an int w into frozenset({w}).
Each checker takes the rule, m and n, and by default tries every profile of all_profiles(m,
n). Pass profiles= to check a given list of profiles instead (for example approval profiles,
or a random sample when the full domain is too large). Each checker returns None when the
property holds on every profile it tried, and else a counterexample tuple.
There is no voting rule in this module. Every count is an exact integer.
"""
from itertools import permutations, product
# ---------------------------------------------------------------- rankings and profiles
def all_rankings(m):
"""Return the list of the m! rankings of 0, ..., m - 1, in lexicographic order."""
return list(permutations(range(m)))
def all_profiles(m, n):
"""Yield every profile of n rankings of m candidates: (m!)^n profiles, voters ordered."""
return product(all_rankings(m), repeat=n)
def random_profile(rng, m, n):
"""Return a profile of n rankings drawn uniformly and independently (impartial culture)."""
return tuple(tuple(rng.sample(range(m), m)) for _ in range(n))
def position(r, a):
"""Return the position of candidate a in ranking r: 0 for the top."""
return r.index(a)
def prefers(r, a, b):
"""Return True if ranking r puts a above b."""
return r.index(a) < r.index(b)
def pairwise(profile, m):
"""Return the m by m matrix N with N[a][b] the number of voters who rank a above b."""
N = [[0] * m for _ in range(m)]
for r in profile:
for i, a in enumerate(r):
for b in r[i + 1:]:
N[a][b] += 1
return N
def margins(profile, m):
"""Return the m by m matrix of margins N[a][b] - N[b][a]."""
N = pairwise(profile, m)
return [[N[a][b] - N[b][a] for b in range(m)] for a in range(m)]
def condorcet_winner(profile, m):
"""Return the candidate with a positive margin over every other candidate, or None."""
M = margins(profile, m)
for a in range(m):
if all(M[a][b] > 0 for b in range(m) if b != a):
return a
return None
def weak_condorcet_winners(profile, m):
"""Return the frozenset of candidates whose margin over every other candidate is >= 0."""
M = margins(profile, m)
return frozenset(a for a in range(m) if all(M[a][b] >= 0 for b in range(m) if b != a))
def kendall_tau(r1, r2):
"""Return the number of pairs of candidates that r1 and r2 order differently."""
pos = {a: i for i, a in enumerate(r2)}
seq = [pos[a] for a in r1]
return sum(1 for i in range(len(seq)) for j in range(i + 1, len(seq)) if seq[i] > seq[j])
def is_single_peaked_on(profile, axis):
"""Return True if every ranking of the profile is single-peaked on the axis.
axis is a tuple of all candidates, left to right. A ranking is single-peaked on the axis
exactly when, for each k, its k best candidates form a contiguous block of the axis.
"""
where = {a: i for i, a in enumerate(axis)}
for r in profile:
lo = hi = where[r[0]]
for a in r[1:]:
p = where[a]
if p == lo - 1:
lo = p
elif p == hi + 1:
hi = p
else:
return False
return True
def lex_tiebreak(candidates):
"""Return the candidate with the smallest index: the default tie-breaking rule."""
return min(candidates)
def random_approval_profile(rng, m, n, p):
"""Return n approval ballots; each voter approves each candidate with probability p."""
return tuple(frozenset(a for a in range(m) if rng.random() < p) for _ in range(n))
def permute_profile(profile, pi):
"""Rename the candidates: candidate a becomes pi[a]. Works for rankings and approval ballots."""
out = []
for ballot in profile:
if isinstance(ballot, (set, frozenset)):
out.append(frozenset(pi[a] for a in ballot))
else:
out.append(tuple(pi[a] for a in ballot))
return tuple(out)
# ---------------------------------------------------------------- axiom checkers
def _as_set(result):
if isinstance(result, (set, frozenset)):
return frozenset(result)
return frozenset([result])
def _domain(m, n, profiles):
return all_profiles(m, n) if profiles is None else profiles
def _candidate_generators(m):
"""A transposition and an m-cycle: together they generate every permutation of the candidates."""
gens = []
if m >= 2:
swap = list(range(m))
swap[0], swap[1] = 1, 0
gens.append(tuple(swap))
if m >= 3:
gens.append(tuple((a + 1) % m for a in range(m)))
return gens
def check_anonymity(rule, m, n, profiles=None):
"""Check that permuting the voters does not change the result.
It tries the swap of voters 0 and 1 and the cyclic shift of the voters. These generate all
permutations, so on the full domain this is a complete test. Returns None or
(profile, permuted_profile).
"""
for P in _domain(m, n, profiles):
P = tuple(P)
if len(P) < 2:
continue
base = _as_set(rule(P, m))
others = [(P[1], P[0]) + P[2:], P[1:] + P[:1]]
for Q in others:
if _as_set(rule(Q, m)) != base:
return (P, Q)
return None
def check_neutrality(rule, m, n, profiles=None):
"""Check that renaming the candidates by pi renames the result by pi.
It tries a transposition and an m-cycle of the candidates, which generate all permutations.
A resolute rule with a fixed tie-breaking order usually fails this test; test its
correspondence instead. Returns None or (profile, pi).
"""
gens = _candidate_generators(m)
for P in _domain(m, n, profiles):
P = tuple(P)
base = _as_set(rule(P, m))
for pi in gens:
if _as_set(rule(permute_profile(P, pi), m)) != frozenset(pi[a] for a in base):
return (P, pi)
return None
def check_pareto(rule, m, n, profiles=None):
"""Check that no candidate b wins when every voter ranks some a above b.
Returns None or (profile, a, b).
"""
for P in _domain(m, n, profiles):
P = tuple(P)
W = _as_set(rule(P, m))
N = pairwise(P, m)
for b in W:
for a in range(m):
if a != b and N[a][b] == len(P):
return (P, a, b)
return None
def check_condorcet_consistency(rule, m, n, profiles=None):
"""Check that a Condorcet winner, when one exists, is the unique winner.
Returns None or (profile, condorcet_winner).
"""
for P in _domain(m, n, profiles):
P = tuple(P)
c = condorcet_winner(P, m)
if c is not None and _as_set(rule(P, m)) != frozenset([c]):
return (P, c)
return None
def _raise_once(r, w):
"""Return r with w moved up one place, or None if w is already on top."""
i = r.index(w)
if i == 0:
return None
s = list(r)
s[i - 1], s[i] = s[i], s[i - 1]
return tuple(s)
def check_monotonicity(rule, m, n, profiles=None):
"""Check that a winner stays a winner when one voter moves it up one place.
Every raise of w, with no other change in the relative order of the others, is a chain of
such one-place moves, so on the full domain this is a complete test. For a correspondence
the test is that w stays in the winning set. Returns None or (profile, raised_profile, w).
"""
for P in _domain(m, n, profiles):
P = tuple(P)
for w in _as_set(rule(P, m)):
for i, r in enumerate(P):
s = _raise_once(r, w)
if s is None:
continue
Q = P[:i] + (s,) + P[i + 1:]
if w not in _as_set(rule(Q, m)):
return (P, Q, w)
return None
def find_manipulation(rule, m, n, profiles=None):
"""Search for a voter who gets a strictly better winner by a false ranking.
The rule must be resolute (a correspondence must return one winner on every profile it
is called on). Returns None or (profile, voter, false_ranking): with the false ranking in
place of the voter's true one, the winner is one that the true ranking strictly prefers.
"""
rankings = all_rankings(m)
for P in _domain(m, n, profiles):
P = tuple(P)
w = _single(rule(P, m))
for i, r in enumerate(P):
if r[0] == w:
continue
for s in rankings:
if s == r:
continue
Q = P[:i] + (s,) + P[i + 1:]
if prefers(r, _single(rule(Q, m)), w):
return (P, i, s)
return None
def _single(result):
W = _as_set(result)
if len(W) != 1:
raise ValueError("find_manipulation needs a resolute rule")
return next(iter(W))
top_trading_cycles.py 55 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/top-trading-cycles/. The authors are listed in prov/YD7XQN.jsonl.
from typing import Optional, Sequence
def top_trading_cycles(
prefs: Sequence[Sequence[int]], start_order: Optional[Sequence[int]] = None
) -> list[int]:
"""Gale's top trading cycles for a Shapley-Scarf housing market.
Agent i owns house i, for i = 0, ..., n - 1. prefs[i] is the strict ranking of agent i,
best first. It must contain i; houses after i in the list are never used, so a list may
stop at i (the agent would rather keep its house than take those). Returns x with x[i]
the house that agent i gets.
The walk keeps a path of agents, each pointing to the owner of its best remaining
house; when the path closes a cycle, the cycle trades and leaves. start_order only
changes the order in which walks start (the result does not depend on it).
O(n + total list length) time, so O(n^2) for complete lists, and O(n) extra space:
each agent enters the path once, and each list pointer only moves forward.
"""
n = len(prefs)
for i, lst in enumerate(prefs):
if len(set(lst)) != len(lst) or any(not 0 <= h < n for h in lst) or i not in lst:
raise ValueError("each list must be a ranking of houses that contains the own house")
ptr = [0] * n # @line L1
left = [True] * n # agent i and its house i are still in the market
x = [-1] * n # @line L2
on_path = [False] * n
order = range(n) if start_order is None else start_order
for s in order: # @line L3
if not left[s]:
continue
path = [s] # @line L4
on_path[s] = True
while path: # @line L5
i = path[-1] # @line L6
while not left[prefs[i][ptr[i]]]: # @line L7
ptr[i] += 1
j = prefs[i][ptr[i]] # @line L8
if on_path[j]: # @line L9
cycle = [] # the agents j, ..., i at the end of the path
while True:
k = path.pop()
x[k] = prefs[k][ptr[k]] # k gets the house it points to
on_path[k] = False
cycle.append(k)
if k == j:
break
for k in cycle: # the houses of the cycle are the houses of its agents
left[k] = False
else: # @line L10
path.append(j)
on_path[j] = True
return x # @line L11
test_top_trading_cycles.py 130 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/top-trading-cycles/. The authors are listed in prov/YD7XQN.jsonl.
import random
import unittest
from itertools import combinations, permutations
from agtprefs import all_profiles, random_profile
from top_trading_cycles import top_trading_cycles
def ttc_by_rounds(prefs):
"""Reference: the textbook rounds. All agents point at once, all cycles leave."""
n = len(prefs)
left = set(range(n))
x = [-1] * 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: # a new cycle
for k in seen[seen.index(i):]:
x[k] = point[k]
gone.add(k)
left -= gone
return x
def rank(prefs, i, h):
return prefs[i].index(h)
def weakly_blocked(prefs, x):
"""Return a coalition S and a trade y of the houses of S that weakly blocks x, or None."""
n = len(prefs)
for k in range(1, n + 1):
for S in combinations(range(n), k):
for y in permutations(S):
a = [rank(prefs, i, h) for i, h in zip(S, y)]
b = [rank(prefs, i, x[i]) for i in S]
if all(p <= q for p, q in zip(a, b)) and a != b:
return S, y
return None
def strict_core(prefs):
n = len(prefs)
return [list(x) for x in permutations(range(n)) if weakly_blocked(prefs, list(x)) is None]
class TestTopTradingCycles(unittest.TestCase):
def test_page_example(self):
# agents 1..5 of the page are 0..4 here
prefs = [[2, 1, 0, 3, 4], [0, 2, 1, 3, 4], [1, 0, 2, 3, 4], [0, 4, 3, 1, 2], [3, 0, 1, 2, 4]]
self.assertEqual(top_trading_cycles(prefs), [2, 0, 1, 4, 3])
self.assertEqual(strict_core(prefs), [[2, 0, 1, 4, 3]])
def test_weak_core_is_larger(self):
# Roth-Postlewaite page: (h2, h3, h1) is not strongly blocked but is weakly blocked.
prefs = [[1, 0, 2], [0, 2, 1], [0, 1, 2]]
self.assertEqual(top_trading_cycles(prefs), [1, 0, 2])
self.assertEqual(strict_core(prefs), [[1, 0, 2]])
self.assertIsNotNone(weakly_blocked(prefs, [1, 2, 0]))
def test_edge_cases(self):
self.assertEqual(top_trading_cycles([]), [])
self.assertEqual(top_trading_cycles([[0]]), [0])
self.assertEqual(top_trading_cycles([[0, 1], [0, 1]]), [0, 1])
self.assertEqual(top_trading_cycles([[1, 0], [0, 1]]), [1, 0])
self.assertEqual(top_trading_cycles([[1, 0], [1]]), [0, 1]) # a list may stop at the own house
with self.assertRaises(ValueError):
top_trading_cycles([[1], [0]])
def test_unique_strict_core_exhaustive(self):
for profile in all_profiles(3, 3):
prefs = [list(r) for r in profile]
self.assertEqual(strict_core(prefs), [top_trading_cycles(prefs)])
def test_unique_strict_core_random(self):
rng = random.Random(4)
for _ in range(60):
prefs = [list(r) for r in random_profile(rng, 4, 4)]
self.assertEqual(strict_core(prefs), [top_trading_cycles(prefs)])
def test_strategyproof_exhaustive(self):
lies = [list(r) for r in permutations(range(3))]
for profile in all_profiles(3, 3):
prefs = [list(r) for r in profile]
x = top_trading_cycles(prefs)
for i in range(3):
for lie in lies:
y = top_trading_cycles(prefs[:i] + [lie] + prefs[i + 1:])
self.assertLessEqual(rank(prefs, i, x[i]), rank(prefs, i, y[i]))
def test_strategyproof_random(self):
rng = random.Random(9)
for _ in range(150):
n = 5
prefs = [list(r) for r in random_profile(rng, n, n)]
x = top_trading_cycles(prefs)
i = rng.randrange(n)
for _ in range(10):
lie = rng.sample(range(n), n)
y = top_trading_cycles(prefs[:i] + [lie] + prefs[i + 1:])
self.assertLessEqual(rank(prefs, i, x[i]), rank(prefs, i, y[i]))
def test_against_rounds_and_start_order(self):
rng = random.Random(1)
for _ in range(100):
n = rng.randint(1, 40)
prefs = [rng.sample(range(n), n) for _ in range(n)]
x = top_trading_cycles(prefs)
self.assertEqual(x, ttc_by_rounds(prefs))
self.assertEqual(sorted(x), list(range(n)))
order = rng.sample(range(n), n)
self.assertEqual(top_trading_cycles(prefs, order), x)
# cutting each list after the own house changes nothing
cut = [lst[: lst.index(i) + 1] for i, lst in enumerate(prefs)]
self.assertEqual(top_trading_cycles(cut), x)
# individually rational
self.assertTrue(all(rank(prefs, i, x[i]) <= rank(prefs, i, i) for i in range(n)))
if __name__ == "__main__":
unittest.main()
History
Shapley and Scarf (1974) defined the housing market and proved that its core is not empty by the top trading cycle algorithm, which they attributed to David Gale. Roth and Postlewaite (1977) showed that with strict preferences its result is the unique allocation in the strict core and the unique competitive allocation. Roth (1982) proved that it is strategyproof, Bird (1984) that it is group strategyproof, and Ma (1994) that it is the only individually rational, Pareto optimal and strategyproof rule. Abdulkadiroglu and Sonmez (1998) connected it with random serial dictatorship, and Roth, Sonmez and Unver (2004) extended it to kidney exchange.
References
- Lloyd Shapley and Herbert Scarf, On cores and indivisibility, Journal of Mathematical Economics 1(1), 23 to 37 (1974), the housing market model and the top trading cycle algorithm, which the paper attributes to David Gale
- Alvin E. Roth and Andrew Postlewaite, Weak versus strong domination in a market with indivisible goods, Journal of Mathematical Economics 4(2), 131 to 137 (1977), the uniqueness of the strict core allocation for strict preferences
- Alvin E. Roth, Incentive compatibility in a market with indivisible goods, Economics Letters 9(2), 127 to 132 (1982), the proof that truth-telling is a dominant strategy under top trading cycles
- Charles G. Bird, Group incentive compatibility in a market with indivisible goods, Economics Letters 14, 309 to 313 (1984), group strategyproofness of the core rule
- Strategy-proofness and the strict core in a market with indivisibilities, the characterization of the core rule by individual rationality, Pareto efficiency and strategyproofness
- Atila Abdulkadiroglu and Tayfun Sonmez, Random serial dictatorship and the core from random endowments in house allocation problems, Econometrica 66(3) (1998), the equivalence of the core from random endowments and random serial dictatorship
Where this leads
About this page
The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.
| 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 YD7XQN Edit this page History Report an error Markdown