Algorithm Search⌘K

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
Properties
not comparison baseddeterministiciterative
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, "xx is above yy", unless the results already locked put yy above xx. 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 mm candidates A={0,…,m−1}A = \{0, \ldots, m - 1\} and nn voters with rankings r1,…,rnr_1, \ldots, r_n, each best first. Let nP(a,b)n_P(a, b) be the number of voters who rank aa above bb, and let the margin be g(a,b)=nP(a,b)−nP(b,a)g(a, b) = n_P(a, b) - n_P(b, a), so g(b,a)=−g(a,b)g(b, a) = -g(a, b). 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 tt of the candidates, by default 0,1,…,m−10, 1, \ldots, m - 1: among pairs with the same margin, the pair (x,y)(x, y) comes first when xx is earlier in tt, and then when yy is earlier in tt. With the default tt, ties go to the smaller index, as on every rule page of this area.

The algorithm

  1. RANKED-PAIRS(P, m, t) ▷ t is the tie-break ranking of the candidates
  2. 1g[x][y] ← n_P(x, y) - n_P(y, x) for all x ≠ y
  3. 2L ← the pairs (x, y) with g[x][y] ≥ 0, sorted by g[x][y] from largest to smallest, ties by t
  4. 3R[x][y] ← (x = y) for all x, y ▷ R is the transitive closure of the locked pairs
  5. 4for each (x, y) in L, in order do
  6. 5if R[y][x] then skip this pair ▷ locking x over y would close a cycle
  7. 6for each z with R[z][x] and not R[z][y]: R[z][w] ← true for each w with R[y][w]
  8. 7order ← the candidates sorted by |{w : R[x][w]}|, largest first
  9. 8return 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 LL. Line L5 is the cycle test: yy already reaches xx through locked pairs, so the pair xx over yy would close a cycle. Line L6 locks xx over yy and updates the transitive closure at once. Every zz that reaches xx now reaches all that yy reaches. A row zz that already reaches yy 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 O(m3)O(m^3) bound. At the end the closure is a linear order, and line L7 reads it off: the candidate in place kk from the top reaches exactly m−k+1m - k + 1 candidates, itself included.

Example

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

voters ranking
3 a≻b≻c≻da \succ b \succ c \succ d
6 c≻d≻a≻bc \succ d \succ a \succ b
11 b≻c≻d≻ab \succ c \succ d \succ a
6 c≻a≻b≻dc \succ a \succ b \succ d

The positive margins are g(c,d)=26g(c, d) = 26, g(c,a)=20g(c, a) = 20, g(b,d)=14g(b, d) = 14, g(d,a)=8g(d, a) = 8, g(a,b)=4g(a, b) = 4 and g(b,c)=2g(b, c) = 2. Every candidate loses some contest, so there is no Condorcet winner, and the majorities form the cycles a→b→d→aa \to b \to d \to a and b→c→a→bb \to c \to a \to b, among others.

step pair margin test of line L5 action
L4 to L6 cc over dd 26 dd does not reach cc lock
L4 to L6 cc over aa 20 aa does not reach cc lock
L4 to L6 bb over dd 14 dd does not reach bb lock
L4 to L6 dd over aa 8 aa does not reach dd lock
L4 to L6 aa over bb 4 b→d→ab \to d \to a is locked skip
L4 to L6 bb over cc 2 cc does not reach bb lock
L7 bb reaches 4, cc reaches 3, dd reaches 2, aa reaches 1

The ranking is b≻c≻d≻ab \succ c \succ d \succ a, and bb wins. The only result that is overruled is aa over bb, the weakest link of the cycle a→b→d→aa \to b \to d \to a. On the same profile the Schulze method elects cc: it compares bb and cc by their strongest paths, and the path c→a→bc \to a \to b has strength 4, more than the direct margin 2 of bb over cc. Ranked pairs keeps bb over cc, 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 RR is its reflexive transitive closure. Line L5 rejects exactly the pairs that would close a cycle, and line L6 adds to row zz the set reached by yy exactly when zz reaches xx, which is what the new pair adds to the closure. For every two candidates x≠yx \ne y, at least one of (x,y)(x, y) and (y,x)(y, x) is in LL. When it is processed, either it is locked, or line L5 finds that the other direction is already in RR. So at the end RR 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 O(m3)O(m^3) bound of the closure updates and proves the properties below.

Proof: Correctness and properties of ranked pairsfull

