Algorithm Search⌘K

Algorithmintro

Serial dictatorship

Also called priority mechanism.

Agents pick their favourite remaining object in a fixed order. The result is Pareto optimal, no agent gains by lying, and every Pareto optimal matching comes from some order.

Time
O(m + n^2) worst
Space
O(m) extra
Where
m = the number of objects; n = the number of agents
Properties
deterministiciterative
Origin
Atila Abdulkadiroglu, Tayfun Sonmez, Lars Gunnar Svensson, 1998

Serial dictatorship solves the house allocation problem by a fixed order of the agents: the first agent takes its favourite object, the second takes its favourite among the objects that are left, and so on. Each agent in turn is a dictator over what remains. The result is a Pareto optimal matching, and no agent can get a better object by reporting a false list, so truth-telling is a dominant strategy. It runs in O(m+n2)O(m + n^2) time for nn agents and mm objects. The rule is not fair: the first agent always gets its first choice. The fair version draws the order at random, which is random serial dictatorship.

In plain words

The people line up. The first person takes the room they like best. The second person takes the best room that is still free, and so on to the end of the line. A person who finds no acceptable room free gets nothing.

Nobody can do better by lying, because your turn and the rooms left at your turn do not depend on what you say. The answer is never wasteful: to make someone happier you would have to take a room from a person earlier in the line, who would then be unhappier. But the line decides everything, so the first person in line has a large advantage.

The problem

The input is nn agents and mm objects. Agent ii has a strict list of the objects it accepts, best first, and it prefers any listed object to nothing. An order π\pi of the agents is also given. The output is a matching: each agent gets at most one acceptable object, and no object goes to two agents.

The algorithm

  1. SERIAL-DICTATORSHIP(lists, π)
  2. 1for each object o do taken[o] ← false
  3. 2for each agent i do M[i] ← NIL
  4. 3for k ← 1 to n do
  5. 4i ← π(k)
  6. 5for each object o on the list of i, best first do
  7. 6if not taken[o] then M[i] ← o; taken[o] ← true; stop the loop of line L5
  8. 7return M

Line L5 scans the list of agent ii from the top and line L6 stops at the first free object. An agent whose list runs out stays unmatched. Nothing else in the algorithm depends on the list of agent ii, which is the key to its incentive property.

Example

This is the example of Bogomolnaia and Moulin (2001). Agents 1 and 2 rank a≻b≻c≻da \succ b \succ c \succ d, and agents 3 and 4 rank b≻a≻d≻cb \succ a \succ d \succ c. With the order 1, 2, 3, 4:

step agent free objects before the step list takes
1 1 a,b,c,da, b, c, d a,b,c,da, b, c, d aa
2 2 b,c,db, c, d a,b,c,da, b, c, d bb (after skipping aa)
3 3 c,dc, d b,a,d,cb, a, d, c dd (after skipping bb and aa)
4 4 cc b,a,d,cb, a, d, c cc (after skipping three)

The matching gives a,b,d,ca, b, d, c to agents 1 to 4. Agent 4 reads 4 entries, the most possible for the fourth agent. With the order 1, 3, 2, 4 the result is a,c,b,da, c, b, d, and with the order 4, 3, 1, 2 it is c,d,a,bc, d, a, b. Over all 4!=244! = 24 orders, serial dictatorship gives 12 different matchings, and a brute force check over all 209 matchings of this instance shows that these 12 are exactly the Pareto optimal ones.

Edge cases. With no agents the result is empty. An agent with an empty list gets nothing. If three agents accept only aa, the first of them in the order gets it and the others get nothing.

Correctness

The output is a matching, because line L6 gives an agent only a free object and marks it taken. It is Pareto optimal: if a matching M′M' were at least as good as MM for everybody and better for someone, take the first agent ii in the order with M′(i)≠M(i)M'(i) \ne M(i). With strict lists, M′(i)M'(i) is an object that ii ranks above M(i)M(i), and it was not free at the turn of ii, so an earlier agent jj holds it in MM. But M′(j)=M(j)M'(j) = M(j) by the choice of ii, so M′M' gives the object to both ii and jj, which is impossible.

It is strategyproof: the objects taken before the turn of ii depend only on the lists of earlier agents, and with its true list agent ii gets its best free object. A false list can only give a free object that ii likes less, or nothing.

Every Pareto optimal matching MM is the output for some order. In any such MM, some agent gets its first choice among all objects: otherwise each agent points to the holder of an object it prefers, and either some agent points to an unassigned object, or the pointers contain a cycle along which the agents can trade, and in both cases MM is not Pareto optimal. Put that agent first, remove it and its object, and repeat on the rest, where MM stays Pareto optimal. The full proofs are in the proof file below.

