Algorithm Search⌘K

Algorithmadvanced

Generalized median voter rule

Also called Moulin phantom voters rule, generalized median rule.

Takes the median of the reported peaks and n+1 fixed phantom points. On a single-peaked line these are exactly the anonymous strategyproof rules that use only the peaks.

Time
O(n + m) worst
Space
O(m) extra
Where
m = the number of candidates; n = the number of voters
Properties
not comparison baseddeterministiciterative
Origin
Hervé Moulin, Kim C. Border, James S. Jordan, Duncan Black, 1980

A generalized median voter rule chooses one point of a line from the peaks that the voters report. It adds a fixed list of extra points, the phantom peaks, and returns the median of all the points. With single-peaked preferences on the line, no voter can get a better outcome by reporting a false peak, for every choice of phantoms. Moulin (1980) proved the converse: with nn voters, the anonymous strategyproof rules that use only the peaks are exactly the medians with n+1n + 1 phantoms.

In plain words

Each voter names a favourite place on a line, for example a temperature for a shared office or a site on a road. The rule also has some fixed places of its own, set in advance and the same for every election. It puts all the named places and all the fixed places in order and takes the one in the middle. If the middle is to the left of your favourite, naming a place farther to the right does not move the middle, and naming a place to its left can only move the middle away from you. So the honest answer is always best. The fixed places let the designer choose how much the outcome leans to one side or how much a single voter can move it.

The problem

The candidates are the points 0,1,…,m−10, 1, \ldots, m - 1 of an axis. Each voter ii reports a peak pip_i. The rule has kk phantom peaks a1,…,aka_1, \ldots, a_k, points of the axis fixed before the vote, with n+kn + k odd. The output is the median of the multiset {p1,…,pn,a1,…,ak}\{p_1, \ldots, p_n, a_1, \ldots, a_k\}, the value in position (n+k+1)/2(n + k + 1)/2 when the multiset is sorted. Moulin's rules have k=n+1k = n + 1; the rules that are also Pareto efficient have k=n−1k = n - 1.

Two choices give familiar rules. With ⌈(n+1)/2⌉\lceil (n + 1)/2 \rceil phantoms at 00 and the rest at m−1m - 1, the rule is the median of the peaks for odd nn, and on a single-peaked profile that is the Condorcet winner by the median voter theorem. With all n+1n + 1 phantoms at one point aa, the rule always returns aa, a constant rule.

The algorithm

  1. GEN-MEDIAN(p_1, ..., p_n; a_1, ..., a_k; m) ▷ n + k odd, all values in 0, ..., m - 1
  2. 1cnt[x] ← 0 for x = 0, ..., m - 1
  3. 2for i ← 1 to n do cnt[p_i] ← cnt[p_i] + 1
  4. 3for j ← 1 to k do cnt[a_j] ← cnt[a_j] + 1
  5. 4need ← (n + k + 1) / 2; seen ← 0
  6. 5for x ← 0 to m - 1 do seen ← seen + cnt[x]
  7. 6if seen ≥ need then return x

Lines L1 to L3 count how many values sit at each point, as in counting sort. Line L5 keeps the number of values at or to the left of xx. The first point where this number reaches half of the values, rounded up, is the median, and line L6 returns it. If mm is much larger than nn, the same median comes from linear-time selection on the n+kn + k values, without the table.

Example

The axis has seven points 0,…,60, \ldots, 6. Three voters report the peaks 11, 44 and 66, and the rule has the four phantoms 0,2,2,60, 2, 2, 6.

values in order position 4 of 7 outcome
0,1,2,2,4,6,60, 1, 2, 2, 4, 6, 6 22 22

The outcome 22 is to the left of the peaks 44 and 66. If the voter with peak 44 reports 55 or 66, the values at or to the left of 22 are still 0,1,2,20, 1, 2, 2, and the outcome stays 22. If it reports 00, 11 or 22, the outcome can only move left, farther from 44. The voter with peak 11 is to the left of the outcome and has the mirror choices. The plain median of the peaks uses the phantoms 0,0,6,60, 0, 6, 6 instead: the values 0,0,1,4,6,6,60, 0, 1, 4, 6, 6, 6 give 44, the middle peak.

Correctness

The proof is in proofs/correctness.md. The median is the smallest xx such that at least half of the values, rounded up, are at most xx, and lines L5 and L6 find exactly this xx.

