Algorithm Search⌘K

Algorithmcore

Boston mechanism

Also called immediate acceptance mechanism.

Each round, every unassigned student applies to her next school and schools accept by priority for good. Pareto efficient for the reported lists, but not strategyproof and not stable.

Time
O(n m log n) worst
Space
O(n m) extra
Where
m = the number of schools; n = the number of students
Properties
deterministiciterative
Origin
Atila Abdulkadiroglu, Tayfun Sonmez, 2003

The Boston mechanism assigns students to schools in rounds: in round kk every student who has no seat yet applies to the kk-th school on her list, and each school takes applicants by priority up to the seats it has left, and keeps them for good. It is one algorithm for the school choice problem, which defines the input and the goals. It differs from student-proposing deferred acceptance in one point: deferred acceptance holds applicants only tentatively, so a later applicant with higher priority can take the seat, while the Boston mechanism accepts immediately. That one change makes the outcome Pareto efficient for the reported lists, but it destroys strategyproofness and stability.

In plain words

Every student writes a ranked list of schools. In the first round, each school looks only at the students who put it first and fills its seats with the best of them by its priority order. Those students are done. In the second round, the students who are left apply to their second choice, and schools that still have seats fill them the same way. This goes on until every list is used up. The trouble is that a seat at a popular school is lost if you do not rank it first. So a student who expects to lose at her favorite school does better to rank a safer school first, and honest families can lose out to families that play this game.

The problem

There are nn students and mm schools. School ss has qs≥0q_s \ge 0 seats and a strict priority order ≻s\succ_s over all students. Each student ii reports a strict list PiP_i of the schools she finds acceptable, best first; the list may be shorter than mm. An assignment gives each student at most one school on her list and gives school ss at most qsq_s students. The full problem, with the properties a district may want (stability, efficiency and strategyproofness), is on school choice problem.

The algorithm

  1. BOSTON(lists P, priorities, capacities q)
  2. 1left[s] ← q_s for each school s; U ← the set of all students
  3. 2for k ← 1 to m do
  4. 3for each school s do A_s ← the students i ∈ U with s at place k of P_i
  5. 4for each school s with A_s nonempty do
  6. 5T ← the min(left[s], |A_s|) students of A_s with the highest priority at s
  7. 6assign every student of T to s for good; U ← U \ T; left[s] ← left[s] - |T|
  8. 7return the assignment (the students still in U get no school)

Line L3 collects the applications of round kk. A student whose list is shorter than kk does not apply. Lines L5 and L6 are the immediate acceptance: an accepted student never loses her seat, and a rejected student never comes back to that school. A school whose seats are gone after a round rejects every later applicant, whatever her priority.

Example

Three students i1,i2,i3i_1, i_2, i_3 and three schools s1,s2,s3s_1, s_2, s_3 with one seat each. The lists and priorities are:

student list school priority
i1i_1 s2,s1,s3s_2, s_1, s_3 s1s_1 i1,i3,i2i_1, i_3, i_2
i2i_2 s3,s2,s1s_3, s_2, s_1 s2s_2 i3,i2,i1i_3, i_2, i_1
i3i_3 s3,s2,s1s_3, s_2, s_1 s3s_3 i1,i2,i3i_1, i_2, i_3
round applications accepted seats left after the round
1 i1→s2i_1 \to s_2; i2,i3→s3i_2, i_3 \to s_3 i1i_1 at s2s_2; i2i_2 at s3s_3 (higher priority than i3i_3) s1s_1: 1, s2s_2: 0, s3s_3: 0
2 i3→s2i_3 \to s_2 nobody, s2s_2 is full s1s_1: 1
3 i3→s1i_3 \to s_1 i3i_3 at s1s_1 none

The outcome is i1→s2i_1 \to s_2, i2→s3i_2 \to s_3, i3→s1i_3 \to s_1. Student i3i_3 gets her last choice.