Proof: Serial dictatorship is Pareto optimal, strategyproof and reaches every Pareto optimal matchingfull

Fix agents 1,…,n1, \dots, n, objects OO, and for each agent ii a strict list of its acceptable objects. Write x≻iyx \succ_i y if ii prefers xx to yy; every acceptable object is preferred to nothing (∅\emptyset), and nothing is preferred to every object that ii does not list. Let π\pi be the order, and let TkT_k be the set of objects with taken=true\text{taken} = \text{true} at the start of the kk-th pass of line L3.

Termination. The loop of line L3 makes nn passes, and each scan of line L5 reads a finite list. So the algorithm stops.

Claim 1 (each agent gets its best free object). Let i=π(k)i = \pi(k). After the pass, M[i]M[i] is the object of the list of ii that ii ranks highest among those not in TkT_k, or NIL if every object of the list is in TkT_k. Also Tk+1=Tk∪{M[i]}T_{k+1} = T_k \cup \{M[i]\} when M[i]≠M[i] \ne NIL, and Tk+1=TkT_{k+1} = T_k otherwise. Proof. Line L5 reads the list best first, and line L6 stops at the first object not in TkT_k and marks only that one. □\square

The output is a matching. By Claim 1 each agent gets at most one object, from its list, and an object leaves the free set when it is given, so no object is given twice.

Pareto optimality. Suppose a matching M′M' satisfies M′(j)⪰jM(j)M'(j) \succeq_j M(j) for all jj and M′(j)≻jM(j)M'(j) \succ_j M(j) for some jj. Then M′≠MM' \ne M. Let kk be the smallest index with M′(π(k))≠M(π(k))M'(\pi(k)) \ne M(\pi(k)) and i=π(k)i = \pi(k). The lists are strict, so M′(i)≻iM(i)M'(i) \succ_i M(i); in particular M′(i)M'(i) is an acceptable object oo. If o∉Tko \notin T_k, Claim 1 says that ii gets oo or an object it ranks higher, which contradicts o≻iM(i)o \succ_i M(i). So o∈Tko \in T_k, and by Claim 1 some agent j=π(l)j = \pi(l) with l<kl < k has M(j)=oM(j) = o. By the choice of kk, M′(j)=M(j)=o=M′(i)M'(j) = M(j) = o = M'(i) with j≠ij \ne i, so M′M' is not a matching. This contradiction proves that MM is Pareto optimal.

Strategyproofness. Let i=π(k)i = \pi(k) report any list in place of its true one, and let M^\hat M be the result. The passes 1,…,k−11, \dots, k - 1 read only the lists of the agents π(1),…,π(k−1)\pi(1), \dots, \pi(k-1), so TkT_k is the same in both runs. With the false list, M^(i)\hat M(i) is an object outside TkT_k or nothing. If it is an object that ii truly finds acceptable, Claim 1 for the true run says M(i)⪰iM^(i)M(i) \succeq_i \hat M(i). If it is nothing or an object that ii does not accept, then M(i)⪰i∅≻iM^(i)M(i) \succeq_i \emptyset \succ_i \hat M(i) or M(i)⪰iM^(i)=∅M(i) \succeq_i \hat M(i) = \emptyset. So no false list gives ii a better result.

Claim 2 (some agent has its top choice). Let MM be a Pareto optimal matching for a set RR of agents and a set FF of objects, where each agent of RR accepts only the objects of its list that lie in FF and gets one of them or nothing. Then some agent i∈Ri \in R has M(i)M(i) equal to its best acceptable object in FF, or has M(i)=∅M(i) = \emptyset and accepts no object of FF. Proof. Suppose not. Then each i∈Ri \in R has an object t(i)∈Ft(i) \in F that it accepts and prefers to M(i)M(i). If some t(i)t(i) is assigned to nobody in MM, giving t(i)t(i) to ii (and freeing M(i)M(i)) makes ii better off and nobody worse off, a contradiction. Otherwise each t(i)t(i) is M(j)M(j) for a unique agent j=s(i)∈Rj = s(i) \in R, with j≠ij \ne i because ii prefers t(i)t(i) to M(i)M(i). The map ss on the finite set RR has a cycle i1,…,iri_1, \dots, i_r with s(iq)=iq+1s(i_q) = i_{q+1} and s(ir)=i1s(i_r) = i_1. Give each iqi_q the object t(iq)t(i_q). The objects t(iq)=M(iq+1)t(i_q) = M(i_{q+1}) are distinct and were held by the cycle itself, so this is a matching, it makes every agent of the cycle better off, and nobody else changes. This contradicts Pareto optimality. □\square

