Algorithm Search⌘K

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.

Time
O(n + L) worst
Space
O(n) extra
Where
L = the total length of the preference lists; n = the number of agents
Properties
deterministiciterative
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 O(n+L)O(n + L) time, where LL is the total length of the lists, so O(n2)O(n^2) 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 nn agents 1,…,n1, \dots, n, and agent ii owns house hih_i. 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 xx with x(i)x(i) the house of agent ii.

The algorithm

  1. TOP-TRADING-CYCLES(lists)
  2. 1for each agent i do ptr[i] ← 1
  3. 2for each agent i do x[i] ← NIL
  4. 3for each agent s that is still in the market, in any order do
  5. 4path ← (s)
  6. 5while path is not empty do
  7. 6i ← the last agent on path
  8. 7while house list[i][ptr[i]] has left the market do ptr[i] ← ptr[i] + 1
  9. 8j ← the owner of house list[i][ptr[i]]
  10. 9if 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
  11. 10else append j to path
  12. 11return 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 jj to ii 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 h3≻h2≻h1h_3 \succ h_2 \succ h_1, agent 2 ranks h1≻h3≻h2h_1 \succ h_3 \succ h_2, agent 3 ranks h2≻h1≻h3h_2 \succ h_1 \succ h_3, agent 4 ranks h1≻h5≻h4h_1 \succ h_5 \succ h_4, and agent 5 ranks h4≻h1≻h2≻h3≻h5h_4 \succ h_1 \succ h_2 \succ h_3 \succ h_5. The walk starts at agent 1.

step path last agent points to action
1 1 owner of h3h_3, agent 3 append 3
2 1, 3 owner of h2h_2, agent 2 append 2
3 1, 3, 2 owner of h1h_1, agent 1, on the path cycle 1, 3, 2: agent 1 gets h3h_3, 3 gets h2h_2, 2 gets h1h_1
4 (empty) start again at agent 4
5 4 h1h_1 has left, so h5h_5, agent 5 append 5
6 4, 5 owner of h4h_4, agent 4, on the path cycle 4, 5: agent 4 gets h5h_5, 5 gets h4h_4

The allocation is x=(h3,h1,h2,h5,h4)x = (h_3, h_1, h_2, h_5, h_4). Agents 1, 2 and 3 get their first choices. Agents 4 and 5 both wanted h1h_1 or h4h_4, but h1h_1 went in the first cycle, so they trade with each other. A brute force check over all 120120 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 ii owns house hih_i, for i=1,…,ni = 1, \dots, n, and has a strict ranking ≻i\succ_i of the houses. A list that stops at hih_i stands for any ranking that puts the unlisted houses below hih_i; we show below that the algorithm never reads past hih_i, so the choice of these rankings does not matter. An allocation is a permutation xx, with x(i)x(i) the house of agent ii. A coalition SS weakly blocks xx if there is a permutation yy of the houses {hj:j∈S}\{h_j : j \in S\} among the agents of SS with y(i)⪰ix(i)y(i) \succeq_i x(i) for all i∈Si \in S and y(i)≻ix(i)y(i) \succ_i x(i) for some i∈Si \in S. 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 ii remains exactly when hih_i remains. The pointer graph has the remaining agents as nodes and an arc from ii to the owner of the best remaining house of ii. 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 ii, it stops at an entry at or before hih_i, and the entry is the best remaining house of ii. Proof. Each list contains hih_i, which remains while ii remains. Houses only leave, so every entry before ptr[i]\text{ptr}[i] 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. □\square

Claim 2 (path invariant). At the start of each pass of line L5, the path consists of distinct remaining agents p1,…,prp_1, \dots, p_r, and for each q<rq < r, ptr[pq]\text{ptr}[p_q] points to hpq+1h_{p_{q+1}}, which is the best remaining house of pqp_q. Proof. It holds when line L4 sets the path to one remaining agent. Line L10 appends jj after the last agent ii; by Claim 1 and line L8, hjh_j is the best remaining house of ii, and jj is not on the path. Line L9 removes a suffix j,…,ij, \dots, i and the houses of these agents only. The agents before jj on the path point to houses of agents on the path, and only the agent just before jj 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. □\square

Claim 3 (each trade is a cycle of the pointer graph). When line L9 runs, the agents j=pt,pt+1,…,pr=ij = p_t, p_{t+1}, \dots, p_r = i form a cycle of the pointer graph, and each gets the house of the next agent on the cycle. Proof. By Claim 2, each pqp_q with t≤q<rt \le q < r points to hpq+1h_{p_{q+1}}, its best remaining house, and by Claim 1 and line L8, ii points to hjh_j, its best remaining house. □\square

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 2n2n 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 xx be the result of a cycle removal with cycles C1,…,CrC_1, \dots, C_r in the order of removal, and let HkH_k be the set of houses of the agents of C1∪⋯∪CkC_1 \cup \dots \cup C_k. The houses given to CkC_k are the houses of CkC_k, so xx maps the agents of C1∪⋯∪CkC_1 \cup \dots \cup C_k onto HkH_k. Each agent ii of CkC_k gets its best house outside Hk−1H_{k-1}.

