Algorithm Search⌘K

Algorithmcore

Copeland's method

Also called Copeland rule.

Ranks candidates by the number of pairwise majority contests they win minus those they lose. It is Condorcet consistent.

Time
O(n m^2) worst
Space
O(m^2) extra
Where
m = the number of candidates; n = the number of voters
Properties
not comparison baseddeterministiciterative
Origin
Ramon Llull, Arthur H. Copeland, 1951

Copeland's method elects the candidate that wins the most head-to-head majority contests. For each pair of candidates, it asks which one more voters rank higher, and it gives the winner of the pair one point and takes one point from the loser. The candidate with the highest total wins, and sorting by the totals gives a full ranking. A candidate that beats every rival, the Condorcet winner, scores m−1m - 1, which no other candidate can reach, so the method is Condorcet consistent. It is easy to explain and to compute, but it often ends in a tie at the top.

In plain words

Think of the election as a round-robin sports league. Every candidate plays every other candidate once. In each game, the voters decide: the candidate that more voters rank higher wins the game. A win earns a point, a loss costs a point, and a draw changes nothing. At the end, the candidate at the top of the league table wins. A candidate that beats all others wins every game, so it always comes first. When no such candidate exists, the table shows who wins the most games, but it does not care by how much a game was won, so two or more candidates often share the top place.

The problem

There are mm candidates A={0,…,m−1}A = \{0, \ldots, m - 1\} and nn voters, and voter ii has a ranking rir_i of all candidates, best first. For candidates a≠ba \ne b, let nP(a,b)n_P(a, b) be the number of voters who rank aa above bb. Candidate aa beats bb when nP(a,b)>nP(b,a)n_P(a, b) > n_P(b, a), and the pair is a tie when the two counts are equal. The Copeland score of aa is

sP(a)=∣{b:a beats b}∣−∣{b:b beats a}∣.s_P(a) = |\{ b : a \text{ beats } b \}| - |\{ b : b \text{ beats } a \}|.

The Copeland correspondence returns W(P)=arg⁡max⁡asP(a)W(P) = \arg\max_a s_P(a), and the resolute rule returns one element of W(P)W(P). Ties go to the candidate with the smallest index, as on every rule page of this area. The Copeland ranking sorts the candidates by sPs_P, highest first, with the same tie rule.

The algorithm

  1. COPELAND(P, m) ▷ P = (r_1, ..., r_n), each ranking best first
  2. 1N[a][b] ← number of voters who rank a above b, for all a ≠ b
  3. 2s[a] ← 0 for each candidate a
  4. 3for each pair a < b do
  5. 4if N[a][b] > N[b][a] then s[a] ← s[a] + 1; s[b] ← s[b] - 1
  6. 5else if N[b][a] > N[a][b] then s[b] ← s[b] + 1; s[a] ← s[a] - 1
  7. 6W ← {a : s[a] = max over b of s[b]} ▷ the Copeland correspondence
  8. 7return the smallest candidate in W ▷ the fixed tie-breaking rule

Line L1 builds the pairwise count matrix with one pass over each ballot: for a ballot, every candidate is above each candidate that comes later in it. Lines L3 to L5 play each pair once. A tied pair passes both tests of lines L4 and L5 and changes no score. Line L6 finds the candidates with the best record, and line L7 applies the tie-breaking rule. The code also returns the set WW and the full ranking.

Example

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

voter ranking
1 d≻a≻b≻cd \succ a \succ b \succ c
2 a≻b≻c≻da \succ b \succ c \succ d
3 b≻c≻d≻ab \succ c \succ d \succ a

Line L1 gives these pairwise results, each as the count for the first candidate against the count for the second: aa beats bb by 2 to 1, aa beats cc by 2 to 1, dd beats aa by 2 to 1, bb beats cc by 3 to 0, bb beats dd by 2 to 1, and cc beats dd by 2 to 1.