The outcome is not stable. Student i3i_3 prefers s2s_2 to s1s_1, and s2s_2 gives i3i_3 higher priority than i1i_1, who holds the seat. This is justified envy. Student-proposing deferred acceptance on the same lists gives i1→s1i_1 \to s_1, i2→s3i_2 \to s_3, i3→s2i_3 \to s_2, which is stable.

The mechanism is not strategyproof. Suppose i3i_3 reports s2,s3,s1s_2, s_3, s_1 instead. In round 1, i1i_1 and i3i_3 both apply to s2s_2, and s2s_2 takes i3i_3, who has higher priority. Student i2i_2 gets s3s_3. In round 2, i1i_1 applies to s1s_1 and gets it. Now i3i_3 has s2s_2, her second true choice, instead of s1s_1, her third. The lie gains her one place. The tests in impl/python check this example, the trace above and the manipulation.

Correctness

The full proofs are in proofs/correctness.md. The main claims are these.

  • Feasibility. Each student gets at most one school, which is on her list, and no school takes more than qsq_s students. Line L5 never takes more than the seats left.
  • Pareto efficiency for the reported lists. No other assignment makes some student better off, by her reported list, and no student worse off. The proof is an induction on the rounds: a student accepted in round kk was rejected in rounds 1,…,k−11, \ldots, k-1 by schools that were full of students accepted in earlier rounds, and these students cannot be moved without hurting them.
  • Most first choices. The number of students who get their reported first choice is the maximum over all assignments. Round 1 gives school ss exactly min⁡(qs,fs)\min(q_s, f_s) students, where fsf_s is the number of students who list ss first, and no assignment can give more.
  • Deferred acceptance in disguise. Change the priority of school ss so that students who list ss at place 11 come first, then those who list it at place 22, and so on, with ties broken by ≻s\succ_s. Student-proposing deferred acceptance with these adjusted priorities gives exactly the Boston outcome. The tests use this as the reference method on random instances.

The efficiency is only for the reported lists. When students misreport, the outcome can be inefficient for their true preferences, and in the example above the truthful outcome leaves justified envy.

Proof: The Boston mechanism is feasible, Pareto efficient for the reported lists, and equal to deferred acceptance with adjusted prioritiesfull

Fix an input: students II with ∣I∣=n|I| = n, schools SS with ∣S∣=m|S| = m, capacities qs≥0q_s \ge 0, strict priorities ≻s\succ_s over II, and reported strict lists PiP_i without repeats, each of length at most mm. Write pli(s)\text{pl}_i(s) for the place of ss on PiP_i (1 for the top) and set pli(none)=∞\text{pl}_i(\text{none}) = \infty; student ii prefers ss to tt when pli(s)<pli(t)\text{pl}_i(s) < \text{pl}_i(t). Let aa be the output of BOSTON, and say that student ii is accepted in round kk when line L6 assigns her in the pass of line L2 with that kk.

Termination. The loop of line L2 makes exactly mm passes, and each pass touches finitely many students and schools. So the algorithm stops.

Claim 1 (feasibility). Every student gets at most one school, that school is on her list, and school ss gets at most qsq_s students. Proof. Line L6 removes each accepted student from UU, and line L3 only looks at students in UU, so a student is accepted at most once. A student in AsA_s has ss on her list. The invariant left[s]=qs−∣{i:a(i)=s so far}∣≥0\text{left}[s] = q_s - |\{i : a(i) = s \text{ so far}\}| \ge 0 holds after line L1 and is kept by lines L5 and L6, because ∣T∣≤left[s]|T| \le \text{left}[s]. □\square

Claim 2 (full after a rejection). If student ii applies to ss in round kk and is not accepted, then at the end of round kk school ss has no seat left, and every student assigned to ss was accepted in a round j≤kj \le k. Proof. Line L5 takes min⁡(left[s],∣As∣)\min(\text{left}[s], |A_s|) students. If ii is not among them, then ∣As∣>left[s]|A_s| > \text{left}[s] and the minimum is left[s]\text{left}[s], so after line L6 left[s]=0\text{left}[s] = 0. Nothing is assigned to ss later, because line L5 then takes nobody. □\square

