Algorithmcore
Ranked pairs
Also called Tideman method.
Locks in pairwise majorities from the largest margin down, skipping any that would form a cycle, and elects the source of the result.
- Time
- O(n m^2 + m^3) worst
- Space
- O(m^2) extra
- Where
- m = the number of candidates; n = the number of voters
- Model
- Word RAM
- Properties
- not comparison baseddeterministiciterative
- Evidence
- Proof sketchCode in 1 languages
- Origin
- T. Nicolaus Tideman, Thomas M. Zavist, 1987
Ranked pairs is a Condorcet method that builds a ranking from the strongest majorities down. It sorts the pairwise contests by the size of the winning margin, then goes down the list and locks in each result, " is above ", unless the results already locked put above . The locked results form a ranking, and its top candidate wins. A Condorcet winner is never overruled, and when the majorities form a cycle, the weakest majority in the cycle is the one that is dropped. Tideman proposed it in 1987, and it is one of the few common rules that is independent of clones.
In plain words
Look at every pair of candidates and see which one more voters prefer, and by how much. Sort these results from the clearest win to the narrowest. Then build the final order one result at a time, starting with the clearest. Each new result is written down unless it contradicts what is already written down, either directly or through a chain such as "A above B and B above C" against "C above A". At the end every pair is settled, and the candidate at the top is the winner. The idea is that a big majority is more reliable than a small one, so when majorities disagree in a circle, the smallest one gives way.
The problem
There are candidates and voters with rankings , each best first. Let be the number of voters who rank above , and let the margin be , so . The output is a ranking of all candidates and its top candidate, the winner. Equal margins must be ordered by a tie-breaking rule. Here it is a tie-break ranking of the candidates, by default : among pairs with the same margin, the pair comes first when is earlier in , and then when is earlier in . With the default , ties go to the smaller index, as on every rule page of this area.
The algorithm
RANKED-PAIRS(P, m, t) ▷ t is the tie-break ranking of the candidates- 1
g[x][y] ← n_P(x, y) - n_P(y, x) for all x ≠ y - 2
L ← the pairs (x, y) with g[x][y] ≥ 0, sorted by g[x][y] from largest to smallest, ties by t - 3
R[x][y] ← (x = y) for all x, y ▷ R is the transitive closure of the locked pairs - 4
for each (x, y) in L, in order do - 5
if R[y][x] then skip this pair ▷ locking x over y would close a cycle - 6
for each z with R[z][x] and not R[z][y]: R[z][w] ← true for each w with R[y][w] - 7
order ← the candidates sorted by |{w : R[x][w]}|, largest first - 8
return order, and order[1] as the winner
Line L2 keeps both directions of a pair with margin 0, so every pair of candidates has at least one entry in . Line L5 is the cycle test: already reaches through locked pairs, so the pair over would close a cycle. Line L6 locks over and updates the transitive closure at once. Every that reaches now reaches all that reaches. A row that already reaches already reaches all of that, so only the other rows are changed. This is the incremental closure of Ibaraki and Katoh that the Handbook of Computational Social Choice uses for the bound. At the end the closure is a linear order, and line L7 reads it off: the candidate in place from the top reaches exactly candidates, itself included.
Example
Take four candidates (indices 0 to 3) and 26 voters:
| voters | ranking |
|---|---|
| 3 | |
| 6 | |
| 11 | |
| 6 |
The positive margins are , , , , and . Every candidate loses some contest, so there is no Condorcet winner, and the majorities form the cycles and , among others.
| step | pair | margin | test of line L5 | action |
|---|---|---|---|---|
| L4 to L6 | over | 26 | does not reach | lock |
| L4 to L6 | over | 20 | does not reach | lock |
| L4 to L6 | over | 14 | does not reach | lock |
| L4 to L6 | over | 8 | does not reach | lock |
| L4 to L6 | over | 4 | is locked | skip |
| L4 to L6 | over | 2 | does not reach | lock |
| L7 | reaches 4, reaches 3, reaches 2, reaches 1 |
The ranking is , and wins. The only result that is overruled is over , the weakest link of the cycle . On the same profile the Schulze method elects : it compares and by their strongest paths, and the path has strength 4, more than the direct margin 2 of over . Ranked pairs keeps over , because that result does not contradict anything locked before it. So the two methods, which agree on most profiles, are different rules.
Correctness
Each pass of the loop keeps two facts: the locked pairs form an acyclic graph, and is its reflexive transitive closure. Line L5 rejects exactly the pairs that would close a cycle, and line L6 adds to row the set reached by exactly when reaches , which is what the new pair adds to the closure. For every two candidates , at least one of and is in . When it is processed, either it is locked, or line L5 finds that the other direction is already in . So at the end relates every pair one way and, being acyclic, is a linear order, which line L7 lists. The proof in proofs/correctness.md writes this out, proves the bound of the closure updates and proves the properties below.
Proof: Correctness and properties of ranked pairsfull
Let , let be a profile of full rankings, and let be the margins. Fix the tie-break ranking . Order all ordered pairs with by the key , where is the place of in . This is a strict total order, which we call priority: a pair with a smaller key has higher priority. The list of line L2 is the set of pairs with , in priority order. Write for a locked pair, and for the matrix of lines L3 to L6.
Claim 1 (invariant). Before and after each pass of the loop of lines L4 to L6, the locked pairs form an acyclic directed graph , and holds exactly when has a path from to (of length 0 when ).
Proof. At the start has no edges and is the identity, by line L3. Take a pass for the pair . If , the pair is skipped and nothing changes. Otherwise the edge is added. The new graph is acyclic: a cycle would use the new edge and a path from to in the old graph, but is false. A path in the new graph from to either avoids the new edge, or it is a path from to , then the edge, then a path from to ; a path that uses the edge twice repeats , which is impossible in an acyclic graph. So the new reach set of is the old one, together with the reach set of when reaches . Line L6 adds exactly this for the rows with and not . For a row with and , the reach set of is already contained in that of , because reach is transitive, so nothing needs to be added. Line L6 reads row while it changes other rows. Row itself is not changed in this pass: changing it would need , which is false. So all rows get the right set.
Claim 2 (correctness). At the end, is a linear order on , and line L7 lists in this order, best first.
Proof. For , one of and is at least 0, so one of and is in , say . When it is processed, either already holds, or the edge is locked and holds from then on. Entries of never go from true to false. So at the end or for every pair. By Claim 1, is the reach relation of an acyclic graph, so it is reflexive, transitive and antisymmetric. A reflexive, transitive, antisymmetric and total relation is a linear order. In a linear order of elements, the element in place from the top is above exactly others, so it reaches candidates, itself included. These counts differ, so sorting by them in line L7 lists the order. Line L8 returns its top.
Claim 3 (time). RANKED-PAIRS runs in time and extra space.
Proof. Line L1 visits the ordered pairs of each ballot once, in time. Line L2 sorts at most pairs in time. Each pass of the loop does work in line L5 and scans rows in line L6, which is over at most passes. A row gets the inner loop only when is false before the pass, and the update makes it true. Each of the entries goes from false to true at most once, so the inner loops take time in all. Line L7 counts entries and sorts numbers. The matrices and and the list have entries.
Claim 4 (Smith set on top). Let be the Smith set, the smallest nonempty set of candidates each of whom beats every candidate outside it. Then the ranking puts every member of above every candidate outside . In particular, a Condorcet winner, whose Smith set is , wins.
Proof. For and , , so and . So no locked edge goes from outside into , and no path of does either: the first edge of such a path that enters would be such an edge. When is processed, is false, since it would need a path from to . So is locked and is above .
Claim 5 (Pareto). If and every voter ranks above , then is above in the ranking.
Proof. , the largest possible margin. Suppose is skipped. Then a path of locked edges exists when it is processed, and every edge of it was processed earlier, so , which means : every voter ranks above . By transitivity of each voter's ranking, every voter ranks above , which contradicts . So is locked.
Claim 6 (anonymity, and neutrality with the tie-break). Reordering the voters does not change the result. For a permutation of , the ranking of with tie-break is the image under of the ranking of with tie-break .
Proof. The algorithm reads only through , which does not depend on the order of the voters. In , , and the place of in is the place of in . So the key of in the renamed instance is the key of , pair by pair, and the run on the renamed instance is the image of the run on under . With a fixed tie-break the resolute rule is not neutral: for the ballots and , both pairs have margin 0, and comes first and is locked, both for the profile and for its image under the swap of 0 and 1.
Claim 7 (margins and winning votes). With full rankings, sorting the pairs of by , with the same tie-break, gives the same list as sorting them by .
Proof. , so , an increasing function of .
Claim 8 (monotonicity). Let be the ranking for with top , and let be with moved up one place on one ballot, passing the candidate . Then the ranking for with the same tie-break is , so still wins.
Proof. Only the pair changes: and . So the priority of goes up, the priority of goes down, and the relative priority of any two other pairs is the same. Call a pair downward if it agrees with and upward otherwise. Since is the top of , is downward and is upward. Every locked edge of the run on is downward, by Claim 2.
Consider the run on , with list . We show by induction over the passes that only downward pairs are locked. Then the closure is always contained in , so a downward pair is never skipped (that would need the upward reach ) and ends in . Let be an upward pair of . Then , , and , so as well. In the run on , was skipped, so there was a path from to of edges locked before , all downward. Each such edge precedes in too: if neither is or , their order is unchanged; if , its priority only went up; if , its priority only went down; and because is downward. Each is downward, has , and so, by the induction hypothesis, is in when is processed. So holds and is skipped. At the end, is a linear order by Claim 2 and is contained in the linear order , so .
Complexity
Line L1 takes time. Line L2 sorts at most pairs in time. Line L5 takes time per pair. In line L6, the scan over takes time per locked pair, which is in all. A row is rewritten in time only when goes from false to true, and this happens at most once for each of the entries, which is in all. Line L7 takes time. The total is in the word RAM model, with extra space for , and . A simpler version that tests each pair with a fresh depth-first search takes time per pair, so in all.
Properties
The proofs are in proofs/correctness.md, and the tests check each property by brute force over all profiles with up to 4 candidates and few voters, and on random profiles with up to 6 candidates.
- Condorcet and Smith consistent. The ranking puts the Smith set on top, so a Condorcet winner always wins. A pair from outside the Smith set into it has a negative margin and is never in , so nothing can ever lock an outsider above a member.
- Pareto. If every voter ranks above , the margin of over is the largest possible, and a locked chain from to would need margins of all the way, which would make every voter rank above .
- Anonymous. Only the margins are used.
- Neutral, up to the tie-break. Renaming the candidates and the tie-break ranking in the same way renames the result. With a fixed tie-break ranking the rule is not neutral.
- Monotone. Raising the winner on a ballot leaves the whole ranking the same. Every pair that was skipped is still skipped, because the chain that blocked it is locked again, and no earlier.
- Independent of clones. Adding a candidate that is next to an existing candidate on every ballot does not change which of the other candidates wins, with the tie-break rule of Zavist and Tideman.
- Not strategyproof. Some voter can gain by a false ranking with 3 candidates and 3 voters. Xia, Zuckerman, Procaccia, Conitzer and Rosenschein showed in 2009 that finding a manipulation is NP-hard for ranked pairs, even for one voter.
- Margins and winning votes agree on full rankings. With full rankings, , so sorting by the number of winning votes gives the same order of pairs as sorting by margin.
Variants and improvements
- Winning votes. Many descriptions sort the pairs by , the number of voters on the winning side. With full rankings this is the same order. With ballots that leave candidates unranked, the two versions differ.
- All tie-breaks. The neutral correspondence takes every candidate that wins for some order of the tied pairs. Brill and Fischer (2012) proved that deciding whether a candidate is in this set is NP-complete. The code computes the winner for one given tie-break ranking.
- Stack characterization. A ranking is the ranked pairs ranking exactly when, for each pair with above in it, there is a chain from down to , inside the ranking, whose links all come before the pair in the order of line L2, with the pairs of negative margin placed last. This is Lemma 4.14 in the Handbook, after Zavist and Tideman. The tests check it by brute force.
- Strongest paths. The Schulze method uses strongest paths in place of the greedy locking. The example shows that they can differ.
When to use it
Use ranked pairs for a Condorcet method whose count is easy to explain step by step and that gives a full ranking. It suits committees and online polls with full ballots and a moderate number of candidates. It is also a good choice when clones are a concern, for example when one party can nominate several similar candidates. If the electorate already uses the Schulze method, keep it: both rules are Condorcet and clone consistent, and they rarely differ.
Pitfalls
- Dropping pairs with margin 0. If line L2 keeps only positive margins, a tied pair may stay unsettled, and the locked relation is not a full ranking. Keep both directions of a tied pair, or rank the leftover pairs by another rule.
- An unstated tie rule. Equal margins are common with few voters, and the order of tied pairs can change the winner. State the tie-break ranking, as line L2 does.
- Testing the wrong direction. Line L5 must ask whether already reaches . Asking whether reaches rejects the pairs that are already implied, which are harmless, and misses the ones that close a cycle.
- Electing the candidate with no locked defeat too early. The winner is the source of the final graph. A candidate with no locked defeat after part of the list may still get one later, so read the winner only after all pairs are processed.
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.
# 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))
ranked_pairs.py 82 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/ranked-pairs/. The authors are listed in prov/XQFZVT.jsonl.
from typing import Optional, 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 pair_order(M: list[list[int]], tiebreak: Sequence[int]) -> list[tuple[int, int, int]]:
"""Return the ordered pairs (g, x, y) with g = M[x][y] >= 0, in the order of locking.
Larger margins come first. Pairs with equal margins are ordered by the tie-breaking ranking
tiebreak: first by the place of x in it, then by the place of y.
"""
m = len(M)
place = {a: i for i, a in enumerate(tiebreak)}
pairs = [(M[x][y], x, y) for x in range(m) for y in range(m) if x != y and M[x][y] >= 0]
pairs.sort(key=lambda p: (-p[0], place[p[1]], place[p[2]]))
return pairs
def ranked_pairs_ranking(profile: Sequence[Ranking], m: int,
tiebreak: Optional[Sequence[int]] = None) -> tuple[int, ...]:
"""Return the ranked pairs ranking of the candidates, best first.
Ties between equal margins are broken by tiebreak, a ranking of the candidates; the default
is 0, 1, ..., m - 1. Time O(n m^2 + m^3), extra space O(m^2).
"""
if tiebreak is None:
tiebreak = tuple(range(m))
M = margin_matrix(profile, m) # @line L1
pairs = pair_order(M, tiebreak) # @line L2
reach = [[x == y for y in range(m)] for x in range(m)] # @line L3
for _, x, y in pairs: # @line L4
if reach[y][x]: # @line L5
continue
row_y = reach[y]
for z in range(m): # @line L6
rz = reach[z]
if rz[x] and not rz[y]:
for w in range(m):
if row_y[w]:
rz[w] = True
below = [sum(reach[x]) for x in range(m)]
return tuple(sorted(range(m), key=lambda x: -below[x])) # @line L7
def ranked_pairs(profile: Sequence[Ranking], m: int,
tiebreak: Optional[Sequence[int]] = None) -> int:
"""Return the ranked pairs winner: the top of ranked_pairs_ranking. Precondition: m >= 1."""
return ranked_pairs_ranking(profile, m, tiebreak)[0] # @line L8
def locked_edges(profile: Sequence[Ranking], m: int,
tiebreak: Optional[Sequence[int]] = None) -> list[tuple[int, int]]:
"""Return the locked pairs (x, y), meaning x over y, in the order in which they were locked."""
if tiebreak is None:
tiebreak = tuple(range(m))
M = margin_matrix(profile, m)
reach = [[x == y for y in range(m)] for x in range(m)]
out = []
for _, x, y in pair_order(M, tiebreak):
if reach[y][x]:
continue
out.append((x, y))
for z in range(m):
if reach[z][x] and not reach[z][y]:
for w in range(m):
if reach[y][w]:
reach[z][w] = True
return out
test_ranked_pairs.py 185 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/ranked-pairs/. The authors are listed in prov/XQFZVT.jsonl.
import random
from itertools import combinations, permutations
from agtprefs import (all_rankings, check_anonymity, check_condorcet_consistency,
check_monotonicity, check_neutrality, check_pareto, condorcet_winner,
find_manipulation, margins, permute_profile, prefers, random_profile)
from ranked_pairs import locked_edges, margin_matrix, pair_order, ranked_pairs, ranked_pairs_ranking
A, B, C, D = 0, 1, 2, 3
# The worked example of the page: 26 voters in four groups.
EXAMPLE = ((A, B, C, D),) * 3 + ((C, D, A, B),) * 6 + ((B, C, D, A),) * 11 + ((C, A, B, D),) * 6
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 naive_ranked_pairs(P, m, tiebreak):
"""Lock pairs one by one and test for a cycle by a fresh depth-first search each time."""
M = margins(P, m)
place = {a: i for i, a in enumerate(tiebreak)}
pairs = sorted(((x, y) for x in range(m) for y in range(m) if x != y and M[x][y] >= 0),
key=lambda e: (-M[e[0]][e[1]], place[e[0]], place[e[1]]))
succ = {x: set() for x in range(m)}
def reaches(u, v):
seen, stack = {u}, [u]
while stack:
z = stack.pop()
if z == v:
return True
for w in succ[z]:
if w not in seen:
seen.add(w)
stack.append(w)
return False
for x, y in pairs:
if not reaches(y, x):
succ[x].add(y)
return tuple(sorted(range(m), key=lambda x: -sum(reaches(x, y) for y in range(m))))
def stack_rankings(P, m, tiebreak):
"""All rankings with the stack property of Zavist and Tideman, by brute force."""
M = margins(P, m)
place = {a: i for i, a in enumerate(tiebreak)}
def key(x, y):
return (-M[x][y], place[x], place[y])
out = []
for r in all_rankings(m):
ok = True
for i in range(m):
for j in range(i + 1, m):
bound = key(r[j], r[i])
reach = {i}
for t in range(i + 1, j + 1):
if any(key(r[s], r[t]) <= bound for s in reach):
reach.add(t)
if j not in reach:
ok = False
break
if not ok:
break
if ok:
out.append(r)
return out
def rp_all_tiebreaks(P, m):
"""The winners of ranked pairs over every tie-breaking ranking of the candidates."""
return frozenset(ranked_pairs(P, m, t) for t in permutations(range(m)))
def test_example():
M = margin_matrix(EXAMPLE, 4)
assert M[A][B] == 4 and M[C][A] == 20 and M[D][A] == 8
assert M[B][C] == 2 and M[B][D] == 14 and M[C][D] == 26
assert condorcet_winner(EXAMPLE, 4) is None
assert [(x, y) for _, x, y in pair_order(M, (0, 1, 2, 3))] == [(C, D), (C, A), (B, D), (D, A),
(A, B), (B, C)]
assert locked_edges(EXAMPLE, 4) == [(C, D), (C, A), (B, D), (D, A), (B, C)]
assert ranked_pairs_ranking(EXAMPLE, 4) == (B, C, D, A)
assert ranked_pairs(EXAMPLE, 4) == B
assert rp_all_tiebreaks(EXAMPLE, 4) == frozenset({B})
def test_edge_cases():
assert ranked_pairs_ranking((), 1) == (0,)
assert ranked_pairs_ranking((), 3) == (0, 1, 2)
assert ranked_pairs_ranking((), 3, (2, 0, 1)) == (2, 0, 1)
assert ranked_pairs_ranking(((2, 0, 1),), 3) == (2, 0, 1)
cycle = ((A, B, C), (B, C, A), (C, A, B))
assert ranked_pairs_ranking(cycle, 3) == (A, B, C)
# With the tie-break c, b, a the pairs are locked in the order (c, a), (b, c), (a, b).
assert ranked_pairs_ranking(cycle, 3, (2, 1, 0)) == (B, C, A)
def test_matches_naive_and_stack_property():
rng = random.Random(1)
for _ in range(250):
m, n = rng.randint(1, 5), rng.randint(0, 8)
P = random_profile(rng, m, n)
t = tuple(rng.sample(range(m), m))
r = ranked_pairs_ranking(P, m, t)
assert r == naive_ranked_pairs(P, m, t)
assert sorted(r) == list(range(m))
for x, y in locked_edges(P, m, t):
assert prefers(r, x, y)
if m <= 4:
assert stack_rankings(P, m, t) == [r]
def test_smith_set_comes_first():
rng = random.Random(2)
for _ in range(300):
m, n = rng.randint(1, 6), rng.randint(1, 9)
P = random_profile(rng, m, n)
S = smith_set(P, m)
r = ranked_pairs_ranking(P, m, tuple(rng.sample(range(m), m)))
assert set(r[:len(S)]) == S
def test_axioms_on_full_domains():
for m, n in ((2, 3), (3, 1), (3, 2), (3, 3), (3, 4), (4, 1), (4, 2)):
assert check_anonymity(ranked_pairs, m, n) is None
assert check_pareto(ranked_pairs, m, n) is None
assert check_condorcet_consistency(ranked_pairs, m, n) is None
assert check_monotonicity(ranked_pairs, m, n) is None
assert check_neutrality(rp_all_tiebreaks, m, n) is None
def test_axioms_on_random_profiles():
for m, n, seed in ((4, 5, 3), (5, 6, 4), (6, 7, 5)):
rng = random.Random(seed)
Ps = [random_profile(rng, m, n) for _ in range(120)]
assert check_anonymity(ranked_pairs, m, n, Ps) is None
assert check_pareto(ranked_pairs, m, n, Ps) is None
assert check_condorcet_consistency(ranked_pairs, m, n, Ps) is None
assert check_monotonicity(ranked_pairs, m, n, Ps) is None
def test_neutral_when_the_tie_break_is_renamed():
rng = random.Random(6)
for _ in range(300):
m, n = rng.randint(1, 6), rng.randint(0, 8)
P = random_profile(rng, m, n)
t = tuple(rng.sample(range(m), m))
pi = tuple(rng.sample(range(m), m))
r = ranked_pairs_ranking(P, m, t)
renamed = ranked_pairs_ranking(permute_profile(P, pi), m, tuple(pi[a] for a in t))
assert renamed == tuple(pi[a] for a in r)
def test_resolute_rule_is_not_neutral():
assert ranked_pairs(((A, B), (B, A)), 2) == A
assert check_neutrality(ranked_pairs, 2, 2) is not None
def test_manipulation_exists():
found = find_manipulation(ranked_pairs, 3, 3)
assert found is not None
P, i, s = found
Q = P[:i] + (s,) + P[i + 1:]
assert prefers(P[i], ranked_pairs(Q, 3), ranked_pairs(P, 3))
def test_large_input():
rng = random.Random(7)
P = random_profile(rng, 40, 25)
r = ranked_pairs_ranking(P, 40)
assert sorted(r) == list(range(40))
M = margin_matrix(P, 40)
assert all(M[a][b] == -M[b][a] for a in range(40) for b in range(40))
History
T. Nicolaus Tideman introduced ranked pairs in 1987 in a paper that also defined independence of clones: a rule should not change its winner among the other candidates when a candidate is replaced by a set of similar candidates. Ranked pairs met this condition except in some cases with ties, and Thomas M. Zavist and Tideman added a tie-break ranking of the candidates in 1989 that makes it fully independent of clones. In computational social choice, Xia and coauthors showed in 2009 that manipulation is NP-hard, and Brill and Fischer showed in 2012 that the neutral version over all tie-breaks is NP-hard to compute.
References
- T. Nicolaus Tideman, Independence of clones as a criterion for voting rules, Social Choice and Welfare 4(3) (1987), 185-206, the definition of the ranked pairs rule and the independence of clones criterion
- Thomas M. Zavist and T. Nicolaus Tideman, Complete independence of clones in the ranked pairs rule, Social Choice and Welfare 6(2) (1989), 167-173, the tie-breaking ranking of the candidates that makes ranked pairs completely independent of clones
- 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 4 (Felix Fischer, Olivier Hudry and Rolf Niedermeier, Weighted tournament solutions), Section 4.5.3, the O(m^3) bound with an incremental transitive closure, Lemma 4.14 (the stack characterization) and Theorem 4.15 (NP-completeness over all tie-breaks)
- Markus Brill and Felix Fischer, The price of neutrality for the ranked pairs method, Proceedings of the 26th AAAI Conference on Artificial Intelligence (AAAI 2012), 1299-1305, the proof that deciding whether a candidate wins ranked pairs for some tie-breaking order is NP-complete
About this page
The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.
| Ladder | Level | What the next level needs |
|---|---|---|
| Human proof | H1 sketch |
|
| Lean | L0 no Lean part |
|
| Code (python) | I0 not checked yet |
|
| Visual | V0 none |
|
| Writing | W2 basic |
|
Tag XQFZVT Edit this page History Report an error Markdown