step pair winner s=(sa,sb,sc,sd)s = (s_a, s_b, s_c, s_d)
L2 (0,0,0,0)(0, 0, 0, 0)
L3 to L5 a,ba, b aa (1,−1,0,0)(1, -1, 0, 0)
L3 to L5 a,ca, c aa (2,−1,−1,0)(2, -1, -1, 0)
L3 to L5 a,da, d dd (1,−1,−1,1)(1, -1, -1, 1)
L3 to L5 b,cb, c bb (1,0,−2,1)(1, 0, -2, 1)
L3 to L5 b,db, d bb (1,1,−2,0)(1, 1, -2, 0)
L3 to L5 c,dc, d cc (1,1,−1,−1)(1, 1, -1, -1)
L6 W={a,b}W = \{a, b\}
L7 return aa

There is no Condorcet winner: aa loses to dd, and bb loses to aa. The majorities form the cycle a→b→d→aa \to b \to d \to a, and cc is on the cycle a→c→d→aa \to c \to d \to a, so the Smith set is all four candidates and gives no help. Copeland's method separates aa and bb, with two wins each, from cc and dd, with one win each. It cannot separate aa from bb, and the tie rule elects aa. The Copeland ranking is a,b,c,da, b, c, d.

Correctness

After line L1, N[a][b]=nP(a,b)N[a][b] = n_P(a, b), because each ballot adds 1 to N[a][b]N[a][b] exactly when it ranks aa above bb. The loop of lines L3 to L5 visits each unordered pair once. For the pair {a,b}\{a, b\} it adds 1 to the score of the candidate that wins the pair and subtracts 1 from the score of the other, and it does nothing on a tie. So at the end, s[a]s[a] is the number of wins of aa minus the number of its losses, which is sP(a)s_P(a). Line L6 builds W(P)W(P), which is not empty, and line L7 returns its smallest element. The proof in proofs/correctness.md writes this out and proves the properties below.

Proof: Correctness and properties of Copeland's methodfull

Let A={0,…,m−1}A = \{0, \ldots, m - 1\} with m≥1m \ge 1, and let P=(r1,…,rn)P = (r_1, \ldots, r_n) be a profile of rankings, each best first. Write nP(a,b)n_P(a, b) for the number of voters who rank aa above bb. Candidate aa beats bb when nP(a,b)>nP(b,a)n_P(a, b) > n_P(b, a). Let wP(a)w_P(a) and lP(a)l_P(a) be the numbers of candidates that aa beats and that beat aa, and let tP(a)=m−1−wP(a)−lP(a)t_P(a) = m - 1 - w_P(a) - l_P(a) be the number of ties of aa. The Copeland score is sP(a)=wP(a)−lP(a)s_P(a) = w_P(a) - l_P(a), the correspondence is W(P)={a:sP(a)=max⁡bsP(b)}W(P) = \{ a : s_P(a) = \max_b s_P(b) \}, and the resolute rule is f(P)=min⁡W(P)f(P) = \min W(P). For 0≤α≤10 \le \alpha \le 1, the Copelandα^\alpha score is cPα(a)=wP(a)+α tP(a)c^\alpha_P(a) = w_P(a) + \alpha\, t_P(a).

Claim 1 (correctness). COPELAND returns f(P)f(P).

Proof. Line L1: a ballot rr ranks aa above bb exactly when aa comes before bb in rr, so adding 1 to N[a][b]N[a][b] for each such ordered pair of each ballot gives N[a][b]=nP(a,b)N[a][b] = n_P(a, b). Loop of lines L3 to L5, invariant: after the pairs {a,b}\{a, b\} in a set FF have been processed, s[x]s[x] equals the number of pairs in FF that xx wins minus the number of pairs in FF that xx loses. It holds for F=∅F = \emptyset by line L2. Processing the pair {a,b}\{a, b\} changes only s[a]s[a] and s[b]s[b]. If aa beats bb, line L4 adds 1 to s[a]s[a] and subtracts 1 from s[b]s[b], which matches one more win of aa and one more loss of bb. If bb beats aa, line L5 does the reverse. If the pair is a tie, neither test holds and neither count changes. When every pair has been processed, s[a]=wP(a)−lP(a)=sP(a)s[a] = w_P(a) - l_P(a) = s_P(a). Line L6 builds W(P)W(P), which is nonempty since a maximum over the finite nonempty set AA is attained, and line L7 returns min⁡W(P)=f(P)\min W(P) = f(P).