Claim 3 (Pareto efficiency for the reported lists). There is no feasible assignment bb with pli(b(i))≤pli(a(i))\text{pl}_i(b(i)) \le \text{pl}_i(a(i)) for all ii and strict inequality for some ii. Proof. Let bb be feasible with pli(b(i))≤pli(a(i))\text{pl}_i(b(i)) \le \text{pl}_i(a(i)) for all ii. We show b=ab = a. We prove by induction on k=1,…,mk = 1, \ldots, m that every student accepted in round kk has b(i)=a(i)b(i) = a(i).

Let ii be accepted in round kk at s=a(i)s = a(i), so ss is at place kk of PiP_i and ii was in UU in every round j<kj < k. Since pli(b(i))≤k\text{pl}_i(b(i)) \le k, b(i)b(i) is one of the first kk schools on PiP_i. Let tt be at place j<kj < k. In round jj student ii applied to tt and was not accepted, so by Claim 2 school tt is full in aa with students accepted in rounds ≤j<k\le j < k. By the induction hypothesis all of them have b=tb = t as well, so bb gives tt its qtq_t students already and has no seat for ii. So b(i)≠tb(i) \ne t, and hence b(i)=sb(i) = s.

Now let ii be unassigned in aa. She applied to every school on her list, in rounds 1,…,∣Pi∣1, \ldots, |P_i|, and was rejected each time. By Claim 2 and the induction (which now covers all rounds), every school on her list is full in bb with students other than ii, so b(i)=noneb(i) = \text{none}.

So b=ab = a, and no bb can be strictly better for some student. □\square

Claim 4 (most first choices). Let fsf_s be the number of students with ss at place 1. Every feasible assignment gives at most ∑smin⁡(qs,fs)\sum_s \min(q_s, f_s) students their first choice, and aa gives exactly that many. Proof. In any feasible assignment, the students who get their first choice ss are among the fsf_s students who list ss first and are at most qsq_s. In round 1 of BOSTON, AsA_s is exactly these fsf_s students and left[s]=qs\text{left}[s] = q_s, so line L5 accepts min⁡(qs,fs)\min(q_s, f_s) of them at ss. □\square

Claim 5 (deferred acceptance with adjusted priorities). For each school ss define the strict order ≻s′\succ'_s on II: i≻s′ji \succ'_s j if pli(s)<plj(s)\text{pl}_i(s) < \text{pl}_j(s), or pli(s)=plj(s)\text{pl}_i(s) = \text{pl}_j(s) and i≻sji \succ_s j. Then student-proposing deferred acceptance with the lists PiP_i, the priorities ≻s′\succ'_s and the capacities qsq_s outputs aa. Proof. Deferred acceptance gives the same output for every order of proposals, because its output is the student-optimal stable matching (see the proof on the Gale-Shapley page; the many-to-one case reduces to one-to-one by splitting each school into qsq_s copies with the same priority). So we may run it in rounds: in round kk, every student who is not held and has a list of length at least kk proposes to the school at place kk of her list, and each school keeps the qsq_s best proposers by ≻s′\succ'_s among those it holds and the new ones, and rejects the rest.

We prove by induction on kk: at the end of round kk of this run, the students held at each school ss are exactly the students that BOSTON has assigned to ss in rounds 1,…,k1, \ldots, k, and the students not held are exactly UU after round kk of BOSTON, each of whom has made exactly kk proposals or used up her list. For k=0k = 0 nobody is held, and UU is all students. In round kk, the new proposers to ss are the students of UU with ss at place kk, which is the set AsA_s of line L3. Each student held at ss from an earlier round j<kj < k lists ss at place j<kj < k, so she is above every new proposer in ≻s′\succ'_s, and the held students are never rejected. Among the new proposers, who all list ss at place kk, ≻s′\succ'_s agrees with ≻s\succ_s. So ss keeps its old students and takes the min⁡(left[s],∣As∣)\min(\text{left}[s], |A_s|) new proposers of highest priority ≻s\succ_s, which is the set TT of line L5. This is the step of BOSTON, and the induction goes through. After round mm every list is used up or its owner is held, so the run of deferred acceptance has ended, with the output aa. ■\blacksquare