Every Pareto optimal matching is reached. Let MM be a Pareto optimal matching of the whole instance. Build the order step by step. Suppose π(1),…,π(k−1)\pi(1), \dots, \pi(k-1) are chosen, let RR be the other agents, and let FF be OO minus the objects M(π(1)),…,M(π(k−1))M(\pi(1)), \dots, M(\pi(k-1)). The restriction of MM to RR uses only objects of FF, and it is Pareto optimal for RR and FF: a matching of RR into FF that dominates it would, together with the objects of the chosen agents, dominate MM. By Claim 2, some i∈Ri \in R has M(i)M(i) equal to its best acceptable object in FF, or nothing if it accepts no object of FF. Let π(k)=i\pi(k) = i.

Run serial dictatorship with this order. By induction on kk, after kk passes every agent π(l)\pi(l) with l≤kl \le k has M(π(l))M(\pi(l)), and Tk+1T_{k+1} is the set of these objects. The step: at the start of pass kk the free objects are exactly FF, and by Claim 1 agent π(k)\pi(k) gets its best acceptable object of FF, or nothing, which is M(π(k))M(\pi(k)) by the choice of π(k)\pi(k). So the output is MM. ■\blacksquare

Cost. By Claim 1, ∣Tk∣≤k−1|T_k| \le k - 1. The scan of line L5 for agent π(k)\pi(k) reads objects of TkT_k until it meets a free one or the list ends, so it reads at most ∣Tk∣+1≤k|T_k| + 1 \le k entries. Summing over kk gives at most n(n+1)/2n(n+1)/2 entries; lines L1 and L2 cost O(m+n)O(m + n). The total is O(m+n2)O(m + n^2).

Complexity

The model is the word RAM; objects are indices, and a test of taken[o]\text{taken}[o] costs O(1)O(1).

  • Initialization. Lines L1 and L2 cost O(m+n)O(m + n).
  • Scans. Before the turn of the kk-th agent, exactly the objects of the earlier agents are taken, at most k−1k - 1 of them. So line L5 reads at most kk entries of the list before it stops or the list ends. The total over all agents is at most 1+2+⋯+n=n(n+1)/21 + 2 + \dots + n = n(n + 1)/2.
  • Total. O(m+n2)O(m + n^2) time and O(m)O(m) extra space for the array taken\text{taken}, besides the input and output. When n≤mn \le m and the lists are complete, the input has nmnm entries, so the algorithm does not even read all of it.

Properties

  • Pareto optimal, and every Pareto optimal matching arises from some order (Abdulkadiroglu and Sonmez 1998; the proof below also covers incomplete lists).
  • Strategyproof. Truth-telling is a dominant strategy for every agent.
  • Nonbossy and neutral. An agent cannot change the objects of others without changing its own, and renaming the objects renames the result. Svensson (1999) proved that a deterministic rule with these two properties and strategyproofness is a serial dictatorship.
  • Not fair. Two agents with the same list get very different objects, depending only on the order.
  • Not of maximum size. A Pareto optimal matching can be about half as large as a largest one. If agent 1 accepts aa and bb and agent 2 accepts only aa, the order 1, 2 gives one pair and the order 2, 1 gives two.

Variants and improvements

  • Random order. Random serial dictatorship draws the order uniformly at random. It treats equal agents equally and stays strategyproof.
  • Ties. With indifference, an agent cannot just take one object of its top tie class, because the choice inside the tie class can hurt agents later in the order. The fix keeps the choice open: each agent in turn only promises to take one of its best objects that can still be given to it together with the promises of earlier agents, and a bipartite matching at the end fixes the objects. Manlove (2013, Section 6.2.2) treats this case.
  • Copies. If an object has several copies, an agent takes a copy while one is left; the analysis is the same.
  • Owners. When agents own the objects at the start, an order of the agents would violate individual rationality. Top trading cycles is the right rule then.
  • Size. To get a largest Pareto optimal matching, Abraham, Cechlarova, Manlove and Mehlhorn (2004) start from a maximum matching and improve it, in O(n1/2∣E∣)O(n^{1/2} |E|) time for ∣E∣|E| acceptable pairs.

When to use it