For strategyproofness, fix the other reports and let xx be the outcome with the true peak pi>xp_i > x. A false report q>xq > x does not change the number of values at or to the left of any y≤xy \le x, so the outcome stays xx. A false report q≤xq \le x only adds to these numbers, so the outcome moves to some x′≤xx' \le x. Since the voter's ranking is single-peaked, a point farther left of the peak is worse, so x′x' is not better than xx. The case pi<xp_i < x is the mirror image. The argument holds for any phantoms, so every rule of this form is strategyproof in the sense of dominant-strategy incentive compatibility.

With n−1n - 1 phantoms the outcome lies between the smallest and the largest peak, and every such point is Pareto efficient on a single-peaked line. With n+1n + 1 phantoms the rule is Pareto efficient if and only if there is a phantom at each end of the axis.

Proof: The generalized median is computed correctly, is strategyproof on single-peaked preferences, and is Pareto efficient with n - 1 phantomsfull

The candidates are the points 0,1,…,m−10, 1, \ldots, m - 1 of the axis. Each voter ii has a ranking ≻i\succ_i that is single-peaked on the axis with peak pip_i. The rule takes the multiset VV of the nn reported peaks and the kk phantoms a1,…,aka_1, \ldots, a_k, with T=n+kT = n + k odd, and returns its median: the value at position (T+1)/2(T + 1)/2 when VV is sorted. For a value yy let c(y)c(y) be the number of elements of VV that are at most yy. The median is the smallest yy with c(y)≥(T+1)/2c(y) \ge (T + 1)/2.

The code returns the median

Lines L1 to L3 set cnt[x]\mathrm{cnt}[x] to the number of elements of VV equal to xx. Before line L6 tests xx, line L5 has made seen=cnt[0]+⋯+cnt[x]=c(x)\mathrm{seen} = \mathrm{cnt}[0] + \cdots + \mathrm{cnt}[x] = c(x). The loop goes through x=0,1,…x = 0, 1, \ldots in order and stops at the first xx with c(x)≥(T+1)/2c(x) \ge (T + 1)/2, which is the median by the description above. Some xx stops the loop, because c(m−1)=Tc(m - 1) = T. The time is O(n+k+m)O(n + k + m) and the extra space is O(m)O(m).

A fact about single-peaked rankings

If y<z≤piy < z \le p_i, then z≻iyz \succ_i y. If pi≤z<yp_i \le z < y, then z≻iyz \succ_i y. In words, on each side of the peak a point nearer to the peak is better. This is the no-valley form of the definition applied to y,z,piy, z, p_i, with z=piz = p_i allowed.

Strategyproofness

Fix the reports of the other voters and the phantoms. Let xx be the outcome when voter ii reports its true peak pip_i, and let x′x' be the outcome when it reports some qq. We show that x′≻ixx' \succ_i x never holds. The rule reads only the top of each reported ranking, so a false ranking acts only through its top qq.

If x=pix = p_i, the voter gets its best point and cannot gain. Assume x<pix < p_i; the case x>pix > p_i is the mirror image.

  • If q>xq > x: going from pip_i to qq removes a value above xx and adds a value above xx, so c(y)c(y) does not change for any y≤xy \le x. The smallest yy with c(y)≥(T+1)/2c(y) \ge (T + 1)/2 is still xx, so x′=xx' = x.
  • If q≤xq \le x: the change adds one to c(y)c(y) for q≤y<piq \le y < p_i and leaves the other counts the same. No count goes down, so the smallest yy with a large enough count can only move left: x′≤xx' \le x.

So x′≤x<pix' \le x < p_i, and by the fact above x≻ix′x \succ_i x' or x′=xx' = x. The voter cannot gain. This holds for every choice of phantoms, every kk with TT odd, and every reports of the other voters.

Unanimity and Pareto efficiency

With n−1n - 1 phantoms, T=2n−1T = 2n - 1 and the median is the element in position nn. At least nn values, the nn peaks, are at most max⁡ipi\max_i p_i, so c(max⁡ipi)≥nc(\max_i p_i) \ge n and the outcome is at most max⁡ipi\max_i p_i. In the same way it is at least min⁡ipi\min_i p_i. A point xx with min⁡ipi≤x≤max⁡ipi\min_i p_i \le x \le \max_i p_i is Pareto efficient on single-peaked rankings: for z>xz > x, the voter with peak min⁡ipi≤x\min_i p_i \le x prefers xx to zz by the fact above, and for z<xz < x the voter with peak max⁡ipi\max_i p_i prefers xx to zz. So no other point is ranked above xx by all voters.