Complexity

Line L1 and the precomputation of a rank table, so that the priority of a student at a school is found in constant time, take O(nm)O(nm) time and space. There are mm rounds. In each round, line L3 scans the unassigned students, and line L5 sorts the applicants of each school by priority, so a round costs O(nlog⁡n)O(n \log n) and the whole run O(nmlog⁡n)O(nm \log n). Each student applies at most once per round, so there are at most nmnm applications in total. With a linear-time selection of the top left[s]\text{left}[s] applicants instead of a sort, the time is O(nm)O(nm), which is the size of the input when all priorities are given.

Properties

  • Not strategyproof. Ranking a school first is the only safe way to get it, so a student can gain by ranking a less popular school first, as in the example.
  • Not stable. The outcome can leave justified envy (the example). Deferred acceptance is stable and strategyproof for students; see Gale-Shapley.
  • Equilibria are stable matchings. Ergin and Sonmez (2006) proved that, when all students know all lists and priorities (complete information) and play the Boston game, the outcomes of its Nash equilibria are exactly the stable matchings for the true preferences. So in equilibrium the Boston mechanism does at best what deferred acceptance does under truth, and the student-optimal stable matching is among the equilibrium outcomes. The tests check this claim by brute force over all 63=2166^3 = 216 report profiles of 3 students and 3 schools.
  • Sincere and sophisticated students. Pathak and Sonmez (2008) studied a mix of students who report truthfully and students who play best responses. They show that the best equilibrium outcome for the sophisticated students is the student-optimal stable matching of a changed economy, in which the sincere students lose their priority to sophisticated students at every school except their first choice.
  • Pareto efficient for the reports. See Correctness. It is not efficient for the true preferences in general.

Variants and improvements

  • Deferred acceptance. Replace the immediate acceptance in line L6 by tentative holding. This is the mechanism Boston adopted in 2005.
  • Top trading cycles for schools. Efficient and strategyproof for students, but not stable; see top trading cycles and the comparison on school choice problem.
  • Truncated lists. Many districts limit the length of the list. With a short list, even deferred acceptance stops being strategyproof, because a student must choose which schools to list.
  • Tie-breaking. Real priorities have large classes of equal priority (walk zone and siblings). A lottery breaks the ties, either one lottery for all schools or one per school; the Boston mechanism then works on the strict priorities.
  • Ex ante welfare. With cardinal preferences and equal priorities, Abdulkadiroglu, Che and Yasuda (2011) show that the Boston mechanism can give every student a higher expected utility in equilibrium than deferred acceptance, because a student can show how strongly she wants a school by ranking it first.

When to use it

Use it to model a district that uses immediate acceptance, or to measure how much honest families lose. For a new design, deferred acceptance is the usual choice when stability matters, and top trading cycles when efficiency for students matters more; both make truth telling a dominant strategy for students. The Boston mechanism is a reasonable choice only when a designer wants students to signal intensity of preference and accepts that strategic skill then matters.

Pitfalls

  • Efficiency for the reported lists is not efficiency for the true preferences. Reports under the Boston mechanism are often strategic, so welfare figures computed from reports mean little.
  • A student who is rejected in round kk does not reapply to that school later, even if seats appear. Seats never appear, because acceptance is final.
  • In the version used in practice, a student may list fewer schools than there are; a student whose list is used up stays unassigned and goes to an administrative assignment. The pseudocode returns no school for her.
  • The rule depends on the round in which a student applies, not only on her priority, so a high-priority student can lose a seat to a low-priority student. Do not describe the outcome as "assignment by priority".
  • Laboratory evidence is a measurement, not a theorem: Chen and Sonmez (2006) found a high rate of preference manipulation under the Boston mechanism in their experiments.

