Algorithm Search⌘K

Algorithmadvanced

Slater's rule

Also called Slater ranking.

Finds the ranking that disagrees with the fewest pairwise majority outcomes, a minimum feedback arc set of the majority tournament.

Time
O(n m^2 + 2^m m) worst
Space
O(2^m) extra
Where
m = the number of candidates; n = the number of voters
Properties
not comparison baseddeterministiciterative
Origin
Patrick Slater, 1961

Slater's rule turns the majority relation of an election into a ranking. For each pair of candidates, a majority of voters prefers one to the other, and the rule looks for the ranking that goes against as few of these majorities as possible. When the majority relation has no cycle, the answer is that relation itself. When it has cycles, some majorities must be reversed, and the rule reverses the fewest. In graph terms, it finds a minimum feedback arc set of the majority tournament. The Slater winners are the candidates on top of some optimal ranking. The problem is NP-hard. The algorithm below is a dynamic program over subsets that takes O(2mm)O(2^m m) time after the majorities are counted, which is fast enough for about 20 candidates.

In plain words

For every pair of candidates, count which one more voters prefer. Each such result is one fact about the voters. A ranking agrees with some of these facts and goes against others. Slater's rule picks the ranking that goes against the fewest facts, and the top of that ranking wins. Only who won each pair counts, not by how much. The program builds the best ranking one place at a time: for every group of candidates, it remembers the best way to rank that group, and it tries each member of a group as its first.

The problem

There are mm candidates A={0,…,m−1}A = \{0, \ldots, m - 1\} and a profile PP of nn rankings. Let g(x,y)=nP(x,y)−nP(y,x)g(x, y) = n_P(x, y) - n_P(y, x) be the margin of xx over yy. The majority graph has an arc x→yx \to y when g(x,y)>0g(x, y) > 0; when nn is odd it is a tournament, with one arc between each pair. For a ranking rr, its Slater cost is the number of pairs where rr puts yy above xx although g(x,y)>0g(x, y) > 0. A Slater ranking has the least cost, and the Slater winners are the candidates on top of some Slater ranking. The code returns the Slater ranking that is first in lexicographic order, and its top as the winner. Pairs with margin 0 cost nothing in either order.

The algorithm

For a set SS of candidates, let cost(S)\mathrm{cost}(S) be the least cost of a ranking of SS alone. If vv is first, it is above all of S∖{v}S \setminus \{v\}, so it goes against the arcs into vv from SS, and the rest is ranked as well as possible:

cost(S)=min⁡v∈S(∣lose(v)∩(S∖{v})∣+cost(S∖{v})),\mathrm{cost}(S) = \min_{v \in S} \left( |\mathrm{lose}(v) \cap (S \setminus \{v\})| + \mathrm{cost}(S \setminus \{v\}) \right),

where lose(v)={u:g(u,v)>0}\mathrm{lose}(v) = \{ u : g(u, v) > 0 \}. Sets are stored as bit masks.

  1. SLATER(P, m)
  2. 1lose[v] ← {u : g(u, v) > 0} for each v, from the margins of P
  3. 2cost[∅] ← 0
  4. 3for each nonempty S ⊆ A, in increasing order of its bit mask do
  5. 4cost[S] ← min over v ∈ S of |lose[v] ∩ (S \ {v})| + cost[S \ {v}]
  6. 5S ← A; r ← empty list
  7. 6while S ≠ ∅ do
  8. 7v ← the smallest v ∈ S with |lose[v] ∩ (S \ {v})| + cost[S \ {v}] = cost[S]
  9. 8append v to r; S ← S \ {v}
  10. 9return r

The bit mask of S∖{v}S \setminus \{v\} is smaller than that of SS, so line L4 only reads entries that are already filled. Lines L5 to L8 rebuild an optimal ranking from the table. Taking the smallest vv that is optimal at each step gives the lexicographically first Slater ranking. A candidate is a Slater winner exactly when it passes the test of line L7 for S=AS = A.

Example

Take four candidates a,b,c,da, b, c, d (indices 0 to 3) and 13 voters:

voters ranking
4 d≻b≻c≻ad \succ b \succ c \succ a
6 b≻a≻d≻cb \succ a \succ d \succ c
3 c≻a≻d≻bc \succ a \succ d \succ b