With n+1n + 1 phantoms. If the phantoms include the point 00 and the point m−1m - 1, removing one copy of each from VV removes the smallest and the largest value and does not change the median, so the rule equals a rule with the other n−1n - 1 phantoms and is Pareto efficient. If no phantom is at 00, let every voter have peak 00. Then VV has exactly nn values equal to 00, fewer than (T+1)/2=n+1(T + 1)/2 = n + 1, so the outcome is not 00, while every voter prefers 00 to it. The case with no phantom at m−1m - 1 is the mirror image. So a median with n+1n + 1 phantoms is Pareto efficient if and only if it has a phantom at each end of the axis.

More precisely, with n+1n + 1 phantoms and all voters at the same peak pp, the outcome is in position n+1n + 1 of 2n+12n + 1 values. If p<min⁡jajp < \min_j a_j, the first nn values are the copies of pp and the outcome is min⁡jaj\min_j a_j. If p>max⁡jajp > \max_j a_j, the first n+1n + 1 values are the phantoms and the outcome is max⁡jaj\max_j a_j. Otherwise it is pp. So the outcome is pp moved into the interval [min⁡jaj,max⁡jaj][\min_j a_j, \max_j a_j].

The characterization

The converse, that every anonymous and strategyproof rule that depends only on the peaks is a median with n+1n + 1 phantoms, is Moulin's theorem (Moulin 1980, Proposition 2; Weymark 2011, Theorem 4), and with Pareto efficiency added the rule is a median with n−1n - 1 phantoms (Weymark 2011, Theorem 5). This file does not reprove it. The test test_characterization_three_candidates_two_voters checks it by brute force for m=3m = 3 and n=2n = 2: of the 36=7293^6 = 729 functions from multisets of two peaks to outcomes, exactly the 10 medians with 3 phantoms are strategyproof, and exactly the 3 medians with 1 phantom are strategyproof and Pareto efficient.

Complexity

Lines L1 and L5 take O(m)O(m) time, and lines L2 and L3 take O(n+k)O(n + k) time. With k=n+1k = n + 1 or k=n−1k = n - 1 the total is O(n+m)O(n + m) time in the word RAM model, with O(m)O(m) extra space for the counts. Linear selection gives O(n)O(n) time and O(n)O(n) space, which is better when mm is large or the axis is the real line.

Properties

  • Strategyproof on the single-peaked domain, for every choice of phantoms. On the full domain of rankings, a rule of this kind with three or more possible outcomes and no dictator can be manipulated, as the Gibbard-Satterthwaite theorem says it must.
  • Anonymous. The output depends only on the multiset of peaks.
  • Peak-only. It reads only the top of each ranking, so a voter reports one point, not a full ranking.
  • Not neutral. The phantoms favour some points of the axis, and even the plain median treats points by their place on the axis, not by their names.
  • Unanimity. If all voters report the same peak pp, a rule with n+1n + 1 phantoms returns pp moved into the interval from the smallest to the largest phantom. It returns pp for every pp exactly when there are phantoms at both ends.
  • The characterization. On the single-peaked domain, a rule that depends only on the peaks is anonymous and strategyproof if and only if it is a median with n+1n + 1 phantoms (Moulin 1980, Proposition 2; Weymark 2011, Theorem 4). It is also Pareto efficient if and only if it is a median with n−1n - 1 phantoms (Weymark 2011, Theorem 5).

Variants and improvements

  • Without anonymity. Moulin (1980, Proposition 3) describes all strategyproof peak-only rules by a min-max formula with one parameter for each coalition of voters, 2n2^n parameters in all. The phantom medians are the anonymous case, where the parameter depends only on the size of the coalition.
  • Without the peak-only condition. For strategyproof rules on the single-peaked domain, using only the peaks is equivalent to having an interval of the axis as the set of possible outcomes (Weymark 2011, Theorem 1).
  • Several dimensions. Border and Jordan (1983) studied ideal points in a space of several dimensions, where the strategyproof rules that respect unanimity decompose coordinate by coordinate into one-dimensional rules of this kind.
  • Facility location. In the facility location mechanism setting the agents are points on a line and the cost is distance. The median of the reports is strategyproof and minimizes the sum of the distances.

When to use it

Use it to choose one value on an ordered scale, such as a budget level, a date, a temperature or a location on a road, when the voters can be assumed to have single-peaked preferences and honest reports matter. Use the plain median when the rule should treat both directions alike, and phantoms at chosen points when there is a default, a status quo or a bound the outcome should lean to. Check the profile with single-peaked recognition when the axis is not given by the problem.