Implementations

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))
boston_mechanism.py 67 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/boston-mechanism/. The authors are listed in prov/GWGCR1.jsonl.
"""The Boston mechanism (immediate acceptance) for school choice.

Students are 0, ..., n - 1 and schools are 0, ..., m - 1. prefs[i] is the list of the schools
that student i reports as acceptable, best first; it may be shorter than m. priority[s] is a
ranking of all n students for school s, best first. capacity[s] is the number of seats of
school s. The result gives, for each student, the school she gets or None.
"""

from typing import Optional


def boston(
    prefs: list[tuple[int, ...]],
    priority: list[tuple[int, ...]],
    capacity: list[int],
    trace: Optional[list] = None,
) -> list[Optional[int]]:
    """Return the Boston assignment: in round k each unassigned student applies to her k-th
    choice, and each school accepts applicants by priority up to its remaining seats, for good.

    If trace is a list, the function appends, for each round k = 1, 2, ..., the dict of the
    students accepted in that round, keyed by school. O(n m + n log n) time per instance with
    the sort in line L5 done once per school and round.
    """
    n, m = len(prefs), len(capacity)
    if len(priority) != m:
        raise ValueError("one priority ranking per school")
    for s in range(m):
        if sorted(priority[s]) != list(range(n)):
            raise ValueError("a priority ranking must list every student once")
        if capacity[s] < 0:
            raise ValueError("capacities must be nonnegative")
    for lst in prefs:
        if len(set(lst)) != len(lst) or any(not 0 <= s < m for s in lst):
            raise ValueError("a preference list repeats a school or is out of range")
    rank = [[0] * n for _ in range(m)]
    for s in range(m):
        for r, i in enumerate(priority[s]):
            rank[s][i] = r
    left = list(capacity)  # @line L1
    assigned: list[Optional[int]] = [None] * n
    unassigned = set(range(n))
    for k in range(m):  # @line L2
        applicants: dict[int, list[int]] = {}
        for i in sorted(unassigned):  # @line L3
            if k < len(prefs[i]):
                applicants.setdefault(prefs[i][k], []).append(i)
        accepted_now: dict[int, list[int]] = {}
        for s, group in sorted(applicants.items()):  # @line L4
            group.sort(key=lambda i: rank[s][i])  # @line L5
            take = group[: left[s]]
            for i in take:
                assigned[i] = s
                unassigned.discard(i)
            left[s] -= len(take)  # @line L6
            if take:
                accepted_now[s] = take
        if trace is not None:
            trace.append(accepted_now)
    return assigned  # @line L7


def first_choice_count(prefs: list[tuple[int, ...]], assigned: list[Optional[int]]) -> int:
    """Return the number of students who get the first school on their reported list."""
    return sum(1 for i, s in enumerate(assigned) if s is not None and prefs[i] and prefs[i][0] == s)
test_boston_mechanism.py 178 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/boston-mechanism/. The authors are listed in prov/GWGCR1.jsonl.

import random
import unittest
from itertools import permutations, product

from agtprefs import all_rankings, random_profile
from boston_mechanism import boston, first_choice_count

# The example of the page, with students and schools indexed from 0.
PREFS = [(1, 0, 2), (2, 1, 0), (2, 1, 0)]
PRIORITY = [(0, 2, 1), (2, 1, 0), (0, 1, 2)]
CAPACITY = [1, 1, 1]


def deferred_acceptance(prefs, priority, capacity):
    """Student-proposing deferred acceptance, the reference method."""
    n, m = len(prefs), len(capacity)
    rank = [{i: r for r, i in enumerate(priority[s])} for s in range(m)]
    nxt = [0] * n
    held = [[] for _ in range(m)]
    free = list(range(n))
    while free:
        i = free.pop()
        if nxt[i] >= len(prefs[i]):
            continue
        s = prefs[i][nxt[i]]
        nxt[i] += 1
        held[s].append(i)
        held[s].sort(key=lambda x: rank[s][x])
        if len(held[s]) > capacity[s]:
            free.append(held[s].pop())
    out = [None] * n
    for s in range(m):
        for i in held[s]:
            out[i] = s
    return out