The majority arcs, with margins, are b→ab \to a (7), b→cb \to c (7), d→cd \to c (7), a→da \to d (5), c→ac \to a (1) and d→bd \to b (1). They form the cycles a→d→b→aa \to d \to b \to a and a→d→c→aa \to d \to c \to a, so there is no Condorcet winner, and all four candidates are in the Smith set. The test of line L7 for S=AS = A gives:

first vv arcs into vv best ranking of the rest total
aa b→ab \to a, c→ac \to a: 2 d≻b≻cd \succ b \succ c: 0 2
bb d→bd \to b: 1 {a,c,d}\{a, c, d\} is a cycle: 1 2
cc b→cb \to c, d→cd \to c: 2 {a,b,d}\{a, b, d\} is a cycle: 1 3
dd a→da \to d: 1 b≻c≻ab \succ c \succ a: 0 1

So cost(A)=1\mathrm{cost}(A) = 1, the only Slater ranking is d≻b≻c≻ad \succ b \succ c \succ a, and dd wins. It reverses only the arc a→da \to d. Kemeny's rule weighs each reversed arc by its margin. It prefers b≻a≻d≻cb \succ a \succ d \succ c, which reverses d→bd \to b and c→ac \to a, of margin 1 each, for a weight of 2 against 5 for the Slater ranking. So the two rules elect different candidates on this profile.

Correctness

The recursion of line L4 is correct because in any ranking of SS with first element vv, the pairs that include vv cost exactly ∣lose(v)∩(S∖{v})∣|\mathrm{lose}(v) \cap (S \setminus \{v\})|, and the other pairs are a ranking of S∖{v}S \setminus \{v\}, which costs at least cost(S∖{v})\mathrm{cost}(S \setminus \{v\}) and can cost exactly that. Lines L5 to L8 follow optimal choices, so the ranking they build has cost cost(A)\mathrm{cost}(A). The proof in proofs/correctness.md gives the details and proves the properties below.

Proof: Correctness and properties of the subset program for Slater's rulefull

Let A={0,…,m−1}A = \{0, \ldots, m - 1\}, let PP be a profile of nn rankings, and let g(x,y)g(x, y) be the margins. Write x→yx \to y when g(x,y)>0g(x, y) > 0, and lose(v)={u:u→v}\mathrm{lose}(v) = \{u : u \to v\}. For a ranking rr of a set S⊆AS \subseteq A, its cost κ(r)\kappa(r) is the number of pairs {x,y}⊆S\{x, y\} \subseteq S with x→yx \to y and yy above xx in rr. Let opt(S)\mathrm{opt}(S) be the least cost of a ranking of SS, with opt(∅)=0\mathrm{opt}(\emptyset) = 0.

Claim 1 (recursion). For nonempty SS, opt(S)=min⁡v∈S(∣lose(v)∩(S∖{v})∣+opt(S∖{v}))\mathrm{opt}(S) = \min_{v \in S} \left( |\mathrm{lose}(v) \cap (S \setminus \{v\})| + \mathrm{opt}(S \setminus \{v\}) \right). More precisely, the least cost of a ranking of SS with first element vv is the term for vv.