Claim 2 (Copeland1/2^{1/2}). sP(a)=2cP1/2(a)−(m−1)s_P(a) = 2 c^{1/2}_P(a) - (m - 1) for every aa, so the Copeland score and the Copeland1/2^{1/2} score order the candidates in the same way.

Proof. 2cP1/2(a)−(m−1)=2wP(a)+tP(a)−wP(a)−lP(a)−tP(a)=wP(a)−lP(a)2 c^{1/2}_P(a) - (m - 1) = 2 w_P(a) + t_P(a) - w_P(a) - l_P(a) - t_P(a) = w_P(a) - l_P(a).

Claim 3 (anonymity and neutrality). WW does not change when the voters are reordered. For a permutation π\pi of AA and the renamed profile πP\pi P, W(πP)=π(W(P))W(\pi P) = \pi(W(P)).

Proof. nP(a,b)n_P(a, b) counts ballots with a property of the ballot alone, so it does not depend on their order. In πP\pi P, a voter ranks π(a)\pi(a) above π(b)\pi(b) exactly when the voter ranks aa above bb in PP, so nπP(π(a),π(b))=nP(a,b)n_{\pi P}(\pi(a), \pi(b)) = n_P(a, b). So π(a)\pi(a) beats π(b)\pi(b) in πP\pi P exactly when aa beats bb in PP, and sπP(π(a))=sP(a)s_{\pi P}(\pi(a)) = s_P(a). The two score vectors have the same maximum, and π(a)\pi(a) attains it in πP\pi P exactly when aa attains it in PP. The resolute rule is not neutral for m≥2m \ge 2: with the two ballots (0,1,2,…,m−1)(0, 1, 2, \ldots, m - 1) and (1,0,2,…,m−1)(1, 0, 2, \ldots, m - 1), candidates 0 and 1 tie with each other and have the same results against all others, the swap π\pi of 0 and 1 maps the profile to itself up to the order of the voters, and ff returns 0 on both, while π(0)=1\pi(0) = 1.

Claim 4 (Condorcet consistency). If cc is a Condorcet winner, then W(P)={c}W(P) = \{c\}.

Proof. cc beats all m−1m - 1 others, so sP(c)=m−1s_P(c) = m - 1. Every b≠cb \ne c loses to cc, so lP(b)≥1l_P(b) \ge 1 and wP(b)≤m−2w_P(b) \le m - 2, which gives sP(b)≤m−3<sP(c)s_P(b) \le m - 3 < s_P(c).

Claim 5 (Smith consistency). Let SS be the Smith set, the smallest nonempty set of candidates each of whom beats every candidate outside it. For every 0≤α≤10 \le \alpha \le 1, every a∈Sa \in S and every b∉Sb \notin S, cPα(a)>cPα(b)c^\alpha_P(a) > c^\alpha_P(b) and sP(a)>sP(b)s_P(a) > s_P(b). So W(P)⊆SW(P) \subseteq S.

Proof. Let k=∣S∣k = |S|. The candidate aa beats all m−km - k candidates outside SS, so cPα(a)≥m−kc^\alpha_P(a) \ge m - k. The candidate bb loses to each of the kk members of SS, so it can gain points only from the other m−k−1m - k - 1 candidates outside SS, at most 1 point from each, and cPα(b)≤m−k−1c^\alpha_P(b) \le m - k - 1. The claim for sPs_P follows by Claim 2 with α=1/2\alpha = 1/2. The set SS is not empty, so every b∉Sb \notin S has a lower score than some member of SS, and b∉W(P)b \notin W(P).

Claim 6 (Pareto). If every voter ranks aa above bb and n≥1n \ge 1, then sP(a)>sP(b)s_P(a) > s_P(b), so b∉W(P)b \notin W(P).

