Algorithmcore
Random serial dictatorship
Also called RSD, random priority.
Runs serial dictatorship with a uniformly random order of agents. The lottery is fair, strategyproof and ex post efficient, but its exact probabilities are #P-hard to compute.
- Solves
- House allocation problem
- Time
- O(m + n^2) worst
- Space
- O(n + m) extra
- Where
- m = the number of objects; n = the number of agents
- Model
- Word RAM
- Properties
- randomizedrandomizediterative
- Evidence
- Proof sketchCode in 1 languages
- Origin
- Atila Abdulkadiroglu, Tayfun Sonmez, 1998
Random serial dictatorship solves the house allocation problem with a lottery. It draws an order of the agents uniformly at random and then runs serial dictatorship in that order: the first agent takes its favourite object, the next agent takes its favourite object that is left, and so on. Bogomolnaia and Moulin call it random priority. Every outcome is Pareto optimal, no agent can gain by a false list whatever the draw, and agents with the same list have the same chances. One draw costs time for agents and objects. The probability that a given agent gets a given object is #P-complete to compute exactly, and the lottery can be ordinally inefficient: probabilistic serial can give every agent a lottery that it prefers.
In plain words
Put the names in a hat and draw them one by one. The first name drawn chooses a room, then the second name chooses among the rooms that are left, and so on.
Before the draw, everybody has the same chance to be early, so the rule is fair in the sense that equal people are treated equally. After the draw, it is plain serial dictatorship, so nobody can gain by lying and nothing is wasted. The weakness is in the chances themselves. Two people who rank the rooms in opposite ways can sometimes both improve their chances by swapping some probability, and random serial dictatorship does not do this swap for them.
The problem
The input is agents and objects, with a strict list of acceptable objects for each agent, best first. The output is one matching drawn at random. The object of interest is the random assignment: the by matrix where is the probability that agent gets object .
The algorithm
RANDOM-SERIAL-DICTATORSHIP(lists)- 1
π ← a uniformly random order of the agents, by the Fisher-Yates shuffle - 2
for each object o do taken[o] ← false - 3
for each agent i do M[i] ← NIL - 4
for k ← 1 to n do - 5
i ← π(k) - 6
for each object o on the list of i, best first do - 7
if not taken[o] then M[i] ← o; taken[o] ← true; stop the loop of line L6 - 8
return M
Line L1 is the only random step. It uses the Fisher-Yates shuffle, so each of the orders has probability . Lines L2 to L8 are serial dictatorship.
Example
This is the example of Bogomolnaia and Moulin (2001). Agents 1 and 2 rank , and agents 3 and 4 rank . The 24 orders give 12 different matchings. The random assignment is:
| agent | ||||
|---|---|---|---|---|
| 1 | 5/12 | 1/12 | 5/12 | 1/12 |
| 2 | 5/12 | 1/12 | 5/12 | 1/12 |
| 3 | 1/12 | 5/12 | 1/12 | 5/12 |
| 4 | 1/12 | 5/12 | 1/12 | 5/12 |
To check the first entry: agents 3 and 4 take before they take . So agent 1 gets exactly when it comes before agent 2, unless agents 3 and 4 both come before agent 1, in which case they take and then . The first event has probability , and the bad case (3 and 4 first, in either order, then 1, then 2) has probability . So . Agent 1 gets only for the orders that start with 2 and 1, which is .
Now look at the 1/12 entries. Agent 1 has a chance at and agent 3 has a chance at , but each of them prefers the object of the other. If they swap these shares, and the same for and , every agent gets or . This is the probabilistic serial assignment. Each agent prefers it in the sense of stochastic dominance (defined under Properties), so random serial dictatorship is not ordinally efficient here.
Edge cases. With one agent, it takes its top object with probability 1. If three agents accept only , each gets it with probability . An agent with an empty list always gets nothing.
Correctness
Each outcome is the output of serial dictatorship for some order, so it is a matching and it is Pareto optimal. The converse also holds: every Pareto optimal matching is the output of some order (see serial dictatorship), so the support of the lottery is exactly the set of Pareto optimal matchings.
Strategyproofness holds order by order. For a fixed order, the objects taken before the turn of agent do not depend on its list, and with its true list it gets its best free object. So for every order, the true list gives an object at least as good as any false list does. Summing over the orders, for every the truth gives a probability at least as large of an object among the best. This is strategyproofness in the sense of stochastic dominance. It implies truthfulness in expectation for every utility function that agrees with the true list.
Equal treatment of equals: if agents and have the same list, swapping and in the order is a bijection of the orders that swaps their objects, so their rows of are equal. The proof file below gives the details.
Proof: Random serial dictatorship is ex post efficient, strategyproof and treats equals equallyfull
Fix agents , objects , and a strict list of acceptable objects for each agent. For an order of the agents, let be the output of lines L2 to L8 with that order. Write for the preference of agent , where every listed object is better than nothing and nothing is better than an unlisted object. Let be the probability that agent gets object .
Termination. Line L1 makes swaps. Lines L2 to L8 are serial dictatorship, which makes passes over finite lists. So the algorithm stops.
Claim 1 (the order is uniform). Line L1 returns each of the orders with probability . Proof. The Fisher-Yates shuffle picks the entry of the last position uniformly from all agents, then the entry of the position before it uniformly from the agents left, and so on. Each order comes from exactly one sequence of choices, and each sequence has probability .
So the output is for a uniform random order , and .
Claim 2 (ex post efficiency). The set of matchings that the algorithm outputs with positive probability is the set of Pareto optimal matchings. Proof. By Claim 1, the matchings with positive probability are the matchings over all orders . The proof file of serial dictatorship shows that each is Pareto optimal and that each Pareto optimal matching equals for some .
Claim 3 (strategyproofness for each order). Fix an order and an agent . Let use the true list of , and let use any other list of , with the lists of the others unchanged. Then . Proof. Let . Passes read only the lists of the agents before , so the set of taken objects at the turn of is the same in both runs. With its true list, gets its best acceptable object outside , or nothing if there is none. With the other list it gets an object outside or nothing. If that object is acceptable to , it is at most as good as the best acceptable object outside . If it is not acceptable, or nothing, then the true outcome, which is an acceptable object or nothing, is at least as good.
Strategyproofness in the sense of stochastic dominance. Let be the true list of , let be the matrix under the true list and the matrix under another list. For each , Claim 3 shows that for every order , if then . Counting orders and dividing by gives
So the true row stochastically dominates every false row. For any utility with and of an unlisted object at most 0, the expected utility is a positive combination of these partial sums (summation by parts), so truth-telling also maximizes the expected utility.
Claim 4 (equal treatment of equals). If agents and have the same list, then for every object . Proof. Let swap and , and for an order let , the order with and exchanged. The map is a bijection of the orders. In the run on , at each step the agent that picks has the same list as the agent that picks at the same step of the run on , so the same objects are taken in the same steps. Hence . Counting the orders gives .
Claim 5 (bistochastic for complete lists with ). If and every list contains every object, then each row and each column of sums to 1. Proof. In each run, when agent picks, objects are taken, so a free object is on its list. Hence every agent gets an object, and since every object is given. So and .
Cost of one draw. Line L1 costs . The proof file of serial dictatorship bounds lines L2 to L8 by : the -th agent reads at most entries of its list.
Complexity
- One draw. Line L1 costs time and random integers. Lines L2 to L8 cost , as for serial dictatorship: the -th agent reads at most entries of its list. The extra space is .
- The exact matrix. Running all orders gives in time, which is what the tests do for . No polynomial method is expected: Saban and Sethuraman (2015) proved that computing the matrix is #P-complete, and that deciding if a given agent gets a given object with positive probability is NP-complete, while the test for probability 1 is polynomial. Aziz, Brandt and Brill (2013) proved #P-completeness of the RSD probabilities in voting and assignment settings.
- Estimates. Each entry of is an average of indicator variables over random orders, so independent draws estimate all entries within with probability at least when , by the Hoeffding inequality and a union bound.
Properties
- Ex post efficient. Every outcome is Pareto optimal.
- Strategyproof in the strong sense: it is a lottery over strategyproof deterministic rules, so truth-telling is dominant after the draw, not only on average.
- Equal treatment of equals and anonymity: the result does not depend on the names of the agents.
- Not ordinally efficient. An assignment stochastically dominates for agent if, for every , gives at least as much probability of one of its best objects. In the example, the probabilistic serial matrix dominates the RSD matrix for every agent and is different from it.
- The core from random endowments. Abdulkadiroglu and Sonmez (1998) showed that if the houses are first given to the agents by a uniform random endowment and the agents then trade by top trading cycles, the lottery over matchings is the same as that of random serial dictatorship. The tests check this on all endowments for .
- Bistochastic. With and complete lists, every agent gets an object and every object is given, so the rows and the columns of sum to 1.
Variants and improvements
- Probabilistic serial. Probabilistic serial is ordinally efficient and envy-free, but it is only weakly strategyproof. Bogomolnaia and Moulin (2001) showed that, for , no rule has ordinal efficiency, strategyproofness and equal treatment of equals together, so a choice between RSD and PS is necessary.
- Large markets. Che and Kojima (2010) showed that when each object has many copies, the RSD and PS assignments get close, so the inefficiency of RSD vanishes in large markets.
- Copies. If an object has several copies, an agent takes a copy while one is left. The properties above stay true.
- Tie-breaking in school choice. In school choice with coarse priorities, one random order of the students often breaks the ties at all schools. This is the same idea, applied inside another mechanism.
- Implementing a matrix. A random assignment matrix of another rule can be turned into a lottery over matchings by the Birkhoff-von Neumann decomposition. RSD does not need this step, since it draws the matching directly.
When to use it
Use it when no priority is accepted as fair and strategyproofness must hold without any doubt: university housing, course seats, public housing and the allocation of slots by a public lottery. It is easy to explain and to audit, since the order can be drawn in public. If the efficiency of the probabilities matters more, and the agents are many or not strategic, consider probabilistic serial.
Pitfalls
- Computing the matrix by formula. A program that must report each agent's probabilities exactly faces a #P-complete problem. Sample, or enumerate the orders for small .
- A biased order. Shuffles that sort by random keys with ties, or that swap with a uniform position in the whole array at every step, do not give uniform orders. Use the Fisher-Yates shuffle as in line L1.
- Believing ex post efficiency is enough. Each outcome is Pareto optimal, but the lottery as a whole can be dominated, as the example shows.
- Equal chances are not equal results. The rule is fair before the draw only. After the draw, the first agent still gets its top choice and the last may get nothing, so the draw must be seen as fair by the agents, for example done in public.
Implementations
The Python version has three functions. random_serial_dictatorship draws one matching from a given random.Random. rsd_lottery and rsd_probabilities enumerate all orders and return the exact lottery and the exact matrix in Fraction. The tests check the example matrix, that the support is exactly the set of Pareto optimal matchings found by brute force, strategyproofness in the sense of stochastic dominance against every possible list (truncations included) for 3 agents and 3 objects, equal treatment, the equality with the core from random endowments, and the sampler frequencies with a fixed seed.
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))
random_serial_dictatorship.py 82 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/random-serial-dictatorship/. The authors are listed in prov/K05SWB.jsonl.
import random
from fractions import Fraction
from itertools import permutations
from typing import Optional, Sequence
def _check(prefs: Sequence[Sequence[int]], m: Optional[int]) -> int:
if m is None:
m = 1 + max((o for lst in prefs for o in lst), default=-1)
for lst in prefs:
if len(set(lst)) != len(lst) or any(not 0 <= o < m for o in lst):
raise ValueError("a preference list repeats an object or is out of range")
return m
def _dictatorship(prefs: Sequence[Sequence[int]], order: Sequence[int], m: int) -> list[int]:
"""One run of serial dictatorship in the given order (lines L2 to L8)."""
taken = [False] * m # @line L2
match = [-1] * len(prefs) # @line L3
for k in range(len(order)): # @line L4
i = order[k] # @line L5
for o in prefs[i]: # @line L6
if not taken[o]: # @line L7
match[i] = o
taken[o] = True
break
return match # @line L8
def random_serial_dictatorship(
prefs: Sequence[Sequence[int]], rng: random.Random, m: Optional[int] = None
) -> list[int]:
"""Random serial dictatorship: serial dictatorship in a uniformly random order.
prefs[i] lists the objects acceptable to agent i, best first; the objects are
0, ..., m - 1. rng is the source of randomness (random.Random with a fixed seed in the
tests). Returns the object of each agent, or -1 for no object.
O(m + n^2) time and O(n + m) space, plus n - 1 random draws for the order.
"""
m = _check(prefs, m)
order = list(range(len(prefs)))
for k in range(len(order) - 1, 0, -1): # @line L1
j = rng.randint(0, k) # Fisher-Yates: order is uniform over all n! orders
order[k], order[j] = order[j], order[k]
return _dictatorship(prefs, order, m)
def rsd_lottery(prefs: Sequence[Sequence[int]], m: Optional[int] = None) -> dict:
"""The exact lottery of random serial dictatorship over matchings.
Returns a dict from each matching (a tuple of objects, -1 for none) to its
probability as a Fraction. It runs serial dictatorship on all n! orders, so it is for
small n only: O(n! (m + n^2)) time.
"""
m = _check(prefs, m)
n = len(prefs)
count: dict = {}
total = 0
for order in permutations(range(n)):
mu = tuple(_dictatorship(prefs, order, m))
count[mu] = count.get(mu, 0) + 1
total += 1
return {mu: Fraction(c, total) for mu, c in count.items()}
def rsd_probabilities(prefs: Sequence[Sequence[int]], m: Optional[int] = None) -> list[list[Fraction]]:
"""The exact random assignment of random serial dictatorship.
Returns the n by m matrix P with P[i][o] the probability that agent i gets object o,
as Fractions. Row i sums to 1 minus the probability that i gets nothing.
O(n! (m + n^2) + n m) time; small n only.
"""
m = _check(prefs, m)
P = [[Fraction(0)] * m for _ in prefs]
for mu, p in rsd_lottery(prefs, m).items():
for i, o in enumerate(mu):
if o >= 0:
P[i][o] += p
return P
test_random_serial_dictatorship.py 186 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/random-serial-dictatorship/. The authors are listed in prov/K05SWB.jsonl.
import random
import unittest
from fractions import Fraction
from itertools import permutations
from agtprefs import all_profiles, random_profile
from random_serial_dictatorship import random_serial_dictatorship, rsd_lottery, rsd_probabilities
def rank_of(lst, o):
"""Position of object o in the list; len(lst) for -1 (no object)."""
return len(lst) if o == -1 else lst.index(o)
def all_matchings(prefs):
"""Every matching: each agent gets an acceptable object or -1, no object twice."""
out = []
def rec(i, used, cur):
if i == len(prefs):
out.append(tuple(cur))
return
for o in [-1] + [o for o in prefs[i] if o not in used]:
rec(i + 1, used | ({o} if o >= 0 else set()), cur + [o])
rec(0, frozenset(), [])
return out
def dominates(prefs, a, b):
"""True if matching a is at least as good as b for all agents and better for one."""
ra = [rank_of(lst, a[i]) for i, lst in enumerate(prefs)]
rb = [rank_of(lst, b[i]) for i, lst in enumerate(prefs)]
return all(x <= y for x, y in zip(ra, rb)) and ra != rb
def pareto_optimal_set(prefs):
ms = all_matchings(prefs)
return {a for a in ms if not any(dominates(prefs, b, a) for b in ms)}
def sd_weakly_better(true_list, p, q):
"""True if row p gives at least as much probability as row q to each top set of the true list."""
sp = sq = Fraction(0)
for o in true_list:
sp += p[o]
sq += q[o]
if sp < sq:
return False
return True
def ttc(prefs, endowment):
"""Top trading cycles with complete lists; agent i owns object endowment[i]."""
owner = {o: i for i, o in enumerate(endowment)}
left = set(range(len(prefs)))
match = [-1] * len(prefs)
while left:
point = {i: owner[next(o for o in prefs[i] if owner[o] in left)] for i in left}
i = next(iter(left))
seen = []
while i not in seen:
seen.append(i)
i = point[i]
cycle = seen[seen.index(i):]
for j in cycle:
match[j] = endowment[point[j]]
left -= set(cycle)
return tuple(match)
def ordered_subsets(m):
"""Every strict list over a subset of 0, ..., m - 1: all possible reports."""
out = []
for k in range(m + 1):
for s in permutations(range(m), k):
out.append(list(s))
return out
BM = [[0, 1, 2, 3], [0, 1, 2, 3], [1, 0, 3, 2], [1, 0, 3, 2]] # a > b > c > d and b > a > d > c
class TestRandomSerialDictatorship(unittest.TestCase):
def test_page_example(self):
F = Fraction
P = rsd_probabilities(BM)
self.assertEqual(P[0], [F(5, 12), F(1, 12), F(5, 12), F(1, 12)])
self.assertEqual(P[1], P[0])
self.assertEqual(P[2], [F(1, 12), F(5, 12), F(1, 12), F(5, 12)])
self.assertEqual(P[3], P[2])
lottery = rsd_lottery(BM)
self.assertEqual(len(lottery), 12)
self.assertEqual(lottery[(0, 2, 1, 3)], F(1, 6))
self.assertEqual(lottery[(0, 1, 2, 3)], F(1, 24))
# Probabilistic serial gives a, c half and half to agents 1 and 2, and b, d to 3 and 4.
# Its rows dominate the RSD rows for every agent, strictly for all, so RSD is not
# ordinally efficient here.
half = F(1, 2)
Q = [[half, 0, half, 0], [half, 0, half, 0], [0, half, 0, half], [0, half, 0, half]]
for i in range(4):
self.assertTrue(sd_weakly_better(BM[i], Q[i], P[i]))
self.assertNotEqual(Q[i], P[i])
def test_edge_cases(self):
rng = random.Random(1)
self.assertEqual(random_serial_dictatorship([], rng), [])
self.assertEqual(rsd_probabilities([[0]]), [[Fraction(1)]])
self.assertEqual(rsd_probabilities([[], [0]]), [[Fraction(0)], [Fraction(1)]])
three = rsd_probabilities([[0], [0], [0]])
self.assertEqual([row[0] for row in three], [Fraction(1, 3)] * 3)
with self.assertRaises(ValueError):
rsd_probabilities([[0, 0]])
with self.assertRaises(ValueError):
random_serial_dictatorship([[2]], rng, m=2)
def test_ex_post_efficient(self):
rng = random.Random(7)
for _ in range(150):
n, m = rng.randint(1, 4), rng.randint(1, 4)
prefs = [rng.sample(range(m), rng.randint(0, m)) for _ in range(n)]
lottery = rsd_lottery(prefs, m)
self.assertEqual(sum(lottery.values()), 1)
# every order gives a Pareto optimal matching, and every Pareto optimal
# matching has positive probability
self.assertEqual(set(lottery), pareto_optimal_set(prefs))
def test_equal_treatment_and_bistochastic(self):
rng = random.Random(11)
for _ in range(100):
n = rng.randint(2, 5)
kinds = [rng.sample(range(n), n) for _ in range(2)]
prefs = [kinds[rng.randint(0, 1)] for _ in range(n)]
P = rsd_probabilities(prefs, n)
for i in range(n):
self.assertEqual(sum(P[i]), 1)
for j in range(n):
if prefs[i] == prefs[j]:
self.assertEqual(P[i], P[j])
for o in range(n):
self.assertEqual(sum(P[i][o] for i in range(n)), 1)
def test_strategyproof_exhaustive(self):
reports = ordered_subsets(3)
for profile in all_profiles(3, 3):
prefs = [list(r) for r in profile]
P = rsd_probabilities(prefs, 3)
for i in range(3):
for lie in reports:
Q = rsd_probabilities(prefs[:i] + [lie] + prefs[i + 1:], 3)
self.assertTrue(sd_weakly_better(prefs[i], P[i], Q[i]), (prefs, i, lie))
def test_core_from_random_endowments(self):
# Abdulkadiroglu and Sonmez (1998): TTC from a uniform random endowment gives the
# same lottery over matchings as random serial dictatorship.
rng = random.Random(5)
for n in (2, 3, 4):
for _ in range(15):
prefs = [list(r) for r in random_profile(rng, n, n)]
core = {}
for e in permutations(range(n)):
mu = ttc(prefs, e)
core[mu] = core.get(mu, 0) + Fraction(1, len(list(permutations(range(n)))))
self.assertEqual(core, rsd_lottery(prefs, n))
def test_sampler(self):
rng = random.Random(2024)
draws = 12000
count = [[0] * 4 for _ in range(4)]
po = pareto_optimal_set(BM)
for _ in range(draws):
mu = random_serial_dictatorship(BM, rng)
self.assertIn(tuple(mu), po)
for i, o in enumerate(mu):
count[i][o] += 1
P = rsd_probabilities(BM)
for i in range(4):
for o in range(4):
self.assertLess(abs(count[i][o] / draws - float(P[i][o])), 0.02)
if __name__ == "__main__":
unittest.main()
History
Lotteries over a priority order are an old way to allocate housing and other goods. Abdulkadiroglu and Sonmez (1998) gave the rule its name in the matching literature and proved that it coincides with the core from random endowments. Bogomolnaia and Moulin (2001) called it random priority, showed by the example above that it is not ordinally efficient, and proposed probabilistic serial in its place. Che and Kojima (2010) showed that the two rules agree in large markets. Aziz, Brandt and Brill (2013) and Saban and Sethuraman (2015) proved that the exact probabilities are #P-complete to compute.
References
- Atila Abdulkadiroglu and Tayfun Sonmez, Random serial dictatorship and the core from random endowments in house allocation problems, Econometrica 66(3) (1998), the main theorem (random serial dictatorship equals the core from random endowments)
- Anna Bogomolnaia and Herve Moulin, A new solution to the random assignment problem, Journal of Economic Theory 100(2), 295 to 328 (2001), the random priority mechanism and the example where it is not ordinally efficient
- Daniela Saban and Jay Sethuraman, The complexity of computing the random priority allocation matrix, Mathematics of Operations Research 40(4), 1005 to 1014 (2015), the #P-completeness of the allocation matrix and the NP-completeness of the positive probability test
- Haris Aziz, Felix Brandt and Markus Brill, The computational complexity of random serial dictatorship, Economics Letters 121(3), 341 to 345 (2013), the #P-completeness of the RSD probabilities
- Yeon-Koo Che and Fuhito Kojima, Asymptotic equivalence of probabilistic serial and random priority mechanisms, Econometrica 78(5), 1625 to 1672 (2010), the main theorem (the two assignments converge as the number of copies grows)
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 K05SWB Edit this page History Report an error Markdown