Algorithmcore
Probabilistic serial
Also called eating algorithm, Bogomolnaia-Moulin mechanism.
Agents eat their favourite remaining objects at equal speed, and the amounts eaten are the assignment probabilities. It is ordinally efficient and envy-free but not strategyproof.
- Solves
- House allocation problem
- Time
- O(m (n + m)) worst
- Space
- O(n m) extra
- Where
- m = the number of objects; n = the number of agents
- Model
- Word RAM
- Properties
- deterministicexactiterative
- Evidence
- Proof sketchCode in 1 languages
- Origin
- Anna Bogomolnaia, Herve Moulin, 2001
Probabilistic serial solves the house allocation problem with a random assignment instead of a single matching. Think of each object as one unit of a divisible good, the probability of getting it. All agents start at time 0 and eat at the same speed. Each agent eats from its favourite object that is not used up, and moves to the next one on its list when that object runs out. At time 1 the amount of object that agent has eaten is the probability that gets . Bogomolnaia and Moulin (2001) proved that the result is ordinally efficient and envy-free in the sense of stochastic dominance, which random serial dictatorship is not. The price is incentives: an agent can sometimes gain in expected utility by a false list. With exact rational arithmetic the algorithm takes time for agents and objects.
In plain words
Imagine each room as a cake. A bell rings, and everybody starts to eat from the cake of the room they like most, all at the same speed. When a cake is finished, the people who were eating it move to the best cake that is still there. After one unit of time the bell rings again. The share of a cake you ate is your chance to get that room.
Nobody envies another person's plate, because at every moment you were eating the best cake left. And no trade of chances can make everybody happier. The catch is that a person can sometimes gain by pretending to like a contested room less and eating an uncontested one first.
The problem
The input is agents and objects, each agent with a strict list of the objects it accepts, best first. The output is a random assignment: an by matrix with row sums at most 1 and column sums at most 1, where is the probability that agent gets object , and if does not accept . When and the lists are complete, is bistochastic, and the Birkhoff-von Neumann decomposition turns it into a lottery over matchings.
For agent , a row stochastically dominates a row if, for every , gives at least as much probability as to the set of the best objects of . The assignment is ordinally efficient if no other random assignment gives every agent a row that dominates its row in , and a different row to at least one agent.
The algorithm
PROBABILISTIC-SERIAL(lists)- 1
for each object o do left[o] ← 1 - 2
for each agent i and object o do P[i][o] ← 0 - 3
t ← 0 - 4
while t < 1 do - 5
for each agent i do top[i] ← the first object on the list of i with left > 0, or NIL - 6
if every top[i] is NIL then stop the loop of line L4 - 7
for each object o do eaters[o] ← the number of agents i with top[i] = o - 8
δ ← min(1 - t, min of left[o] / eaters[o] over the objects o with eaters[o] > 0) - 9
for each agent i with top[i] ≠ NIL do P[i][top[i]] ← P[i][top[i]] + δ; left[top[i]] ← left[top[i]] - δ - 10
t ← t + δ - 11
return P
The algorithm jumps from event to event. Between two events no agent changes its object, so each object shrinks at rate eaters[o], and line L8 finds the time until the first object runs out or the clock reaches 1. All numbers are rationals, and the implementation computes them exactly.
Example
Agent 1 ranks , agent 2 ranks , and agent 3 ranks .
| interval | agent 1 eats | agent 2 eats | agent 3 eats | event at the end |
|---|---|---|---|---|
| is used up: two eaters, each | ||||
| is used up: was left, two eaters | ||||
| is used up and |
The result is
| agent | |||
|---|---|---|---|
| 1 | 1/2 | 1/4 | 1/4 |
| 2 | 1/2 | 0 | 1/2 |
| 3 | 0 | 3/4 | 1/4 |
Agent 3 eats for the whole interval and after that. Agent 1 does not envy agent 3: under the list of agent 1, its own row gives to against , to against , and to everything against .
In the example of Bogomolnaia and Moulin, where agents 1 and 2 rank and agents 3 and 4 rank , probabilistic serial gives agents 1 and 2 half of and half of , and agents 3 and 4 half of and half of . Random serial dictatorship gives agent 1 the row , which is dominated.
A manipulation. Let agents 1 and 2 rank and agent 3 rank . With the truth, agent 1 gets for . If agent 1 reports , it eats together with agent 3 first and gets . With utilities , and , the lie raises its expected utility from about to . The false row does not dominate the true one (it gives less probability to ), which is the weak form of strategyproofness that probabilistic serial has.
Edge cases. If three agents accept only , each gets of it. With more objects than agents, eating stops at time 1, and objects can stay partly uneaten. An agent whose list runs out stops eating, and its row sums to less than 1.
Correctness
The output is a random assignment: each object starts with one unit and line L8 never lets left[o] go below 0, so the column sums are at most 1; each agent eats for at most one unit of time, so the row sums are at most 1. Agents eat only acceptable objects.
Envy-freeness. Fix agents and and the set of the best objects of . While some object of is left, agent eats from . So until the last object of is used up, at time , agent eats from at speed 1 and agent eats from it at speed at most 1, and after nobody eats from . Hence has at least as much of as , for every .
Ordinal efficiency. Suppose an assignment gives every agent a row that dominates its row in . Go through the objects in the order in which they are used up. The agents who eat an object at the moment it runs out have eaten only objects they like at least as much as , and all of these are used up by then, so their whole eating time went into this top set. Domination forces each of them to get at least as much of in as in , given that and agree on the objects used up earlier. Since gives out all of , must agree with on . At the end, the same argument for the objects still left at time 1 shows . The proof file below gives the details. Bogomolnaia and Moulin also characterize ordinal efficiency by the absence of a cycle in a relation on the objects.
Weak strategyproofness. No false list gives a row that dominates the true row unless the two rows give the same probability to each top set. Bogomolnaia and Moulin also proved that, for , no rule has ordinal efficiency, strategyproofness in the sense of stochastic dominance and equal treatment of equals together, so the gap cannot be closed.
Proof: Probabilistic serial returns an envy-free and ordinally efficient random assignmentfull
Fix agents , objects with , and a strict list of acceptable objects for each agent. A random assignment is a matrix with row and column sums at most 1 and when does not accept . For a set of objects write . A top set of agent is the set of its best objects for some . Row dominates row for agent if for every top set of .
Number the passes of the loop of line L4 as , let be the value of at the start of pass and the step of line L8, so that pass covers the interval . Read the algorithm as a process in continuous time: during this interval agent eats top[i] at speed 1.
Claim 1 (tops only move down). If agent eats object in pass and object in a later pass, then , and was used up at the end of some pass between them. Once top[i] is NIL it stays NIL. Proof. left[o] never increases, so an object with left stays used up. In line L5, top[i] is the best object of with left ; the set of such objects only shrinks, so the best of them can only get worse, and it changes only when the old one is used up.
Claim 2 (each pass but the last uses up an object). If , then some object with eaters[o] has , and after line L9 left[o] . Also left[o] always. Proof. Line L9 lowers left[o] by eaters[o] left[o]. If , the minimum in line L8 is reached at some , where the decrease equals left[o].
Termination. By Claim 2, every pass with uses up an object that was not used up before, so there are at most such passes. A pass with sets and ends the loop. Line L6 also ends the loop. So there are at most passes.
The output is a random assignment. Line L9 adds to only when = top[i], an acceptable object. Column sums to by Claim 2. Row sums to the total time that eats, at most .
Envy-freeness. Fix agents and a top set of . Let be the end of the last pass in which some object of has left at its start (or if there is none). Before , some object of is not used up, so top[i] is in (by Claim 1 and the definition of top), and eats from at speed 1. Agent eats at speed at most 1. After , every object of is used up and nobody eats from . So . As was any top set, the row of dominates the row of for agent . In particular, two agents with the same list get the same row.
Ordinal efficiency. Let be a random assignment such that for every agent , dominates for . We prove .
Let be the distinct times at which some object is used up, let be the set of objects used up at time , and , with and . Between and no object is used up, so by Claim 1 every agent eats one fixed object during this interval, or nothing.
Induction claim: for every agent and every . It holds for . Assume it for and take .
- Let be the set of agents with . If for some agent , then ate at some time, and by Claim 1 it moves away from only when is used up, at . So . Hence , because is used up.
- Take and let be the top set of that ends with . Every object that prefers to was used up before started on , so it lies in . Agent has eaten without a break from time 0 to (by Claim 1, a NIL top stays NIL), and only objects of , and nobody eats from after . So , and by domination. Since and agree on , we get .
- So . All inequalities are equalities: for , and for .
This proves the induction claim for , so and agree on , the set of all used-up objects.
Now take an agent . Both and are zero outside the objects that accepts. If every object that accepts is in , then by the induction claim. Otherwise some acceptable object is never used up. Then top[i] is never NIL, so eats at every moment, the loop does not stop at line L6, and it stops with . Let be the object that eats in the last pass and the top set of that ends with . Every object that prefers to was used up before started on , so . Agent ate only objects of , for a total time of 1, so and is zero outside . Domination gives ; as the row sum of is at most 1, and is zero outside . Since on , also . So . This holds for every agent, so , and no other assignment dominates : it is ordinally efficient.
Weak strategyproofness (that no false list gives a row that dominates the true row with a strict gain) is proved by Bogomolnaia and Moulin (2001); it is not reproved here, and the tests check it exhaustively for 3 agents and 3 objects.
Cost. By the termination argument there are at most passes. Lines L7 to L10 cost per pass. For line L5, each agent keeps a pointer into its list. By Claim 1 the pointer only moves forward, so all pointer moves together cost at most the total list length, . The total is arithmetic operations.
Complexity
The model is the word RAM with exact rational arithmetic; each event involves fractions whose sizes grow with the number of events.
- Events. Each pass of the loop of line L4 except the last uses up at least one object, the one that gives the minimum in line L8. So there are at most passes.
- Work per pass. Lines L7 to L10 cost . For line L5, each agent keeps a pointer into its list that only moves forward, because a used-up object never comes back. The pointer moves cost in total over all passes.
- Total. arithmetic operations, and space for the matrix. The output itself has entries.
Properties
- Ordinally efficient, so also ex post efficient: the matrix can be written as a lottery over Pareto optimal matchings.
- Envy-free in the sense of stochastic dominance, which implies equal treatment of equals.
- Weakly strategyproof but not strategyproof: a false list never gives a dominating row, but it can raise the expected utility, as the manipulation above shows.
- Every ordinally efficient assignment is an eating outcome. Bogomolnaia and Moulin showed that, with complete lists and , the ordinally efficient assignments are exactly the outcomes of simultaneous eating algorithms with some eating speeds that may vary over time. Probabilistic serial is the case of equal constant speeds.
- Large markets. Che and Kojima (2010) showed that, as each object gets more and more copies, the probabilistic serial and random serial dictatorship assignments converge to each other.
Variants and improvements
- Ties. Katta and Sethuraman (2006) extended the rule to preferences with indifferences. The eating step then becomes a sequence of parametric flow problems, because an agent indifferent between several objects may eat from any of them.
- Copies and quotas. If object has copies, start with left[o] . In school choice, a student eats seats at its preferred schools.
- Unequal speeds. Eating at speed gives a weighted version, with envy-freeness replaced by a weighted condition.
- Implementing the lottery. For with complete lists, the Birkhoff-von Neumann decomposition writes as a convex combination of at most permutation matrices, and drawing one of them gives a matching with the right marginals.
- Cardinal utilities. With utilities instead of lists, the Hylland-Zeckhauser mechanism gives an ex ante efficient assignment by prices, at a much higher computational cost.
When to use it
Use it when objects are assigned by lottery, ordinal efficiency and fairness matter, and the agents have little room or skill for strategy: course seats, school places, tasks among workers, or the assignment of offices. In small markets with strategic agents, random serial dictatorship is safer because it is fully strategyproof. In large markets the two rules give almost the same result.
Pitfalls
- Floating point. Event times are differences and quotients of earlier ones. Floats can leave a tiny positive amount of an object that should be used up, and then an agent eats a crumb of it in an extra event. Use exact fractions, or compare with a tolerance and round at the end.
- Recomputing top choices from the start of each list. Without pointers, line L5 costs per pass and the total becomes .
- Reporting the matrix as the result. The agents get objects, not probabilities. A lottery that implements the matrix is needed, and for incomplete lists or the decomposition works on a sub-bistochastic matrix padded with dummy agents or objects.
- Selling it as strategyproof. It is not. Agents with good information about others can gain by misreporting in small markets.
Implementations
The Python version takes the lists as lists of object indices, best first, and returns the matrix of Fractions. The tests check the two examples above, the manipulation, and on random instances (complete and incomplete lists) the row and column sums, envy-freeness in the sense of stochastic dominance, and ordinal efficiency by an exact linear program with agtlp: maximize the total of the top-set probabilities over all assignments that dominate the result, and check that the maximum equals the value of the result. The same program shows that the random serial dictatorship matrix of the Bogomolnaia and Moulin example is dominated. An exhaustive test over all profiles and all false lists (truncations included) for 3 agents and 3 objects checks weak strategyproofness.
Each implementation follows the pseudocode above. A comment @line links a line of code to a line of the pseudocode. Point at a line of the pseudocode to see the matching code. The build runs the native tests of each language.
# SPDX-License-Identifier: MIT
# Shared helper of the algorithmic game theory pages of https://algorithm.tamnd.com/. The authors are listed in prov/.
"""Exact linear programming in Fraction, by the two-phase simplex method with Bland's rule.
lp_max(c, A_ub, b_ub, A_eq=None, b_eq=None) maximizes c x subject to A_ub x <= b_ub,
A_eq x = b_eq and x >= 0. lp_min does the same for minimization. Free variables must be
split by the caller (x = x+ - x-). Every input number is converted to Fraction, so the
result is exact: there is no tolerance anywhere.
Both functions return (status, x, value, dual). status is "optimal", "infeasible" or
"unbounded". When status is not "optimal", x, value and dual are None. dual has one entry
per constraint, the A_ub rows first and then the A_eq rows. It is the vector of shadow
prices: the value is sum_i b_i dual_i (strong duality). For lp_max, dual_i >= 0 on the
A_ub rows and A^T dual >= c. For lp_min, dual_i <= 0 on the A_ub rows and A^T dual <= c.
The entries for the A_eq rows have no sign condition.
Bland's rule (the smallest improving column enters, and among the rows with the smallest
ratio the one with the smallest basic variable leaves) makes the method finite on every
input, degenerate inputs included. There is no game algorithm in this module.
"""
from fractions import Fraction
def _frac(v):
return v if isinstance(v, Fraction) else Fraction(v)
def _pivot(T, obj, basis, r, j):
p = T[r][j]
row = [v / p for v in T[r]]
T[r] = row
for k in range(len(T)):
f = T[k][j]
if k != r and f != 0:
T[k] = [a - f * b for a, b in zip(T[k], row)]
f = obj[j]
if f != 0:
obj[:] = [a - f * b for a, b in zip(obj, row)]
basis[r] = j
def _simplex(T, obj, basis, ncols):
"""Maximize. obj[j] is the reduced cost of column j and obj[-1] is minus the value."""
while True:
enter = next((j for j in range(ncols) if obj[j] > 0), None)
if enter is None:
return "optimal"
best = None
for r, row in enumerate(T):
a = row[enter]
if a > 0:
key = (row[-1] / a, basis[r])
if best is None or key < best[0]:
best = (key, r)
if best is None:
return "unbounded"
_pivot(T, obj, basis, best[1], enter)
def _objective_row(cost, T, basis):
obj = list(cost) + [Fraction(0)]
for r, j in enumerate(basis):
f = obj[j]
if f != 0:
obj = [a - f * b for a, b in zip(obj, T[r])]
return obj
def _any_solution(M, rhs, nvars):
"""Return one solution y of M y = rhs (a consistent system), with the free variables 0."""
rows = [list(M[k]) + [rhs[k]] for k in range(len(M))]
pivots = []
r = 0
for col in range(nvars):
p = next((k for k in range(r, len(rows)) if rows[k][col] != 0), None)
if p is None:
continue
rows[r], rows[p] = rows[p], rows[r]
pv = rows[r][col]
rows[r] = [v / pv for v in rows[r]]
for k in range(len(rows)):
f = rows[k][col]
if k != r and f != 0:
rows[k] = [a - f * b for a, b in zip(rows[k], rows[r])]
pivots.append(col)
r += 1
if r == len(rows):
break
y = [Fraction(0)] * nvars
for k, col in enumerate(pivots):
y[col] = rows[k][-1]
return y
def _matrix(A, width, name):
A = [[_frac(v) for v in row] for row in (A or [])]
if any(len(row) != width for row in A):
raise ValueError(name + " must have one column per variable")
return A
def lp_max(c, A_ub, b_ub, A_eq=None, b_eq=None):
"""Maximize c x subject to A_ub x <= b_ub, A_eq x = b_eq and x >= 0, exactly."""
c = [_frac(v) for v in c]
n = len(c)
A_ub = _matrix(A_ub, n, "A_ub")
A_eq = _matrix(A_eq, n, "A_eq")
b_ub = [_frac(v) for v in (b_ub or [])]
b_eq = [_frac(v) for v in (b_eq or [])]
if len(b_ub) != len(A_ub) or len(b_eq) != len(A_eq):
raise ValueError("b_ub and b_eq must have one entry per row")
m1, m2 = len(A_ub), len(A_eq)
m = m1 + m2
width = n + m1
# Rows in the original orientation, with a slack column for each A_ub row.
orig = [A_ub[i] + [Fraction(int(k == i)) for k in range(m1)] for i in range(m1)]
orig += [A_eq[i] + [Fraction(0)] * m1 for i in range(m2)]
rhs = b_ub + b_eq
# A row gets an artificial variable if it is an equation or if its right side is negative.
need = [i >= m1 or rhs[i] < 0 for i in range(m)]
nart = sum(need)
T, basis = [], []
a = 0
for i in range(m):
sign = -1 if rhs[i] < 0 else 1
row = [sign * v for v in orig[i]] + [Fraction(0)] * nart + [sign * rhs[i]]
if need[i]:
row[width + a] = Fraction(1)
basis.append(width + a)
a += 1
else:
basis.append(n + i)
T.append(row)
if nart:
# Phase 1: maximize minus the sum of the artificial variables.
obj = _objective_row([Fraction(0)] * width + [Fraction(-1)] * nart, T, basis)
_simplex(T, obj, basis, width + nart)
if obj[-1] != 0:
return "infeasible", None, None, None
keep = []
for r in range(m):
if basis[r] >= width:
j = next((j for j in range(width) if T[r][j] != 0), None)
if j is None:
continue # the row is a combination of the other rows
_pivot(T, [Fraction(0)] * (width + nart + 1), basis, r, j)
keep.append(r)
T = [T[r][:width] + [T[r][-1]] for r in keep]
basis = [basis[r] for r in keep]
# Phase 2: the original objective, without the artificial columns.
cost = c + [Fraction(0)] * m1
obj = _objective_row(cost, T, basis)
if _simplex(T, obj, basis, width) == "unbounded":
return "unbounded", None, None, None
x = [Fraction(0)] * n
for r, j in enumerate(basis):
if j < n:
x[j] = T[r][-1]
value = sum((ci * xi for ci, xi in zip(c, x)), Fraction(0))
# The dual solves y^T A_B = c_B, where A_B holds the basic columns of the original rows.
M = [[orig[i][j] for i in range(m)] for j in basis]
dual = _any_solution(M, [cost[j] for j in basis], m)
return "optimal", x, value, dual
def lp_min(c, A_ub, b_ub, A_eq=None, b_eq=None):
"""Minimize c x subject to A_ub x <= b_ub, A_eq x = b_eq and x >= 0, exactly."""
status, x, value, dual = lp_max([-_frac(v) for v in c], A_ub, b_ub, A_eq, b_eq)
if status != "optimal":
return status, None, None, None
return status, x, -value, [-v for v in dual]
agtprefs.py 279 lines
# 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))
probabilistic_serial.py 56 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/probabilistic-serial/. The authors are listed in prov/VY2D6A.jsonl.
from fractions import Fraction
from typing import Optional, Sequence
def probabilistic_serial(
prefs: Sequence[Sequence[int]], m: Optional[int] = None
) -> list[list[Fraction]]:
"""Probabilistic serial (the eating algorithm) of Bogomolnaia and Moulin.
prefs[i] lists the objects acceptable to agent i, best first, without repeats; the
objects are 0, ..., m - 1 (by default m is one more than the largest listed object).
Each object is one unit of probability. All agents eat at speed 1 from time 0 to time 1,
each from its best acceptable object that is not used up. Returns the n by m matrix P
of Fractions, where P[i][o] is the amount of o that agent i ate: the probability that
i gets o.
The loop runs once per event: at each event an object is used up or the time reaches 1,
so there are at most m + 1 rounds of O(n + m) work, plus O(total list length) for the
pointers. That is O(m (n + m) + n m) = O(m (n + m)) time, and O(n m) space for P.
"""
n = len(prefs)
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")
left = [Fraction(1)] * m # @line L1
P = [[Fraction(0)] * m for _ in range(n)] # @line L2
t = Fraction(0) # @line L3
ptr = [0] * n # position of the current object in each list; it only moves forward
while t < 1: # @line L4
top = []
for i in range(n): # @line L5
lst = prefs[i]
while ptr[i] < len(lst) and left[lst[ptr[i]]] == 0:
ptr[i] += 1
top.append(lst[ptr[i]] if ptr[i] < len(lst) else -1)
if all(o == -1 for o in top): # @line L6
break
eaters = [0] * m # @line L7
for o in top:
if o != -1:
eaters[o] += 1
delta = 1 - t # @line L8
for o in range(m):
if eaters[o] > 0:
delta = min(delta, left[o] / eaters[o])
for i in range(n): # @line L9
o = top[i]
if o != -1:
P[i][o] += delta
left[o] -= delta
t += delta # @line L10
return P # @line L11
test_probabilistic_serial.py 147 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/probabilistic-serial/. The authors are listed in prov/VY2D6A.jsonl.
import random
import unittest
from fractions import Fraction
from itertools import permutations
from agtlp import lp_max
from agtprefs import all_profiles, random_profile
from probabilistic_serial import probabilistic_serial
F = Fraction
def cumulative(lst, row):
"""Partial sums of row along the list lst: the chance of one of the k best objects."""
out, s = [], Fraction(0)
for o in lst:
s += row[o]
out.append(s)
return out
def sd_weakly_better(lst, p, q):
return all(x >= y for x, y in zip(cumulative(lst, p), cumulative(lst, q)))
def ordinally_efficient(prefs, P, m):
"""True if no sub-bistochastic Q on the acceptable pairs stochastically dominates P.
LP: maximize the sum over agents i and k of the chance under Q of the k best objects
of i, subject to row and column sums at most 1 and each such chance at least the one
under P. P is feasible, and P is dominated exactly when the optimum is larger than the
value of P.
"""
n = len(prefs)
pairs = [(i, o) for i in range(n) for o in prefs[i]]
col = {p: k for k, p in enumerate(pairs)}
c = [0] * len(pairs)
A, b = [], []
for i in range(n):
lst = prefs[i]
for pos, o in enumerate(lst):
c[col[(i, o)]] += len(lst) - pos # o counts in the top-k sets for k > pos
cum = cumulative(lst, P[i])
for k in range(len(lst)):
row = [0] * len(pairs)
for o in lst[: k + 1]:
row[col[(i, o)]] = -1
A.append(row)
b.append(-cum[k])
A.append([1 if p[0] == i else 0 for p in pairs])
b.append(1)
for o in range(m):
A.append([1 if p[1] == o else 0 for p in pairs])
b.append(1)
status, x, value, dual = lp_max(c, A, b)
assert status == "optimal"
own = sum(sum(cumulative(prefs[i], P[i])) for i in range(n))
return value == own
def ordered_subsets(m):
return [list(s) for k in range(m + 1) for s in permutations(range(m), k)]
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
RSD_BM = [[F(5, 12), F(1, 12), F(5, 12), F(1, 12)]] * 2 + [[F(1, 12), F(5, 12), F(1, 12), F(5, 12)]] * 2
class TestProbabilisticSerial(unittest.TestCase):
def test_page_examples(self):
half = F(1, 2)
self.assertEqual(
probabilistic_serial(BM),
[[half, 0, half, 0], [half, 0, half, 0], [0, half, 0, half], [0, half, 0, half]],
)
P = probabilistic_serial([[0, 1, 2], [0, 2, 1], [1, 0, 2]])
self.assertEqual(P, [[F(1, 2), F(1, 4), F(1, 4)], [F(1, 2), 0, F(1, 2)], [0, F(3, 4), F(1, 4)]])
# the RSD matrix of the Bogomolnaia-Moulin example is not ordinally efficient
self.assertTrue(ordinally_efficient(BM, probabilistic_serial(BM), 4))
self.assertFalse(ordinally_efficient(BM, RSD_BM, 4))
def test_manipulation_example(self):
prefs = [[0, 1, 2], [0, 1, 2], [1, 2, 0]]
truth = probabilistic_serial(prefs)[0]
lie = probabilistic_serial([[1, 0, 2]] + prefs[1:])[0]
self.assertEqual(truth, [F(1, 2), F(1, 6), F(1, 3)])
self.assertEqual(lie, [F(1, 4), F(1, 2), F(1, 4)])
u = [F(3), F(29, 10), F(0)] # a utility that agrees with a > b > c
self.assertGreater(sum(x * y for x, y in zip(u, lie)), sum(x * y for x, y in zip(u, truth)))
self.assertFalse(sd_weakly_better(prefs[0], truth, lie))
self.assertFalse(sd_weakly_better(prefs[0], lie, truth))
def test_edge_cases(self):
self.assertEqual(probabilistic_serial([]), [])
self.assertEqual(probabilistic_serial([[]], m=2), [[0, 0]])
self.assertEqual(probabilistic_serial([[1, 0]]), [[0, 1]])
self.assertEqual(probabilistic_serial([[0], [0], [0]]), [[F(1, 3)]] * 3)
# more objects than agents: eating stops at time 1
self.assertEqual(probabilistic_serial([[0, 1], [0, 1]], m=3), [[F(1, 2), F(1, 2), 0]] * 2)
with self.assertRaises(ValueError):
probabilistic_serial([[0, 0]])
def test_properties_random(self):
rng = random.Random(3)
for trial in range(60):
n, m = rng.randint(1, 4), rng.randint(1, 4)
if trial % 2:
prefs = [rng.sample(range(m), rng.randint(0, m)) for _ in range(n)]
else:
m = n
prefs = [list(r) for r in random_profile(rng, n, n)]
P = probabilistic_serial(prefs, m)
for i in range(n):
self.assertTrue(all(P[i][o] == 0 for o in range(m) if o not in prefs[i]))
self.assertLessEqual(sum(P[i]), 1)
for j in range(n): # envy-free in the sense of stochastic dominance
self.assertTrue(sd_weakly_better(prefs[i], P[i], P[j]))
for o in range(m):
self.assertLessEqual(sum(P[i][o] for i in range(n)), 1)
if all(len(lst) == m for lst in prefs) and n == m:
self.assertTrue(all(sum(row) == 1 for row in P))
self.assertTrue(all(sum(P[i][o] for i in range(n)) == 1 for o in range(m)))
self.assertTrue(ordinally_efficient(prefs, P, m))
def test_weakly_strategyproof_exhaustive(self):
# Bogomolnaia and Moulin: no report gives a row that stochastically dominates the
# true row. Full strategyproofness fails, as the manipulation example shows.
reports = ordered_subsets(3)
gains = 0
for profile in all_profiles(3, 3):
prefs = [list(r) for r in profile]
P = probabilistic_serial(prefs, 3)
for i in range(3):
for lie in reports:
Q = probabilistic_serial(prefs[:i] + [lie] + prefs[i + 1:], 3)
if sd_weakly_better(prefs[i], Q[i], P[i]):
self.assertEqual(cumulative(prefs[i], Q[i]), cumulative(prefs[i], P[i]))
if not sd_weakly_better(prefs[i], P[i], Q[i]):
gains += 1
self.assertGreater(gains, 0)
if __name__ == "__main__":
unittest.main()
History
Bogomolnaia and Moulin (2001) introduced ordinal efficiency, showed with their four-agent example that random priority (random serial dictatorship) is not ordinally efficient, and defined the probabilistic serial mechanism with its family of simultaneous eating algorithms. Katta and Sethuraman (2006) extended it to the full preference domain with ties. Che and Kojima (2010) proved that it and random priority become equivalent in large markets, which explains why the simpler random priority works well in practice.
References
- Anna Bogomolnaia and Herve Moulin, A new solution to the random assignment problem, Journal of Economic Theory 100(2), 295 to 328 (2001), the definitions of ordinal efficiency and of the simultaneous eating algorithms, the probabilistic serial mechanism and the impossibility result
- Akshay-Kumar Katta and Jay Sethuraman, A solution to the random assignment problem on the full preference domain, Journal of Economic Theory 131(1), 231 to 250 (2006), the extension of probabilistic serial to preferences with ties
- 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)
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 VY2D6A Edit this page History Report an error Markdown