Proof. nP(a,b)=n>0=nP(b,a)n_P(a, b) = n > 0 = n_P(b, a), so aa beats bb. For any third candidate xx, every voter who ranks bb above xx ranks aa above xx too, so nP(a,x)≥nP(b,x)n_P(a, x) \ge n_P(b, x) and nP(x,a)≤nP(x,b)n_P(x, a) \le n_P(x, b). So the result of aa against xx is at least as good as the result of bb against xx, in the order loss, tie, win. The contribution of xx to sP(a)s_P(a) is at least its contribution to sP(b)s_P(b). The pair {a,b}\{a, b\} contributes +1+1 to sP(a)s_P(a) and −1-1 to sP(b)s_P(b). Adding up gives sP(a)≥sP(b)+2s_P(a) \ge s_P(b) + 2.

Claim 7 (monotonicity). Let w∈W(P)w \in W(P), and let QQ be PP with one ballot changed by moving ww up one place, passing the candidate xx, with all other relative orders kept. Then w∈W(Q)w \in W(Q) and W(Q)⊆W(P)W(Q) \subseteq W(P). So f(P)=wf(P) = w implies f(Q)=wf(Q) = w.

Proof. Only the counts of the pair {w,x}\{w, x\} change: nQ(w,x)=nP(w,x)+1n_Q(w, x) = n_P(w, x) + 1 and nQ(x,w)=nP(x,w)−1n_Q(x, w) = n_P(x, w) - 1. So the result of ww against xx moves up or stays (loss to tie or win, tie to win), and nothing else changes for ww. This gives sQ(w)≥sP(w)s_Q(w) \ge s_P(w). For xx the result against ww moves down or stays, so sQ(x)≤sP(x)s_Q(x) \le s_P(x), and every other score is the same. So sQ(w)≥sP(w)≥sP(y)≥sQ(y)s_Q(w) \ge s_P(w) \ge s_P(y) \ge s_Q(y) for each yy, and w∈W(Q)w \in W(Q). If y∈W(Q)y \in W(Q) with y≠wy \ne w, then sP(y)≥sQ(y)≥sQ(w)≥sP(w)=max⁡sPs_P(y) \ge s_Q(y) \ge s_Q(w) \ge s_P(w) = \max s_P, so y∈W(P)y \in W(P). If ww is the smallest element of W(P)W(P), it is then also the smallest element of W(Q)W(Q). Every raise of ww that keeps the other relative orders is a chain of such moves.

Claim 8 (ties with four candidates). If nn is odd, m=4m = 4 and there is no Condorcet winner, then ∣W(P)∣≥2|W(P)| \ge 2.

Proof. With nn odd there are no tied pairs, so sP(a)=2wP(a)−3s_P(a) = 2 w_P(a) - 3 and the wins add up to the 6 pairs. No candidate has 3 wins. Four numbers in {0,1,2}\{0, 1, 2\} with sum 6 have at least two entries equal to 2: with at most one entry equal to 2 the sum is at most 2+1+1+1=52 + 1 + 1 + 1 = 5. So at least two candidates have the top score.

Claim 9 (time). COPELAND runs in O(nm2)O(n m^2) time and O(m2)O(m^2) extra space.

Proof. Line L1 touches each of the m(m−1)/2m(m - 1)/2 ordered pairs of each of the nn ballots once, in O(1)O(1) time each, after O(m2)O(m^2) time to clear the matrix. Lines L3 to L5 do O(1)O(1) work for each of the m(m−1)/2m(m - 1)/2 pairs. Lines L6 and L7 scan mm scores. The matrix has m2m^2 entries, and the scores and WW take O(m)O(m) space. ■\blacksquare

Complexity