Let A={0,…,m−1}A = \{0, \ldots, m - 1\}, let PP be a profile of nn full rankings, and let g(x,y)=nP(x,y)−nP(y,x)g(x, y) = n_P(x, y) - n_P(y, x) be the margins. Fix the tie-break ranking tt. Order all ordered pairs (x,y)(x, y) with x≠yx \ne y by the key (−g(x,y),t(x),t(y))(-g(x, y), t(x), t(y)), where t(a)t(a) is the place of aa in tt. This is a strict total order, which we call priority: a pair with a smaller key has higher priority. The list LL of line L2 is the set of pairs with g≥0g \ge 0, in priority order. Write x→yx \to y for a locked pair, and RR 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 GG, and R[u][v]R[u][v] holds exactly when GG has a path from uu to vv (of length 0 when u=vu = v).

Proof. At the start GG has no edges and RR is the identity, by line L3. Take a pass for the pair (x,y)(x, y). If R[y][x]R[y][x], the pair is skipped and nothing changes. Otherwise the edge x→yx \to y is added. The new graph is acyclic: a cycle would use the new edge and a path from yy to xx in the old graph, but R[y][x]R[y][x] is false. A path in the new graph from zz to ww either avoids the new edge, or it is a path from zz to xx, then the edge, then a path from yy to ww; a path that uses the edge twice repeats xx, which is impossible in an acyclic graph. So the new reach set of zz is the old one, together with the reach set of yy when zz reaches xx. Line L6 adds exactly this for the rows zz with R[z][x]R[z][x] and not R[z][y]R[z][y]. For a row zz with R[z][x]R[z][x] and R[z][y]R[z][y], the reach set of yy is already contained in that of zz, because reach is transitive, so nothing needs to be added. Line L6 reads row yy while it changes other rows. Row yy itself is not changed in this pass: changing it would need R[y][x]R[y][x], which is false. So all rows get the right set.

Claim 2 (correctness). At the end, RR is a linear order on AA, and line L7 lists AA in this order, best first.

Proof. For x≠yx \ne y, one of g(x,y)g(x, y) and g(y,x)g(y, x) is at least 0, so one of (x,y)(x, y) and (y,x)(y, x) is in LL, say (x,y)(x, y). When it is processed, either R[y][x]R[y][x] already holds, or the edge x→yx \to y is locked and R[x][y]R[x][y] holds from then on. Entries of RR never go from true to false. So at the end R[x][y]R[x][y] or R[y][x]R[y][x] for every pair. By Claim 1, RR 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 mm elements, the element in place kk from the top is above exactly m−km - k others, so it reaches m−k+1m - k + 1 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 O(nm2+m3)O(n m^2 + m^3) time and O(m2)O(m^2) extra space.

Proof. Line L1 visits the m(m−1)/2m(m - 1)/2 ordered pairs of each ballot once, in O(nm2)O(n m^2) time. Line L2 sorts at most m(m−1)m(m - 1) pairs in O(m2log⁡m)O(m^2 \log m) time. Each pass of the loop does O(1)O(1) work in line L5 and scans mm rows in line L6, which is O(m3)O(m^3) over at most m2m^2 passes. A row zz gets the inner O(m)O(m) loop only when R[z][y]R[z][y] is false before the pass, and the update makes it true. Each of the m2m^2 entries goes from false to true at most once, so the inner loops take O(m3)O(m^3) time in all. Line L7 counts m2m^2 entries and sorts mm numbers. The matrices gg and RR and the list LL have O(m2)O(m^2) entries.

Claim 4 (Smith set on top). Let SS 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 SS above every candidate outside SS. In particular, a Condorcet winner, whose Smith set is {c}\{c\}, wins.

Proof. For x∈Sx \in S and y∉Sy \notin S, g(x,y)>0g(x, y) > 0, so g(y,x)<0g(y, x) < 0 and (y,x)∉L(y, x) \notin L. So no locked edge goes from outside SS into SS, and no path of GG does either: the first edge of such a path that enters SS would be such an edge. When (x,y)(x, y) is processed, R[y][x]R[y][x] is false, since it would need a path from y∉Sy \notin S to x∈Sx \in S. So x→yx \to y is locked and xx is above yy.

Claim 5 (Pareto). If n≥1n \ge 1 and every voter ranks aa above bb, then aa is above bb in the ranking.

Proof. g(a,b)=ng(a, b) = n, the largest possible margin. Suppose (a,b)(a, b) is skipped. Then a path b=u0→u1→⋯→uk=ab = u_0 \to u_1 \to \cdots \to u_k = a of locked edges exists when it is processed, and every edge of it was processed earlier, so g(ui−1,ui)≥ng(u_{i-1}, u_i) \ge n, which means g(ui−1,ui)=ng(u_{i-1}, u_i) = n: every voter ranks ui−1u_{i-1} above uiu_i. By transitivity of each voter's ranking, every voter ranks bb above aa, which contradicts n≥1n \ge 1. So (a,b)(a, b) is locked.

Claim 6 (anonymity, and neutrality with the tie-break). Reordering the voters does not change the result. For a permutation π\pi of AA, the ranking of πP\pi P with tie-break πt\pi t is the image under π\pi of the ranking of PP with tie-break tt.