Claim 4 (xx is in the strict core). Proof. Suppose a coalition SS and a permutation yy of its houses weakly block xx. Since some agent is strictly better off, y(i)≠x(i)y(i) \ne x(i) for some i∈Si \in S. Choose such an ii in the cycle CkC_k with the smallest kk. The preferences are strict, so y(i)≻ix(i)y(i) \succ_i x(i). The house x(i)x(i) is the best house of ii outside Hk−1H_{k-1}, so y(i)∈Hk−1y(i) \in H_{k-1}. Let E=S∩(C1∪⋯∪Ck−1)E = S \cap (C_1 \cup \dots \cup C_{k-1}). By the choice of kk, y(j)=x(j)y(j) = x(j) for every j∈Ej \in E, so y(E)=x(E)y(E) = x(E). These are ∣E∣|E| houses in Hk−1H_{k-1}, and they are houses of agents of SS because yy only uses houses of SS. The houses of Hk−1H_{k-1} that belong to agents of SS are exactly the houses of EE, and there are ∣E∣|E| of them. So y(E)y(E) is the set of all houses of EE. But y(i)y(i) is a house of an agent of SS in Hk−1H_{k-1}, that is, a house of EE, and i∉Ei \notin E, so yy gives the same house to ii and to an agent of EE. This contradicts that yy is a permutation. □\square

Claim 5 (the strict core has at most the one element xx). Proof. Let zz be in the strict core. We show by induction on kk that z(i)=x(i)z(i) = x(i) for all agents of CkC_k. Assume it for C1,…,Ck−1C_1, \dots, C_{k-1}. Then zz maps the agents of C1∪⋯∪Ck−1C_1 \cup \dots \cup C_{k-1} onto Hk−1H_{k-1}, so every agent of CkC_k gets under zz a house outside Hk−1H_{k-1}. Each agent ii of CkC_k gets under xx its best house outside Hk−1H_{k-1}, so x(i)⪰iz(i)x(i) \succeq_i z(i). The allocation xx restricted to CkC_k is a permutation of the houses of CkC_k. If z(i)≠x(i)z(i) \ne x(i) for some i∈Cki \in C_k, then x(i)≻iz(i)x(i) \succ_i z(i) by strictness, and the coalition CkC_k with xx weakly blocks zz, a contradiction. So z=xz = x on CkC_k. □\square

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 S={i}S = \{i\} in Claim 4 shows that x(i)⪰ihix(i) \succeq_i h_i (individual rationality), and with Claim 1 this shows that no agent gets a house that it lists after hih_i, so cutting a list after hih_i does not change the result. Taking SS as all agents shows that xx is Pareto optimal.

Claim 6 (strategyproofness). Fix agent ii and the lists of the others. Let xx be the result when ii reports its true list, and x^\hat x the result when it reports any other list that contains hih_i. Then x(i)⪰ix^(i)x(i) \succeq_i \hat x(i). Proof. Both results can be computed by any cycle removal. Use this one: while the pointer graph has a cycle without ii, remove the cycle without ii that contains the smallest agent. The arcs of the agents other than ii, and so the cycles without ii, 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 RR in which every cycle contains ii. A functional graph has a cycle in each weakly connected part, so the pointer graph on RR is connected with one cycle, through ii, and the path of arcs from any agent of RR leads to ii. Now ii points to the owner j∈Rj \in R of its best house in RR according to its report, and the cycle is ii, then jj, then the path from jj back to ii. So ii gets its reported best house in RR. With the true list this is the truly best house in RR, and with the false list it is some house in RR. Hence x(i)⪰ix^(i)x(i) \succeq_i \hat x(i). ■\blacksquare

Cost. By termination there are at most 2n2n passes of line L5, each costing O(1)O(1) besides line L7 and the removals of line L9. Line L9 costs O(1)O(1) per removed agent, O(n)O(n) in total. By Claim 1, each pointer only moves forward inside its list, so line L7 costs O(L)O(L) in total, where LL is the total list length. The loop of line L3 costs O(n)O(n). The total time is O(n+L)O(n + L), and the extra space is O(n)O(n).

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 2n2n passes. Line L7 only moves pointers forward, so its total cost is at most LL, the total list length, and line L9 costs O(1)O(1) per removed agent. The total time is O(n+L)O(n + L), which is O(n2)O(n^2) for complete lists and linear in the input size. The extra space is O(n)O(n) 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 O(n)O(n) besides the pointer moves, and there can be nn rounds, so O(n2)O(n^2) 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 ii owns house ii), each containing the own house, and an optional start order for the walk. It returns xx with x[i]x[i] the house of agent ii. 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.

agtprefs.pyI0RawGitHub
# 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

  1. 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
  2. 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
  3. 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
  4. 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
  5. Strategy-proofness and the strict core in a market with indivisibilities, the characterization of the core rule by individual rationality, Pareto efficiency and strategyproofness
  6. 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.

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
  • a scene preset for the example