Use it when a natural priority exists and is accepted as fair: seniority for offices, the time of application for housing, or a lottery number drawn in public. It is simple to explain and to check, and no agent needs to think about strategy. When no priority is accepted, draw it at random, or use probabilistic serial if ordinal efficiency matters more than full strategyproofness.

Pitfalls

  • An order that depends on the reports. The order must be fixed before the lists are read. If, for example, agents who rank popular objects first are moved back in the line, an agent can gain a better place by a false list, and strategyproofness is lost.
  • Breaking ties arbitrarily. With indifferences, a fixed tie-break inside serial dictatorship can give a matching that is not Pareto optimal. Use the version for ties.
  • Calling it fair because it is efficient. Efficiency and strategyproofness say nothing about equal treatment; the order decides who wins.
  • Expecting a large matching. Pareto optimality does not mean that as many agents as possible get an object.

Implementations

The Python version takes the lists as lists of object indices, best first, and an optional order of the agents, and it returns the object of each agent, with −1-1 for an agent that gets nothing. The tests compare the set of outcomes over all orders with the set of Pareto optimal matchings found by brute force, and check strategyproofness over all false lists, truncated lists included.

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))
serial_dictatorship.py 41 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/serial-dictatorship/. The authors are listed in prov/RKCZD9.jsonl.

from typing import Optional, Sequence


def serial_dictatorship(
    prefs: Sequence[Sequence[int]],
    order: Optional[Sequence[int]] = None,
    m: Optional[int] = None,
) -> list[int]:
    """Serial dictatorship: the agents pick in turn their best object that is still free.

    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.
    order is a permutation of the agents 0, ..., n - 1, the first to pick first; by
    default it is 0, 1, ..., n - 1. Returns the object of each agent, or -1 for an agent
    that finds no acceptable object free when its turn comes.
    O(m + n^2) time and O(n + m) space: the k-th agent to pick reads at most k entries
    of its list, because at most k - 1 objects are taken before its turn.
    """
    n = len(prefs)
    if m is None:
        m = 1 + max((o for lst in prefs for o in lst), default=-1)
    if order is None:
        order = range(n)
    if sorted(order) != list(range(n)):
        raise ValueError("order must be a permutation of the agents")
    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")
    taken = [False] * m  # @line L1
    match = [-1] * n  # @line L2
    for k in range(n):  # @line L3
        i = order[k]  # @line L4
        for o in prefs[i]:  # @line L5
            if not taken[o]:  # @line L6
                match[i] = o
                taken[o] = True
                break
    return match  # @line L7
test_serial_dictatorship.py 137 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/serial-dictatorship/. The authors are listed in prov/RKCZD9.jsonl.

import random
import unittest
from itertools import permutations

from agtprefs import all_rankings, all_profiles, random_profile
from serial_dictatorship import serial_dictatorship


def rank_of(lst, o):
    """Position of object o in the list, len(lst) for -1 (no object), None if unacceptable."""
    if o == -1:
        return len(lst)
    return lst.index(o) if o in lst else None