Line L1 does O(m2)O(m^2) work for each ballot, since a ballot of mm candidates has m(m−1)/2m(m - 1)/2 ordered pairs, so it takes O(nm2)O(n m^2) time. Lines L3 to L5 take O(m2)O(m^2) time and lines L6 and L7 take O(m)O(m) time. The total is O(nm2)O(n m^2) in the word RAM model, and the extra space is the m×mm \times m matrix. When the pairwise matrix is given, the method takes O(m2)O(m^2) time, which is linear in the size of the majority graph; this is Theorem 3.2 of the chapter on tournament solutions in the Handbook of Computational Social Choice.

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.

  • Anonymous, and neutral as a correspondence. The counts nP(a,b)n_P(a, b) do not depend on the order of the voters, and renaming the candidates renames the scores. The resolute rule is not neutral, because of the tie rule.
  • Condorcet consistent. A Condorcet winner scores m−1m - 1, and every other candidate loses to it and so scores at most m−3m - 3.
  • Smith consistent. Every member of the Smith set scores strictly more than every candidate outside it. So the winners are in the Smith set, and the Copeland ranking puts the Smith set first.
  • Pareto. If every voter ranks aa above bb, then aa beats bb, and aa does at least as well as bb against every third candidate, so sP(a)>sP(b)s_P(a) > s_P(b).
  • Monotone. Raising the winner ww on one ballot can only turn a loss of ww into a tie or a win, or a tie into a win. No other score goes up.
  • Not strategyproof. With 3 candidates and 3 voters, some voter can get a better winner by a false ranking, as the Gibbard-Satterthwaite theorem says must happen for some profile.
  • Many ties. When the number of voters is odd, the majority relation is a tournament, and with 4 candidates and no Condorcet winner the top two scores are always equal. The tie rule then decides the election.
  • Metric distortion 5. When voters and candidates are points in a metric space, the winner's total distance to the voters is at most 5 times the best possible total (Anshelevich, Bhardwaj, Elkind, Postl and Skowron, 2018). See metric distortion.

Variants and improvements

  • Copeland with a parameter for ties. Copelandα^\alpha gives 1 point for a win and α\alpha points for a tie, with 0≤α≤10 \le \alpha \le 1. The score of line L4 and line L5 is 2⋅2 \cdot Copeland1/2−(m−1)^{1/2} - (m - 1), so it orders the candidates as Copeland1/2^{1/2} does. Copeland1^1 is the rule of Ramon Llull. The choice of α\alpha matters only when nn is even, and it changes the control results for adding candidates (Faliszewski, Hemaspaandra, Hemaspaandra and Rothe, 2009).
  • Second-order Copeland. Break ties by the sum of the Copeland scores of the candidates that each tied candidate beats. Bartholdi, Tovey and Trick (1989) proved that a manipulation by one voter is NP-hard to find for this version, while plain Copeland is easy to manipulate.
  • Margin-based rules. Ranked pairs and the Schulze method also use the sizes of the majorities, so they have far fewer ties.
  • Slater and Kemeny. The Slater rule looks for a ranking that disagrees with the fewest majority contests. Copeland's ranking is a fast heuristic for it.

When to use it

Use Copeland's method when you want a Condorcet method that anyone can check with a table of head-to-head results, as in a sports league, or when you need a winner in the Smith set at a low cost. Add a tie-break rule that the voters accept, such as the Borda count or second-order Copeland, because with few candidates the top place is often shared. If the size of the majorities should count, use ranked pairs or the Schulze method.

Pitfalls

  • An unstated tie rule. Line L7 decides many elections. Return the set WW of line L6 when the caller must see the ties.
  • Counting only wins. A score of wins alone is Copeland0^0. It treats a tie like a loss, and when nn is even it can elect a different candidate than wins minus losses. Say which α\alpha the code uses.
  • Ties in the count. A pair with nP(a,b)=nP(b,a)n_P(a, b) = n_P(b, a) is a tie, and it must not count as a win for the candidate that comes first in the loop.
  • Partial ballots. If a ballot does not rank every candidate, decide whether a ranked candidate is above an unranked one. Line L1 assumes full rankings.

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))
copeland_method.py 76 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/copeland-method/. The authors are listed in prov/D4PRR4.jsonl.

from fractions import Fraction
from typing import Sequence

Ranking = Sequence[int]


def pairwise_counts(profile: Sequence[Ranking], m: int) -> list[list[int]]:
    """Return N with N[a][b] the number of voters who rank a above b. Time O(n m^2)."""
    N = [[0] * m for _ in range(m)]  # @line L1
    for r in profile:
        for i, a in enumerate(r):
            for b in r[i + 1:]:
                N[a][b] += 1
    return N


def copeland_scores(profile: Sequence[Ranking], m: int) -> list[int]:
    """Return s with s[a] the number of majority contests a wins minus the number it loses.

    A contest with N[a][b] == N[b][a] is a tie and counts for neither side.
    """
    N = pairwise_counts(profile, m)
    s = [0] * m  # @line L2
    for a in range(m):  # @line L3
        for b in range(a + 1, m):
            if N[a][b] > N[b][a]:  # @line L4
                s[a] += 1
                s[b] -= 1
            elif N[b][a] > N[a][b]:  # @line L5
                s[b] += 1
                s[a] -= 1
    return s