Proof. Let rr be a ranking of SS with first element vv, and let r′r' be the rest of rr, a ranking of S∖{v}S \setminus \{v\}. The pairs that contain vv have vv on top, so exactly those with u→vu \to v, u∈S∖{v}u \in S \setminus \{v\}, are reversed. The other pairs are the pairs of r′r'. So κ(r)=∣lose(v)∩(S∖{v})∣+κ(r′)\kappa(r) = |\mathrm{lose}(v) \cap (S \setminus \{v\})| + \kappa(r'). The least value over r′r' is the term for vv, and the least value over vv is the right side.

Claim 2 (correctness). After lines L2 to L4, cost[S]=opt(S)\mathrm{cost}[S] = \mathrm{opt}(S) for every SS. Lines L5 to L8 return the Slater ranking that is first in lexicographic order. A candidate is a Slater winner exactly when it passes the test of line L7 for S=AS = A.

Proof. The first part follows from Claim 1 by induction on the bit mask of SS, because the mask of S∖{v}S \setminus \{v\} is smaller than that of SS. For the second part, consider the loop with the invariant that the list rr built so far is a prefix of the lexicographically first ranking of AA with cost opt(A)\mathrm{opt}(A), and that SS is the set of the candidates not in rr. A ranking that begins with rr and continues with vv can reach cost opt(A)\mathrm{opt}(A) exactly when vv passes the test of line L7, by Claim 1 applied to SS and because the pairs between rr and SS are the same for all such rankings. The lexicographically first optimal ranking continues with the smallest such vv, and line L7 picks it. The third part is Claim 1 for S=AS = A.

Claim 3 (Smith set on top). Let TT be the Smith set, the smallest nonempty set of candidates each of whom has a positive margin over every candidate outside it. Every Slater ranking puts every member of TT above every candidate outside TT.

Proof. Let rr be a ranking that puts some y∉Ty \notin T above some x∈Tx \in T. Let r′r' list the members of TT in their order in rr, then the others in their order in rr. Pairs inside TT and pairs outside TT keep their order. A pair {x,y}\{x, y\} with x∈Tx \in T and y∉Ty \notin T has x→yx \to y, so it costs nothing in r′r', and at least one such pair costs 1 in rr. So κ(r′)<κ(r)\kappa(r') < \kappa(r), and rr is not optimal. A Condorcet winner cc has T={c}T = \{c\}, so it is on top of every Slater ranking.

Claim 4 (Pareto). If n≥1n \ge 1 and every voter ranks aa above bb, then every Slater ranking puts aa above bb.

Proof. For every x≠a,bx \ne a, b, a voter who ranks bb above xx also ranks aa above xx, and a voter who ranks xx above aa also ranks xx above bb. So b→xb \to x implies a→xa \to x, and x→ax \to a implies x→bx \to b. Let rr put bb above aa, and let r′r' be rr with aa and bb exchanged. For xx above both or below both, the two pairs with xx cost the same in total in rr and r′r'. For xx between them, rr has bb above xx above aa and pays [x→b]+[a→x][x \to b] + [a \to x], and r′r' pays [x→a]+[b→x][x \to a] + [b \to x], which is not more by the two implications. The pair {a,b}\{a, b\} has a→ba \to b, since g(a,b)=n≥1g(a, b) = n \ge 1, and costs 1 in rr and 0 in r′r'. So κ(r′)<κ(r)\kappa(r') < \kappa(r).

Claim 5 (monotonicity). Let ww be a Slater winner of PP, and let QQ be PP with ww moved up one place on one ballot, passing xx. Then ww is a Slater winner of QQ.

Proof. Only the margin between ww and xx changes, by 2 in favour of ww. So the only arc that can change is between ww and xx: the arc x→wx \to w may disappear, and the arc w→xw \to x may appear. For a ranking rr, the cost changes only on the pair {w,x}\{w, x\}. If rr puts ww above xx, the cost goes down by Δ=[x→w in P]−[x→w in Q]≥0\Delta = [x \to w \text{ in } P] - [x \to w \text{ in } Q] \ge 0, and if rr puts xx above ww, it does not go down. So every cost goes down by at most Δ\Delta, and a Slater ranking r∗r^* of PP with ww on top goes down by exactly Δ\Delta. So r∗r^* is optimal for QQ, and ww is a winner.

Claim 6 (anonymity and neutrality). Reordering the voters does not change the result. Renaming the candidates by π\pi renames the Slater rankings and the winners by π\pi.

Proof. The cost of a ranking depends only on the arcs, which do not depend on the order of the voters, and renaming the candidates renames the arcs.

Claim 7 (time). SLATER runs in O(nm2+2mm)O(n m^2 + 2^m m) time and O(2m)O(2^m) space on a word RAM with words of at least mm bits.

Proof. The margins take O(nm2)O(n m^2) time, and line L1 takes O(m2)O(m^2). Line L4 runs for 2m−12^m - 1 sets and tries at most mm candidates, each with one AND, one population count, one lookup and one addition. Lines L5 to L8 run mm times with at most mm tries each. The table has 2m2^m entries of O(log⁡m)O(\log m) bits. ■\blacksquare

Complexity

Counting the margins takes O(nm2)O(n m^2) time. The table has 2m2^m entries, and each entry tries at most mm candidates with O(1)O(1) word operations: one AND and one population count on an mm-bit mask, which fits in a word when mm is at most the word size of the word RAM. Lines L5 to L8 take O(m2)O(m^2) time. The total is O(nm2+2mm)O(n m^2 + 2^m m) time and O(2m)O(2^m) space. Trying all m!m! rankings instead would take O(m! m2)O(m! \, m^2) time.

Finding a Slater ranking, or deciding whether a candidate is a Slater winner, is NP-hard, so no polynomial algorithm is expected. For approximations of feedback arc set in tournaments, see Kemeny rank aggregation, which treats the weighted version, and KwikSort, which gives an expected ratio of 3 for the unweighted version with random pivots.

Properties

The proofs are in proofs/correctness.md, and the tests check each property on all profiles with up to 4 candidates and few voters and on random profiles with up to 6 candidates.

  • Smith set on top. Every Slater ranking puts the whole Smith set above all other candidates. So the Slater winners lie in the Smith set, and a Condorcet winner is the only winner.
  • Pareto. If every voter ranks aa above bb, then every Slater ranking puts aa above bb, so bb does not win.
  • Monotone. Moving a winner up on one ballot keeps it a winner.
  • Anonymous, and neutral as a correspondence. Only the majority graph is used. The resolute rule is not neutral, because of the tie rule.
  • A tournament solution. The result depends only on the majority graph. So two profiles with the same majorities but very different margins have the same Slater rankings, unlike Kemeny's rule.
  • Manipulable. The tests find a voter who gains by a false ranking with 3 candidates and 3 voters.

Variants and improvements

  • Kemeny's rule. Weigh each reversed arc by its margin. This is the weighted feedback arc set problem on the same graph, and the same subset program solves it with sums of margins in place of counts.
  • Integer programs. Exact solvers for larger mm use the integer program with one variable for each ordered pair and a constraint for each triple that forbids a cycle of length 3.
  • Approximation. KwikSort, which sorts by majorities with random pivots, has an expected ratio of 3 for feedback arc set in tournaments.
  • Ties in the majority graph. With nn even, some pairs have margin 0. This page charges nothing for them. Other versions charge one half in either order, which gives the same rankings.

When to use it

Use Slater's rule when only the outcomes of pairwise contests are known or trusted, as in round-robin tournaments in sport or in comparisons by judges. For elections with full ballots, Kemeny's rule uses more of the information. With up to about 20 candidates, the subset program is exact and fast; beyond that, use an integer program solver or an approximation.

Pitfalls

  • Ranking by wins. Sorting candidates by their number of majority wins, the Copeland score, is not the Slater ranking, even when it has no ties.
  • Counting margins. The cost counts reversed arcs, not their margins. Using margins gives Kemeny's rule, which can elect a different candidate, as in the example.
  • The memory of the table. The table has 2m2^m entries. For m=30m = 30, that is about a billion entries, too many for most machines.
  • Ties. Several rankings can be optimal, and their tops can differ. Return the set of winners, or state the tie rule.

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))
slater_rule.py 73 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/slater-rule/. The authors are listed in prov/DWARFM.jsonl.

from typing import Sequence

Ranking = Sequence[int]


def margin_matrix(profile: Sequence[Ranking], m: int) -> list[list[int]]:
    """Return M with M[a][b] = (voters who rank a above b) - (voters who rank b above a)."""
    M = [[0] * m for _ in range(m)]
    for r in profile:
        for i, a in enumerate(r):
            for b in r[i + 1:]:
                M[a][b] += 1
                M[b][a] -= 1
    return M


def slater_cost(profile: Sequence[Ranking], m: int, ranking: Ranking) -> int:
    """Return the number of pairs that the ranking puts against a strict majority."""
    M = margin_matrix(profile, m)
    return sum(1 for i, a in enumerate(ranking) for b in ranking[i + 1:] if M[b][a] > 0)


def _table(profile: Sequence[Ranking], m: int) -> tuple[list[int], list[int]]:
    """Return (lose, cost): lose[v] is the bit set of the u with a positive margin over v, and
    cost[S] is the least number of majority disagreements of a ranking of the set S."""
    M = margin_matrix(profile, m)
    lose = [sum(1 << u for u in range(m) if M[u][v] > 0) for v in range(m)]  # @line L1
    cost = [0] * (1 << m)  # @line L2
    for S in range(1, 1 << m):  # @line L3
        best = None
        T = S
        while T:
            v = (T & -T).bit_length() - 1
            T &= T - 1
            rest = S & ~(1 << v)
            c = (lose[v] & rest).bit_count() + cost[rest]  # @line L4
            if best is None or c < best:
                best = c
        cost[S] = best
    return lose, cost


def slater_ranking(profile: Sequence[Ranking], m: int) -> tuple[int, ...]:
    """Return the lexicographically smallest ranking with the fewest majority disagreements."""
    lose, cost = _table(profile, m)
    S = (1 << m) - 1  # @line L5
    out = []
    while S:  # @line L6
        for v in range(m):
            if S >> v & 1:
                rest = S & ~(1 << v)
                if (lose[v] & rest).bit_count() + cost[rest] == cost[S]:  # @line L7
                    break
        out.append(v)  # @line L8
        S = rest
    return tuple(out)  # @line L9


def slater_winners(profile: Sequence[Ranking], m: int) -> frozenset[int]:
    """Return the candidates that are on top of some ranking with the fewest disagreements."""
    lose, cost = _table(profile, m)
    full = (1 << m) - 1
    return frozenset(v for v in range(m)
                     if (lose[v] & (full & ~(1 << v))).bit_count() + cost[full & ~(1 << v)]
                     == cost[full])


def slater(profile: Sequence[Ranking], m: int) -> int:
    """Return the Slater winner; a tie goes to the candidate with the smallest index."""
    return slater_ranking(profile, m)[0]
test_slater_rule.py 142 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/slater-rule/. The authors are listed in prov/DWARFM.jsonl.

import random
from itertools import combinations, permutations

from agtprefs import (check_anonymity, check_condorcet_consistency, check_monotonicity,
                      check_neutrality, check_pareto, condorcet_winner, find_manipulation,
                      kendall_tau, margins, prefers, random_profile)
from slater_rule import margin_matrix, slater, slater_cost, slater_ranking, slater_winners

A, B, C, D = 0, 1, 2, 3

# The worked example of the page: 13 voters in three groups.
EXAMPLE = ((D, B, C, A),) * 4 + ((B, A, D, C),) * 6 + ((C, A, D, B),) * 3


def kemeny_cost(P, r):
    return sum(kendall_tau(r, v) for v in P)


def test_example():
    M = margin_matrix(EXAMPLE, 4)
    assert [M[B][A], M[C][A], M[A][D], M[B][C], M[D][B], M[D][C]] == [7, 1, 5, 7, 1, 7]
    assert condorcet_winner(EXAMPLE, 4) is None
    assert smith_set(EXAMPLE, 4) == frozenset({A, B, C, D})
    best, opt = brute_force(EXAMPLE, 4)
    assert best == 1 and opt == [(D, B, C, A)]
    assert slater_ranking(EXAMPLE, 4) == (D, B, C, A)
    assert slater_winners(EXAMPLE, 4) == frozenset({D})
    assert slater(EXAMPLE, 4) == D
    first = {v: min(slater_cost(EXAMPLE, 4, r) for r in permutations(range(4)) if r[0] == v)
             for v in range(4)}
    assert first == {A: 2, B: 2, C: 3, D: 1}
    # Kemeny weighs each disagreement by its margin and picks another ranking.
    k = {r: kemeny_cost(EXAMPLE, r) for r in permutations(range(4))}
    kbest = min(k.values())
    assert [r for r in k if k[r] == kbest] == [(B, A, D, C)]
    assert slater_cost(EXAMPLE, 4, (B, A, D, C)) == 2
    assert k[(D, B, C, A)] - kbest == 3


def brute_force(P, m):
    M = margins(P, m)
    costs = {r: sum(1 for i in range(m) for j in range(i + 1, m) if M[r[j]][r[i]] > 0)
             for r in permutations(range(m))}
    best = min(costs.values())
    opt = sorted(r for r in costs if costs[r] == best)
    return best, opt


def smith_set(P, m):
    M = margins(P, m)
    for size in range(1, m + 1):
        for S in combinations(range(m), size):
            if all(M[a][b] > 0 for a in S for b in range(m) if b not in S):
                return frozenset(S)
    return frozenset()


def test_matches_brute_force():
    rng = random.Random(1)
    for _ in range(100):
        m, n = rng.randint(1, 6), rng.randint(0, 7)
        P = random_profile(rng, m, n)
        assert margin_matrix(P, m) == margins(P, m)
        best, opt = brute_force(P, m)
        r = slater_ranking(P, m)
        assert r == opt[0]
        assert slater_cost(P, m, r) == best
        assert slater_winners(P, m) == frozenset(o[0] for o in opt)
        assert slater(P, m) == r[0]


def test_edge_cases():
    assert slater_ranking((), 1) == (0,)
    assert slater_ranking((), 3) == (0, 1, 2)
    assert slater_winners((), 3) == frozenset({0, 1, 2})
    assert slater_ranking(((2, 0, 1),), 3) == (2, 0, 1)
    cycle = ((A, B, C), (B, C, A), (C, A, B))
    assert slater_winners(cycle, 3) == frozenset({A, B, C})
    assert slater_ranking(cycle, 3) == (A, B, C)
    assert slater_cost(cycle, 3, (A, B, C)) == 1


def test_smith_set_on_top():
    rng = random.Random(2)
    for _ in range(100):
        m, n = rng.randint(2, 6), rng.randint(1, 7)
        P = random_profile(rng, m, n)
        S = smith_set(P, m)
        _, opt = brute_force(P, m)
        for r in opt:
            assert frozenset(r[:len(S)]) == S


def test_axioms_on_full_domains():
    for m, n in ((2, 3), (3, 1), (3, 2), (3, 3), (4, 1)):
        assert check_anonymity(slater_winners, m, n) is None
        assert check_neutrality(slater_winners, m, n) is None
        assert check_pareto(slater_winners, m, n) is None
        assert check_condorcet_consistency(slater_winners, m, n) is None
        assert check_monotonicity(slater_winners, m, n) is None


def test_axioms_on_random_profiles():
    for m, n, seed in ((5, 5, 3), (6, 7, 4)):
        rng = random.Random(seed)
        Ps = [random_profile(rng, m, n) for _ in range(15)]
        assert check_anonymity(slater_winners, m, n, Ps) is None
        assert check_neutrality(slater_winners, m, n, Ps) is None
        assert check_pareto(slater_winners, m, n, Ps) is None
        assert check_condorcet_consistency(slater_winners, m, n, Ps) is None
        assert check_monotonicity(slater_winners, m, n, Ps) is None


def test_resolute_rule_is_not_neutral():
    assert slater(((A, B), (B, A)), 2) == A
    assert check_neutrality(slater, 2, 2) is not None


def test_manipulation_exists():
    found = find_manipulation(slater, 3, 3)
    assert found is not None
    P, i, s = found
    Q = P[:i] + (s,) + P[i + 1:]
    assert prefers(P[i], slater(Q, 3), slater(P, 3))


def test_larger_input():
    rng = random.Random(7)
    m = 14
    P = random_profile(rng, m, 9)
    r = slater_ranking(P, m)
    assert sorted(r) == list(range(m))
    c = slater_cost(P, m, r)
    for i in range(m - 1):
        s = r[:i] + (r[i + 1], r[i]) + r[i + 2:]
        assert slater_cost(P, m, s) >= c
    w = condorcet_winner(P, m)
    if w is not None:
        assert r[0] == w

History

Patrick Slater posed the problem in 1961 for paired comparisons, where a judge compares every pair of items and the comparisons may be inconsistent. He asked for the ranking with the fewest inconsistencies. The rule later became one of the standard tournament solutions in social choice. The minimum feedback arc set problem in tournaments was shown to be NP-hard in the mid-2000s, which settled the complexity of the Slater ranking and of the Slater winner. Work on approximation for the same problem gave KwikSort in 2005.

References

  1. Patrick Slater, Inconsistencies in a schedule of paired comparisons, Biometrika 48(3-4) (1961), 303-312, the problem of finding the ranking with the fewest inconsistencies with the outcomes of paired comparisons
  2. Felix Brandt, Vincent Conitzer, Ulle Endriss, Jérôme Lang and Ariel D. Procaccia (eds.), Handbook of Computational Social Choice, Cambridge University Press, 2016, Chapter 3 (Felix Brandt, Markus Brill and Paul Harrenstein, Tournament solutions): the Slater set and Theorem 3.3 on its NP-hardness; the top cycle (Smith set) and Theorem 3.8

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
  • at least three sources
  • a scene preset for the example