Pitfalls

  • An even number of values. With an even total there is no single median. Moulin's rules use n+1n + 1 phantoms so that the total 2n+12n + 1 is odd.
  • The wrong number of phantoms. The characterization is for n+1n + 1 phantoms, and the Pareto efficient case is for n−1n - 1. Phantoms that leave out an end of the axis give a rule that ignores the voters even when they all agree on that end.
  • Using the mean. The average of the peaks is not strategyproof: a voter can report an extreme peak to pull the average toward its own.
  • Preferences that are not single-peaked. If a voter's ranking has a valley, a false peak can help, and the strategyproof guarantee is lost.

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))
generalized_median_voter_rule.py 54 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/generalized-median-voter-rule/. The authors are listed in prov/N9KT39.jsonl.
"""Moulin's generalized median voter rules on a line of m candidates.

The candidates are the points 0, ..., m - 1 of the axis, in this order. Each voter reports a
peak. The rule adds a fixed list of phantom peaks and returns the median of all the values.
With n voters, Moulin's rules use n + 1 phantoms (2n + 1 values in all); the rules that are
also Pareto efficient use n - 1 phantoms (2n - 1 values). Any odd total is accepted.
"""

from typing import Sequence


def generalized_median(peaks: Sequence[int], phantoms: Sequence[int], m: int) -> int:
    """Return the median of the peaks and the phantoms, all in 0, ..., m - 1.

    The number of values len(peaks) + len(phantoms) must be odd. Counting sort: O(n + m).
    """
    total = len(peaks) + len(phantoms)
    if total % 2 == 0:
        raise ValueError("the number of peaks and phantoms together must be odd")
    cnt = [0] * m  # @line L1
    for p in peaks:  # @line L2
        cnt[p] += 1
    for a in phantoms:  # @line L3
        cnt[a] += 1
    need = (total + 1) // 2  # @line L4
    seen = 0
    for x in range(m):  # @line L5
        seen += cnt[x]
        if seen >= need:
            return x  # @line L6
    raise AssertionError("unreachable")


def median_rule(phantoms: Sequence[int]):
    """Return the voting rule rule(profile, m) that applies the phantoms to the voters' tops.

    The profile is a sequence of rankings, best first, so the peak of voter i is profile[i][0].
    """

    def rule(profile, m):
        return generalized_median([r[0] for r in profile], phantoms, m)

    return rule


def plain_median_phantoms(n: int, m: int) -> list:
    """Phantoms that make the rule the median of the peaks for odd n, the lower median for even n.

    Half of the n + 1 phantoms (rounded up) sit at 0 and the rest at m - 1.
    """
    low = (n + 2) // 2
    return [0] * low + [m - 1] * (n + 1 - low)
test_generalized_median_voter_rule.py 134 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/generalized-median-voter-rule/. The authors are listed in prov/N9KT39.jsonl.

import itertools
import random

import pytest

from agtprefs import (
    all_rankings,
    check_anonymity,
    check_pareto,
    condorcet_winner,
    find_manipulation,
    is_single_peaked_on,
    margins,
    weak_condorcet_winners,
)
from generalized_median_voter_rule import generalized_median, median_rule, plain_median_phantoms


def sp_rankings(m):
    axis = tuple(range(m))
    return [r for r in all_rankings(m) if is_single_peaked_on((r,), axis)]


def sp_profiles(m, n):
    return list(itertools.product(sp_rankings(m), repeat=n))