def copeland_winners(profile: Sequence[Ranking], m: int) -> frozenset[int]:
    """Return the set of candidates with the highest Copeland score (the correspondence)."""
    s = copeland_scores(profile, m)
    best = max(s)
    return frozenset(a for a in range(m) if s[a] == best)  # @line L6


def copeland(profile: Sequence[Ranking], m: int) -> int:
    """Return the Copeland winner; a tie goes to the candidate with the smallest index.

    Precondition: m >= 1. Time O(n m^2), extra space O(m^2).
    """
    return min(copeland_winners(profile, m))  # @line L7


def copeland_ranking(profile: Sequence[Ranking], m: int) -> tuple[int, ...]:
    """Return the candidates sorted by Copeland score, highest first, ties to the smaller index."""
    s = copeland_scores(profile, m)
    return tuple(sorted(range(m), key=lambda a: (-s[a], a)))


def copeland_alpha_scores(profile: Sequence[Ranking], m: int, alpha: Fraction) -> list[Fraction]:
    """Return the Copeland^alpha scores: 1 for each win and alpha for each tie, 0 <= alpha <= 1.

    For alpha = 1/2 the score is (m - 1 + s[a]) / 2 with s the score of copeland_scores, so it
    orders the candidates in the same way.
    """
    N = pairwise_counts(profile, m)
    out = []
    for a in range(m):
        t = Fraction(0)
        for b in range(m):
            if b != a:
                if N[a][b] > N[b][a]:
                    t += 1
                elif N[a][b] == N[b][a]:
                    t += alpha
        out.append(t)
    return out
test_copeland_method.py 135 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/copeland-method/. The authors are listed in prov/D4PRR4.jsonl.

import random
from fractions import Fraction
from itertools import combinations

from agtprefs import (all_profiles, check_anonymity, check_condorcet_consistency,
                      check_monotonicity, check_neutrality, check_pareto, condorcet_winner,
                      find_manipulation, margins, pairwise, prefers, random_profile)
from copeland_method import (copeland, copeland_alpha_scores, copeland_ranking, copeland_scores,
                             copeland_winners, pairwise_counts)

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

# The worked example of the page: three voters and the cycle a > b > d > a.
EXAMPLE = ((D, A, B, C), (A, B, C, D), (B, C, D, A))


def smith_set(P, m):
    """The smallest set whose members all beat every outsider, by brute force over subsets."""
    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 samples(seed, m, n, count):
    rng = random.Random(seed)
    return [random_profile(rng, m, n) for _ in range(count)]


def test_example():
    assert pairwise_counts(EXAMPLE, 4) == [[0, 2, 2, 1], [1, 0, 3, 2], [1, 0, 0, 2], [2, 1, 1, 0]]
    assert copeland_scores(EXAMPLE, 4) == [1, 1, -1, -1]
    assert copeland_winners(EXAMPLE, 4) == frozenset({A, B})
    assert copeland(EXAMPLE, 4) == A
    assert copeland_ranking(EXAMPLE, 4) == (A, B, C, D)
    assert condorcet_winner(EXAMPLE, 4) is None
    assert smith_set(EXAMPLE, 4) == frozenset({A, B, C, D})


def test_condorcet_cycle_ties_everyone():
    cycle = ((A, B, C), (B, C, A), (C, A, B))
    assert copeland_scores(cycle, 3) == [0, 0, 0]
    assert copeland_winners(cycle, 3) == frozenset({A, B, C})
    assert copeland(cycle, 3) == A


def test_edge_cases():
    assert copeland((), 1) == 0
    assert copeland_winners((), 3) == frozenset({0, 1, 2})
    assert copeland(((2, 0, 1),), 3) == 2
    assert copeland(((0, 1), (1, 0)), 2) == 0
    assert copeland_winners(((0, 1), (1, 0)), 2) == frozenset({0, 1})