def all_matchings(prefs, m):
    """Every matching: each agent gets an acceptable object or -1, no object twice."""
    n = len(prefs)
    out = []

    def rec(i, used, cur):
        if i == n:
            out.append(tuple(cur))
            return
        cur.append(-1)
        rec(i + 1, used, cur)
        cur.pop()
        for o in prefs[i]:
            if o not in used:
                used.add(o)
                cur.append(o)
                rec(i + 1, used, cur)
                cur.pop()
                used.discard(o)

    rec(0, set(), [])
    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."""
    better = False
    for i, lst in enumerate(prefs):
        ra, rb = rank_of(lst, a[i]), rank_of(lst, b[i])
        if ra > rb:
            return False
        if ra < rb:
            better = True
    return better


def pareto_optimal_set(prefs, m):
    ms = all_matchings(prefs, m)
    return {a for a in ms if not any(dominates(prefs, b, a) for b in ms)}


def random_lists(rng, n, m):
    """Random incomplete strict lists: each agent ranks a random subset of the objects."""
    return [rng.sample(range(m), rng.randint(0, m)) for _ in range(n)]


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 TestSerialDictatorship(unittest.TestCase):
    def test_page_example(self):
        self.assertEqual(serial_dictatorship(BM), [0, 1, 3, 2])
        self.assertEqual(serial_dictatorship(BM, [0, 2, 1, 3]), [0, 2, 1, 3])
        self.assertEqual(serial_dictatorship(BM, [2, 3, 0, 1]), [2, 3, 1, 0])
        outcomes = {tuple(serial_dictatorship(BM, o)) for o in permutations(range(4))}
        self.assertEqual(len(outcomes), 12)
        self.assertEqual(outcomes, pareto_optimal_set(BM, 4))

    def test_edge_cases(self):
        self.assertEqual(serial_dictatorship([]), [])
        self.assertEqual(serial_dictatorship([[], [0]]), [-1, 0])
        self.assertEqual(serial_dictatorship([[0], [0], [0]], [2, 0, 1]), [-1, -1, 0])
        self.assertEqual(serial_dictatorship([[1, 0], [1]], m=3), [1, -1])
        self.assertEqual(serial_dictatorship([[1, 0], [1]], [1, 0], m=3), [0, 1])
        with self.assertRaises(ValueError):
            serial_dictatorship([[0, 0]])
        with self.assertRaises(ValueError):
            serial_dictatorship([[0], [1]], [0, 0])

    def test_pareto_optimal_and_every_po_matching_is_reached(self):
        rng = random.Random(11)
        for _ in range(300):
            n, m = rng.randint(1, 4), rng.randint(1, 4)
            prefs = random_lists(rng, n, m)
            po = pareto_optimal_set(prefs, m)
            reached = {tuple(serial_dictatorship(prefs, o, m)) for o in permutations(range(n))}
            self.assertEqual(reached, po)

    def test_strategyproof_exhaustive_three_agents(self):
        for P in all_profiles(3, 3):
            prefs = [list(r) for r in P]
            for order in ([0, 1, 2], [2, 0, 1]):
                truth = serial_dictatorship(prefs, order)
                for i in range(3):
                    for lie in all_rankings(3):
                        q = prefs[:i] + [list(lie)] + prefs[i + 1:]
                        got = serial_dictatorship(q, order)[i]
                        self.assertGreaterEqual(rank_of(prefs[i], got), rank_of(prefs[i], truth[i]))

    def test_strategyproof_random_four_agents_with_truncation(self):
        rng = random.Random(5)
        lies = [list(r[:k]) for r in all_rankings(4) for k in range(5)]
        for _ in range(200):
            prefs = [list(r) for r in random_profile(rng, 4, 4)]
            order = rng.sample(range(4), 4)
            truth = serial_dictatorship(prefs, order)
            i = rng.randrange(4)
            for lie in lies:
                q = prefs[:i] + [lie] + prefs[i + 1:]
                got = serial_dictatorship(q, order, 4)[i]
                self.assertGreaterEqual(rank_of(prefs[i], got), rank_of(prefs[i], truth[i]))

    def test_first_agent_gets_top_and_reads_bound(self):
        rng = random.Random(8)
        for _ in range(200):
            n, m = rng.randint(1, 6), rng.randint(1, 6)
            prefs = random_lists(rng, n, m)
            order = rng.sample(range(n), n)
            match = serial_dictatorship(prefs, order, m)
            taken = set()
            for i in order:
                free = [o for o in prefs[i] if o not in taken]
                self.assertEqual(match[i], free[0] if free else -1)
                if free:
                    taken.add(free[0])


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

History

Allocation by a priority order, for example by seniority or by the date of application, is an old practice. In the matching literature, Abdulkadiroglu and Sonmez (1998) showed that the Pareto optimal matchings are exactly the outcomes of serial dictatorships, and that a random order gives the same lottery as the core from random endowments. Svensson (1999) characterized serial dictatorship as the only strategyproof, nonbossy and neutral rule. Abraham, Cechlarova, Manlove and Mehlhorn (2004) studied the sizes of Pareto optimal matchings with incomplete lists, and Manlove (2013) gives the algorithmic account.

References

  1. David F. Manlove, Algorithmics of Matching Under Preferences, World Scientific (2013), Chapter 6, Pareto optimal matchings, Section 6.2 (house allocation)
  2. Atila Abdulkadiroglu and Tayfun Sonmez, Random serial dictatorship and the core from random endowments in house allocation problems, Econometrica 66(3) (1998), the lemma that every Pareto efficient matching is the outcome of a serial dictatorship
  3. Lars-Gunnar Svensson, Strategy-proof allocation of indivisible goods, Social Choice and Welfare 16, 557 to 567 (1999), the main theorem (strategyproof, nonbossy and neutral rules are serial dictatorships)
  4. David J. Abraham, Katarina Cechlarova, David F. Manlove and Kurt Mehlhorn, Pareto optimality in house allocation problems, ISAAC 2004, LNCS 3341, 3 to 15, Pareto optimal matchings with incomplete lists and their sizes

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