Proof. The algorithm reads PP only through gg, which does not depend on the order of the voters. In πP\pi P, g′(πx,πy)=g(x,y)g'(\pi x, \pi y) = g(x, y), and the place of πx\pi x in πt\pi t is the place of xx in tt. So the key of (πx,πy)(\pi x, \pi y) in the renamed instance is the key of (x,y)(x, y), L′=πLL' = \pi L pair by pair, and the run on the renamed instance is the image of the run on PP under π\pi. With a fixed tie-break the resolute rule is not neutral: for the ballots (0,1)(0, 1) and (1,0)(1, 0), both pairs have margin 0, and (0,1)(0, 1) 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 LL by nP(x,y)n_P(x, y), with the same tie-break, gives the same list as sorting them by g(x,y)g(x, y).

Proof. nP(x,y)+nP(y,x)=nn_P(x, y) + n_P(y, x) = n, so nP(x,y)=(n+g(x,y))/2n_P(x, y) = (n + g(x, y))/2, an increasing function of g(x,y)g(x, y).

Claim 8 (monotonicity). Let rr be the ranking for PP with top ww, and let QQ be PP with ww moved up one place on one ballot, passing the candidate xx. Then the ranking for QQ with the same tie-break is rr, so ww still wins.

Proof. Only the pair {w,x}\{w, x\} changes: gQ(w,x)=g(w,x)+2g_Q(w, x) = g(w, x) + 2 and gQ(x,w)=g(x,w)−2g_Q(x, w) = g(x, w) - 2. So the priority of (w,x)(w, x) goes up, the priority of (x,w)(x, w) goes down, and the relative priority of any two other pairs is the same. Call a pair downward if it agrees with rr and upward otherwise. Since ww is the top of rr, (w,x)(w, x) is downward and (x,w)(x, w) is upward. Every locked edge of the run on PP is downward, by Claim 2.

Consider the run on QQ, with list LQL_Q. We show by induction over the passes that only downward pairs are locked. Then the closure RQR_Q is always contained in rr, so a downward pair is never skipped (that would need the upward reach RQ[y][x]R_Q[y][x]) and ends in RQR_Q. Let p=(z,y)p = (z, y) be an upward pair of LQL_Q. Then p≠(w,x)p \ne (w, x), gQ(p)≥0g_Q(p) \ge 0, and g(p)≥gQ(p)g(p) \ge g_Q(p), so p∈Lp \in L as well. In the run on PP, pp was skipped, so there was a path from yy to zz of edges locked before pp, all downward. Each such edge ee precedes pp in LQL_Q too: if neither is (w,x)(w, x) or (x,w)(x, w), their order is unchanged; if e=(w,x)e = (w, x), its priority only went up; if p=(x,w)p = (x, w), its priority only went down; and e≠(x,w)e \ne (x, w) because ee is downward. Each ee is downward, has gQ(e)≥g(e)≥0g_Q(e) \ge g(e) \ge 0, and so, by the induction hypothesis, is in RQR_Q when pp is processed. So RQ[y][z]R_Q[y][z] holds and pp is skipped. At the end, RQR_Q is a linear order by Claim 2 and is contained in the linear order rr, so RQ=rR_Q = r. ■\blacksquare

Complexity

Line L1 takes O(nm2)O(n m^2) time. Line L2 sorts at most m(m−1)m(m - 1) pairs in O(m2log⁡m)O(m^2 \log m) time. Line L5 takes O(1)O(1) time per pair. In line L6, the scan over zz takes O(m)O(m) time per locked pair, which is O(m3)O(m^3) in all. A row zz is rewritten in O(m)O(m) time only when R[z][y]R[z][y] goes from false to true, and this happens at most once for each of the m2m^2 entries, which is O(m3)O(m^3) in all. Line L7 takes O(m2)O(m^2) time. The total is O(nm2+m3)O(n m^2 + m^3) in the word RAM model, with O(m2)O(m^2) extra space for gg, LL and RR. A simpler version that tests each pair with a fresh depth-first search takes O(m2)O(m^2) time per pair, so O(m4)O(m^4) 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 LL, so nothing can ever lock an outsider above a member.
  • Pareto. If every voter ranks aa above bb, the margin nn of aa over bb is the largest possible, and a locked chain from bb to aa would need margins of nn all the way, which would make every voter rank bb above aa.
  • 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, nP(x,y)=(n+g(x,y))/2n_P(x, y) = (n + g(x, y))/2, 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 nP(x,y)n_P(x, y), 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 xx above yy in it, there is a chain from xx down to yy, inside the ranking, whose links all come before the pair (y,x)(y, x) 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 yy already reaches xx. Asking whether xx reaches yy 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.

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))
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

  1. 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
  2. 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
  3. 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)
  4. 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.

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