def test_scores_match_definition():
    rng = random.Random(1)
    for _ in range(300):
        m, n = rng.randint(1, 6), rng.randint(0, 7)
        P = random_profile(rng, m, n)
        assert pairwise_counts(P, m) == pairwise(P, m)
        M = margins(P, m)
        s = copeland_scores(P, m)
        for a in range(m):
            wins = sum(1 for b in range(m) if M[a][b] > 0)
            losses = sum(1 for b in range(m) if M[a][b] < 0)
            assert s[a] == wins - losses
        assert sum(s) == 0
        half = copeland_alpha_scores(P, m, Fraction(1, 2))
        for a in range(m):
            assert 2 * half[a] == m - 1 + s[a]
        r = copeland_ranking(P, m)
        assert sorted(r) == list(range(m))
        assert r[0] == copeland(P, m)
        assert all(s[r[i]] >= s[r[i + 1]] for i in range(m - 1))


def test_smith_members_outscore_outsiders():
    rng = random.Random(2)
    for _ in range(400):
        m, n = rng.randint(2, 6), rng.randint(1, 7)
        P = random_profile(rng, m, n)
        S = smith_set(P, m)
        for alpha in (Fraction(0), Fraction(1, 2), Fraction(1)):
            t = copeland_alpha_scores(P, m, alpha)
            assert all(t[a] > t[b] for a in S for b in range(m) if b not in S)
        assert copeland_winners(P, m) <= S


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


def test_axioms_on_random_profiles():
    for m, n, seed in ((4, 5, 3), (5, 4, 4), (6, 7, 5)):
        Ps = samples(seed, m, n, 150)
        assert check_anonymity(copeland_winners, m, n, Ps) is None
        assert check_neutrality(copeland_winners, m, n, Ps) is None
        assert check_pareto(copeland_winners, m, n, Ps) is None
        assert check_condorcet_consistency(copeland, m, n, Ps) is None
        assert check_monotonicity(copeland_winners, m, n, Ps) is None


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


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


def test_large_input():
    rng = random.Random(6)
    P = random_profile(rng, 40, 31)
    s = copeland_scores(P, 40)
    assert sum(s) == 0
    assert copeland(P, 40) in copeland_winners(P, 40)
    assert sum(1 for _ in all_profiles(2, 2)) == 4

History

Ramon Llull, in the 13th century, described an election in which each pair of candidates is compared and the candidate with the most pairwise wins is elected, which is Copeland1^1. Condorcet in 1785 argued for the candidate who wins every pairwise contest. Arthur H. Copeland proposed the rule with wins minus losses in 1951, in mimeographed notes for a seminar at the University of Michigan. In computational social choice, Bartholdi, Tovey and Trick showed in 1989 that one voter can find a manipulation in polynomial time, and Faliszewski, Hemaspaandra, Hemaspaandra and Rothe showed in 2009 that the rule resists the standard types of constructive control.

References

  1. 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), Section 3.3, the Copeland set and Theorem 3.2 (it can be computed in linear time)
  2. Arthur H. Copeland, A reasonable social welfare function, mimeographed notes, Seminar on Applications of Mathematics to the Social Sciences, University of Michigan, 1951, the rule that ranks candidates by pairwise wins minus pairwise losses
  3. Piotr Faliszewski, Edith Hemaspaandra, Lane A. Hemaspaandra and Jörg Rothe, Llull and Copeland voting computationally resist bribery and constructive control, Journal of Artificial Intelligence Research 35 (2009), 275-341, the Copeland^alpha family, and the proof that for every rational alpha with 0 < alpha < 1 it resists all standard types of constructive control
  4. Elliot Anshelevich, Onkar Bhardwaj, Edith Elkind, John Postl and Piotr Skowron, Approximating optimal social choice under metric preferences, Artificial Intelligence 264 (2018), 27-51, the upper bound of 5 on the metric distortion of Copeland
  5. John J. Bartholdi III, Craig A. Tovey and Michael A. Trick, The computational difficulty of manipulating an election, Social Choice and Welfare 6(3) (1989), 227-241, the greedy algorithm that finds a manipulation by one voter, and the NP-hardness of manipulating Copeland with the second-order Copeland tie-break

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