def adjusted_priority(prefs, priority, m):
    """Rank students at school s first by the place of s on their list, then by priority."""
    n = len(prefs)
    out = []
    for s in range(m):
        def key(i, s=s):
            place = prefs[i].index(s) if s in prefs[i] else m
            return (place, priority[s].index(i))
        out.append(tuple(sorted(range(n), key=key)))
    return out


def all_assignments(prefs, capacity):
    """Every feasible assignment: each student gets a school on her list or None."""
    options = [list(lst) + [None] for lst in prefs]
    for a in product(*options):
        if all(sum(1 for x in a if x == s) <= capacity[s] for s in range(len(capacity))):
            yield list(a)


def place(prefs, i, s):
    return prefs[i].index(s) if s is not None else len(prefs[i])


def is_stable(prefs, priority, capacity, a):
    n = len(prefs)
    for i in range(n):
        for s in prefs[i][: place(prefs, i, a[i])]:
            holders = [j for j in range(n) if a[j] == s]
            if len(holders) < capacity[s]:
                return False
            if any(priority[s].index(i) < priority[s].index(j) for j in holders):
                return False
    return True


def random_instance(rng, n, m):
    prefs = [tuple(r[: rng.randint(1, m)]) for r in random_profile(rng, m, n)]
    priority = list(random_profile(rng, n, m))
    capacity = [rng.randint(0, 2) for _ in range(m)]
    return prefs, priority, capacity


class TestBoston(unittest.TestCase):
    def test_page_example(self):
        trace = []
        self.assertEqual(boston(PREFS, PRIORITY, CAPACITY, trace), [1, 2, 0])
        self.assertEqual(trace, [{1: [0], 2: [1]}, {}, {0: [2]}])
        self.assertEqual(deferred_acceptance(PREFS, PRIORITY, CAPACITY), [0, 2, 1])

    def test_manipulation_on_page(self):
        lie = [PREFS[0], PREFS[1], (1, 2, 0)]
        a = boston(lie, PRIORITY, CAPACITY)
        self.assertEqual(a, [0, 2, 1])
        self.assertLess(place(PREFS, 2, a[2]), place(PREFS, 2, 0))

    def test_justified_envy_on_page(self):
        self.assertFalse(is_stable(PREFS, PRIORITY, CAPACITY, boston(PREFS, PRIORITY, CAPACITY)))

    def test_feasible(self):
        rng = random.Random(1)
        for _ in range(300):
            prefs, priority, capacity = random_instance(rng, rng.randint(1, 6), rng.randint(1, 4))
            a = boston(prefs, priority, capacity)
            for i, s in enumerate(a):
                self.assertTrue(s is None or s in prefs[i])
            for s in range(len(capacity)):
                self.assertLessEqual(sum(1 for x in a if x == s), capacity[s])

    def test_equals_da_with_adjusted_priorities(self):
        rng = random.Random(2)
        for _ in range(400):
            n, m = rng.randint(1, 7), rng.randint(1, 4)
            prefs, priority, capacity = random_instance(rng, n, m)
            adj = adjusted_priority(prefs, priority, m)
            self.assertEqual(boston(prefs, priority, capacity), deferred_acceptance(prefs, adj, capacity))

    def test_pareto_efficient_and_most_first_choices(self):
        rng = random.Random(3)
        for _ in range(150):
            n, m = rng.randint(1, 4), rng.randint(1, 3)
            prefs, priority, capacity = random_instance(rng, n, m)
            a = boston(prefs, priority, capacity)
            best_first = 0
            for b in all_assignments(prefs, capacity):
                best_first = max(best_first, first_choice_count(prefs, b))
                weakly = all(place(prefs, i, b[i]) <= place(prefs, i, a[i]) for i in range(n))
                strictly = any(place(prefs, i, b[i]) < place(prefs, i, a[i]) for i in range(n))
                self.assertFalse(weakly and strictly)
            self.assertEqual(first_choice_count(prefs, a), best_first)

    def test_not_strategyproof_search(self):
        rng = random.Random(4)
        found = 0
        for _ in range(200):
            prefs = list(random_profile(rng, 3, 3))
            priority = list(random_profile(rng, 3, 3))
            a = boston(prefs, priority, [1, 1, 1])
            for i in range(3):
                for lie in all_rankings(3):
                    b = boston(prefs[:i] + [lie] + prefs[i + 1:], priority, [1, 1, 1])
                    if place(prefs, i, b[i]) < place(prefs, i, a[i]):
                        found += 1
        self.assertGreater(found, 0)

    def test_nash_outcomes_are_the_stable_matchings(self):
        # Ergin and Sonmez 2006: with complete information, the outcomes of the Nash
        # equilibria of the Boston game are the stable matchings under the true preferences.
        rng = random.Random(6)
        strategies = all_rankings(3)
        cap = [1, 1, 1]
        for _ in range(8):
            prefs = list(random_profile(rng, 3, 3))
            priority = list(random_profile(rng, 3, 3))
            stable = {tuple(p) for p in permutations(range(3)) if is_stable(prefs, priority, cap, list(p))}
            result = {prof: boston(list(prof), priority, cap) for prof in product(strategies, repeat=3)}
            nash = set()
            for prof, a in result.items():
                if all(
                    place(prefs, i, result[prof[:i] + (d,) + prof[i + 1:]][i]) >= place(prefs, i, a[i])
                    for i in range(3)
                    for d in strategies
                ):
                    nash.add(tuple(a))
            self.assertEqual(nash, stable)
            self.assertIn(tuple(deferred_acceptance(prefs, priority, cap)), nash)

    def test_bad_input(self):
        with self.assertRaises(ValueError):
            boston([(0, 0)], [(0,)], [1])
        with self.assertRaises(ValueError):
            boston([(0,)], [(0, 0)], [1])
        with self.assertRaises(ValueError):
            boston([(1,)], [(0,)], [1])


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