def test_agrees_with_sorting():
    rng = random.Random(1)
    for _ in range(500):
        m = rng.randint(1, 8)
        n = rng.randint(0, 7)
        peaks = [rng.randrange(m) for _ in range(n)]
        k = n + 1 if n == 0 or rng.random() < 0.5 else n - 1
        phantoms = [rng.randrange(m) for _ in range(k)]
        values = sorted(peaks + phantoms)
        assert generalized_median(peaks, phantoms, m) == values[len(values) // 2]


def test_even_total_is_rejected():
    with pytest.raises(ValueError):
        generalized_median([0, 1], [0, 1], 3)


def test_strategyproof_for_every_phantom_choice():
    m, n = 4, 2
    P = sp_profiles(m, n)
    for phantoms in itertools.combinations_with_replacement(range(m), n + 1):
        assert find_manipulation(median_rule(phantoms), m, n, profiles=P) is None


def test_strategyproof_with_three_voters():
    m, n = 4, 3
    P = sp_profiles(m, n)
    rng = random.Random(2)
    for _ in range(2):
        phantoms = sorted(rng.randrange(m) for _ in range(n + 1))
        assert find_manipulation(median_rule(phantoms), m, n, profiles=P) is None


def test_anonymous():
    m, n = 4, 3
    P = sp_profiles(m, n)
    assert check_anonymity(median_rule([0, 1, 1, 3]), m, n, profiles=P) is None


def test_pareto_with_n_minus_one_phantoms_and_not_in_general():
    m, n = 4, 3
    P = sp_profiles(m, n)
    for phantoms in itertools.combinations_with_replacement(range(m), n - 1):
        assert check_pareto(median_rule(phantoms), m, n, profiles=P) is None
    # n + 1 phantoms that leave out the end 0: all voters at 0 still get 1
    rule = median_rule([1, 1, 2, 3])
    assert rule(((0, 1, 2, 3),) * 3, m) == 1
    assert check_pareto(rule, m, n, profiles=P) is not None


def peak_rule_from_table(table):
    return lambda profile, m: table[tuple(sorted(r[0] for r in profile))]


def test_characterization_three_candidates_two_voters():
    """Every anonymous peak-only rule that is strategyproof on the single-peaked domain is a
    median with n + 1 phantoms, and with Pareto it is a median with n - 1 phantoms."""
    m, n = 3, 2
    P = sp_profiles(m, n)
    keys = list(itertools.combinations_with_replacement(range(m), n))
    sp_rules, sp_pareto_rules = set(), set()
    for values in itertools.product(range(m), repeat=len(keys)):
        table = dict(zip(keys, values))
        rule = peak_rule_from_table(table)
        if find_manipulation(rule, m, n, profiles=P) is None:
            sp_rules.add(values)
            if check_pareto(rule, m, n, profiles=P) is None:
                sp_pareto_rules.add(values)

    def medians(k):
        return {tuple(generalized_median(key, ph, m) for key in keys)
                for ph in itertools.combinations_with_replacement(range(m), k)}

    assert sp_rules == medians(n + 1)
    assert sp_pareto_rules == medians(n - 1)
    assert len(sp_rules) == 10 and len(sp_pareto_rules) == 3


def test_plain_median_is_the_condorcet_winner():
    for m in range(2, 5):
        for n in (1, 3):
            rule = median_rule(plain_median_phantoms(n, m))
            for prof in sp_profiles(m, n):
                assert rule(prof, m) == condorcet_winner(prof, m)


def test_median_voter_theorem_by_brute_force():
    for m in range(2, 6):
        R = sp_rankings(m)
        for n in range(1, 5 if m < 5 else 4):
            for prof in itertools.combinations_with_replacement(R, n):
                peaks = sorted(r[0] for r in prof)
                M = margins(prof, m)
                if n % 2 == 1:
                    order = sorted(range(m), key=lambda a: -sum(1 for b in range(m) if M[a][b] > 0))
                    assert all(M[order[i]][order[j]] > 0 for i in range(m) for j in range(i + 1, m))
                    assert is_single_peaked_on((tuple(order),), tuple(range(m)))
                else:
                    lo, hi = peaks[n // 2 - 1], peaks[n // 2]
                    assert weak_condorcet_winners(prof, m) == frozenset(range(lo, hi + 1))


def test_no_voters():
    assert generalized_median([], [2], 5) == 2

History

Black (1948) observed that the median of the peaks wins every pairwise majority vote on a single-peaked profile. Moulin (1980) asked which rules make honest reports a dominant strategy on this domain, and found the medians with n+1n + 1 fixed extra peaks, together with a min-max formula for the rules without anonymity. Border and Jordan (1983) gave the extra points the name phantom voters, in a study of several dimensions. Weymark (2011) gave a unified treatment of these results.

References

  1. Hervé Moulin, On strategy-proofness and single peakedness, Public Choice 35(4) (1980), 437-455, Proposition 2 (anonymous rules with n+1 phantoms) and Proposition 3 (the general min-max form)
  2. Kim C. Border and James S. Jordan, Straightforward elections, unanimity and phantom voters, Review of Economic Studies 50(1) (1983), 153-170, the characterization by phantom voters
  3. John A. Weymark, A unified approach to strategy-proofness for single-peaked preferences, SERIEs 2(4) (2011), 529-550, Theorem 1 (tops-only and an interval range), Theorem 4 (Moulin's anonymous characterization) and Theorem 5 (with Pareto efficiency, n-1 phantoms)
  4. Duncan Black, On the rationale of group decision-making, Journal of Political Economy 56(1) (1948), 23-34, the median optimum for single-peaked curves of preference

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