History

Boston and several other US school districts used versions of this rule, which Abdulkadiroglu and Sonmez (2003) analyzed under the name Boston student assignment mechanism. They showed that it is not strategyproof and not stable, and proposed deferred acceptance and top trading cycles instead. Abdulkadiroglu, Pathak, Roth and Sonmez (2005) documented that some Boston families played the rule strategically, and in 2005 Boston Public Schools replaced it by student-proposing deferred acceptance. Ergin and Sonmez (2006) characterized its Nash equilibria under complete information. The name "immediate acceptance" contrasts it with deferred acceptance.

References

  1. Atila Abdulkadiroglu and Tayfun Sonmez, School choice, a mechanism design approach, American Economic Review 93(3), 729 to 747 (2003), the description of the Boston student assignment mechanism and its shortcomings
  2. Haluk Ergin and Tayfun Sonmez, Games of school choice under the Boston mechanism, Journal of Public Economics 90(1-2), 215 to 237 (2006), the results on the Nash equilibria of the Boston game under complete information
  3. Atila Abdulkadiroglu, Parag A. Pathak, Alvin E. Roth and Tayfun Sonmez, The Boston public school match, American Economic Review 95(2), 368 to 371 (2005), the whole paper (the old rule, the evidence of strategic play, and the change to deferred acceptance)
  4. Parag A. Pathak and Tayfun Sonmez, Leveling the playing field, sincere and sophisticated players in the Boston mechanism, American Economic Review 98(4), 1636 to 1652 (2008), the whole paper (equilibria with sincere and sophisticated students)
  5. Yan Chen and Tayfun Sonmez, School choice, an experimental study, Journal of Economic Theory 127(1), 202 to 231 (2006), the whole paper (laboratory comparison of the Boston mechanism, deferred acceptance and top trading cycles)
  6. Atila Abdulkadiroglu, Yeon-Koo Che and Yosuke Yasuda, Resolving conflicting preferences in school choice, the Boston mechanism reconsidered, American Economic Review 101(1), 399 to 410 (2011), the whole paper (ex ante welfare with cardinal preferences and equal priorities)

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