Algorithm Search⌘K

Algorithmcore

Schulze method

Also called beatpath method, Schwartz sequential dropping.

Elects the candidate whose strongest path of pairwise majorities to each rival is at least as strong as the reverse, using the widest path variant of Floyd-Warshall.

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
Markus Schulze, 1997

The Schulze method is a Condorcet method that settles majority cycles by looking at chains of majorities. Candidate aa has a path to bb when aa beats some c1c_1, c1c_1 beats c2c_2, and so on, until the last one beats bb. The strength of a path is its weakest majority. The method compares the strongest path from aa to bb with the strongest path from bb to aa, and elects a candidate that is never worse in this comparison. All strongest paths together are a widest path problem, which a version of Floyd-Warshall solves in O(m3)O(m^3) time. The Wikimedia Foundation and several Pirate Parties use the method.

In plain words

Two candidates may be linked not only by their own head-to-head result but also through others: if most voters prefer A to B and most prefer B to C, then A has a chain of wins that leads to C. A chain is only as strong as its narrowest win. For each pair of candidates, the method finds the strongest chain in each direction and lets the stronger direction decide. A candidate wins if no rival has a stronger chain against it than it has against that rival. One such candidate always exists. A candidate that beats everyone directly always wins, and when wins go round in a circle, the narrowest win in the circle counts the least.

The problem

There are mm candidates A={0,…,m−1}A = \{0, \ldots, m - 1\} and nn voters with rankings, each best first. Let nP(a,b)n_P(a, b) be the number of voters who rank aa above bb, and g(a,b)=nP(a,b)−nP(b,a)g(a, b) = n_P(a, b) - n_P(b, a) the margin. The weighted majority graph has a link a→ba \to b of strength g(a,b)g(a, b) whenever g(a,b)>0g(a, b) > 0. The strength of a path is the smallest strength of its links, and p(a,b)p(a, b) is the largest strength of a path from aa to bb, or 0 if there is none. Candidate aa beats bb in the Schulze relation when p(a,b)>p(b,a)p(a, b) > p(b, a). The Schulze winners are the candidates that no other candidate beats in this relation: W(P)={a:p(a,b)≥p(b,a) for all b≠a}W(P) = \{ a : p(a, b) \ge p(b, a) \text{ for all } b \ne a \}. Ties go to the candidate with the smallest index, as on every rule page of this area.

The algorithm

  1. SCHULZE(P, m)
  2. 1g[a][b] ← n_P(a, b) - n_P(b, a) for all a ≠ b
  3. 2p[a][b] ← g[a][b] if g[a][b] > 0, else 0, for all a ≠ b
  4. 3for k ← 0 to m - 1 do
  5. 4for each i ≠ k with p[i][k] > 0, and each j ∉ {i, k} do
  6. 5p[i][j] ← max(p[i][j], min(p[i][k], p[k][j]))
  7. 6W ← {a : p[a][b] ≥ p[b][a] for every b ≠ a}
  8. 7return the smallest candidate in W

Line L2 keeps only the links of the weighted majority graph. Lines L3 to L5 are Floyd-Warshall with the sum replaced by the minimum and the minimum replaced by the maximum: a path through kk is as strong as the weaker of its two halves, and p[i][j]p[i][j] keeps the stronger of the old value and the new path. The test p[i][k]>0p[i][k] > 0 skips rows where no path through kk can help. Line L6 collects the candidates that no rival beats, and line L7 applies the tie rule. The code also returns a full ranking: it repeatedly takes the smallest remaining candidate that no remaining candidate beats.

Example

Take four candidates a,b,c,da, b, c, d (indices 0 to 3) and 26 voters, the profile of the example on the ranked pairs page:

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 links of line L2 are c→dc \to d (26), c→ac \to a (20), b→db \to d (14), d→ad \to a (8), a→ba \to b (4) and b→cb \to c (2). There is no Condorcet winner. The loop of lines L3 to L5 improves these entries:

round kk new paths
aa p[c][b]=4p[c][b] = 4 by c→a→bc \to a \to b; p[d][b]=4p[d][b] = 4 by d→a→bd \to a \to b
bb p[a][c]=2p[a][c] = 2 by a→b→ca \to b \to c; p[a][d]=4p[a][d] = 4 by a→b→da \to b \to d; p[d][c]=2p[d][c] = 2 by d→a→b→cd \to a \to b \to c
cc p[b][a]=2p[b][a] = 2 by b→c→ab \to c \to a
dd p[b][a]=8p[b][a] = 8 by b→d→ab \to d \to a

The final strengths, row xx and column yy for p[x][y]p[x][y]:

aa bb cc dd
aa 4 2 4
bb 8 2 14
cc 20 4 26
dd 8 4 2

Candidate cc beats aa (20 against 2), bb (4 against 2) and dd (26 against 2), so W={c}W = \{c\} and cc wins. The ranking is c≻b≻d≻ac \succ b \succ d \succ a. The direct result between bb and cc favours bb by 2, but cc reaches bb through aa with strength 4. Ranked pairs keeps the direct result and elects bb on this profile, so the two methods are different rules.

Correctness

After round kk of the loop, p[i][j]p[i][j] is the strength of the strongest path from ii to jj whose inner candidates are all among the first k+1k + 1 candidates. This is the invariant of Floyd-Warshall, and it holds for the bottleneck measure because a strongest path through kk consists of a strongest path to kk and a strongest path from kk, and the strength of a walk with a repeated candidate is at most the strength of the path that cuts out the loop. After the last round, p[i][j]=p(i,j)p[i][j] = p(i, j). The Schulze relation is transitive, so some candidate is beaten by no one and WW is not empty. The proof in proofs/correctness.md writes this out and proves the properties below.

Proof: Correctness and properties of the Schulze methodfull

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. The weighted majority graph has a link x→yx \to y of strength g(x,y)g(x, y) when g(x,y)>0g(x, y) > 0. All link strengths are positive. The strength of a walk is the smallest strength of its links, and p(x,y)p(x, y) is the largest strength of a path from xx to yy, or 0 if there is none. Write x≻Syx \succ_S y when p(x,y)>p(y,x)p(x, y) > p(y, x).

Claim 1 (walks). If there is a walk from xx to y≠xy \ne x of strength ss, then p(x,y)≥sp(x, y) \ge s. So p(x,z)≥min⁡(p(x,y),p(y,z))p(x, z) \ge \min(p(x, y), p(y, z)) for distinct x,y,zx, y, z.

Proof. If the walk visits a candidate twice, remove the part between the two visits. The result is a shorter walk from xx to yy whose links are a subset of the old links, so its strength is at least ss. Repeat until no candidate repeats; the result is a path. For the second part, if p(x,y)=0p(x, y) = 0 or p(y,z)=0p(y, z) = 0, the bound holds because p(x,z)≥0p(x, z) \ge 0. Otherwise join a strongest path from xx to yy and one from yy to zz into a walk of strength min⁡(p(x,y),p(y,z))\min(p(x, y), p(y, z)).

Claim 2 (invariant). For k=0,…,mk = 0, \ldots, m, let pk(i,j)p_k(i, j) be the largest strength of a path from ii to jj whose inner candidates are all less than kk, or 0 if there is none. After kk rounds of the loop of lines L3 to L5, p[i][j]=pk(i,j)p[i][j] = p_k(i, j) for all i≠ji \ne j. In particular, at the end p[i][j]=p(i,j)p[i][j] = p(i, j).

Proof. For k=0k = 0, a path without inner candidates is a single link, and line L2 sets p[i][j]p[i][j] to its strength, or to 0. Assume the claim after kk rounds, and take round kk (the candidate kk is the inner candidate that becomes allowed). Lines L4 and L5 never change an entry in row kk or in column kk, so during the round p[i][k]=pk(i,k)p[i][k] = p_k(i, k) and p[k][j]=pk(k,j)p[k][j] = p_k(k, j). A path from ii to jj with inner candidates less than k+1k + 1 either does not pass through kk, and then its strength is at most pk(i,j)p_k(i, j), or it is a path from ii to kk followed by a path from kk to jj, both with inner candidates less than kk, and then its strength is at most min⁡(pk(i,k),pk(k,j))\min(p_k(i, k), p_k(k, j)). Conversely, joining a path from ii to kk and a path from kk to jj gives a walk from ii to jj; by the argument of Claim 1, it contains a path from ii to jj with at least the same strength, and its inner candidates are still less than k+1k + 1. So pk+1(i,j)=max⁡(pk(i,j),min⁡(pk(i,k),pk(k,j)))p_{k+1}(i, j) = \max(p_k(i, j), \min(p_k(i, k), p_k(k, j))), which is what line L5 computes. When p[i][k]=0p[i][k] = 0 the minimum is 0 and no update is needed, so line L4 may skip row ii.

Claim 3 (transitivity). If a≻Sba \succ_S b and b≻Scb \succ_S c for distinct a,b,ca, b, c, then a≻Sca \succ_S c.

Proof. Suppose p(c,a)≥p(a,c)p(c, a) \ge p(a, c). By Claim 1, p(a,c)≥min⁡(p(a,b),p(b,c))p(a, c) \ge \min(p(a, b), p(b, c)).

If p(a,b)≤p(b,c)p(a, b) \le p(b, c), then p(c,a)≥p(a,c)≥p(a,b)p(c, a) \ge p(a, c) \ge p(a, b), and Claim 1 gives p(b,a)≥min⁡(p(b,c),p(c,a))≥p(a,b)p(b, a) \ge \min(p(b, c), p(c, a)) \ge p(a, b). This contradicts a≻Sba \succ_S b.

If p(b,c)<p(a,b)p(b, c) < p(a, b), then p(c,a)≥p(a,c)≥p(b,c)p(c, a) \ge p(a, c) \ge p(b, c), and Claim 1 gives p(c,b)≥min⁡(p(c,a),p(a,b))≥p(b,c)p(c, b) \ge \min(p(c, a), p(a, b)) \ge p(b, c). This contradicts b≻Scb \succ_S c.

So p(a,c)>p(c,a)p(a, c) > p(c, a).

Claim 4 (correctness). The set WW of line L6 is the set of Schulze winners, and it is not empty. The ranking of the code lists every candidate once, and no candidate in it is beaten by a candidate below it.

Proof. By Claim 2, line L6 tests p(a,b)≥p(b,a)p(a, b) \ge p(b, a) for all b≠ab \ne a, which is the definition. The relation ≻S\succ_S is asymmetric and, by Claim 3, transitive, so it has no cycle. In a finite set with an acyclic relation, some element is beaten by no other; so W≠∅W \ne \emptyset. The same holds for the restriction of ≻S\succ_S to any nonempty set of candidates, so the ranking loop always finds a candidate to take. When it takes rir_i, every later rjr_j is still left, so rjr_j does not beat rir_i.

Claim 5 (Smith consistency). Let SS be the Smith set, the smallest nonempty set of candidates each of whom has a positive margin over every candidate outside it. Then x≻Syx \succ_S y for every x∈Sx \in S and y∉Sy \notin S. So W⊆SW \subseteq S, and a Condorcet winner is the only winner.

Proof. For x∈Sx \in S and y∉Sy \notin S, g(x,y)>0g(x, y) > 0, so there is no link from yy to xx. A path from outside SS to a member of SS has a first link that enters SS, and no such link exists. So p(y,x)=0<g(x,y)≤p(x,y)p(y, x) = 0 < g(x, y) \le p(x, y). A Condorcet winner cc has S={c}S = \{c\}.

Claim 6 (Pareto). If n≥1n \ge 1 and every voter ranks aa above bb, then a≻Sba \succ_S b, so b∉Wb \notin W.

Proof. No margin exceeds nn, so no strength does. The link a→ba \to b has strength nn, so p(a,b)=np(a, b) = n. If p(b,a)=np(b, a) = n, a path b=u0→u1→⋯→uk=ab = u_0 \to u_1 \to \cdots \to u_k = a has g(ui−1,ui)=ng(u_{i-1}, u_i) = n for every link, so every voter ranks ui−1u_{i-1} above uiu_i, and by transitivity of each ballot every voter ranks bb above aa. This contradicts n≥1n \ge 1. So p(b,a)<n=p(a,b)p(b, a) < n = p(a, b).

Claim 7 (anonymity and neutrality). Reordering the voters does not change WW. For a permutation π\pi of AA, the winner set of πP\pi P is πW\pi W.

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), so the graph of πP\pi P is the image of the graph of PP, p′(πx,πy)=p(x,y)p'(\pi x, \pi y) = p(x, y), and line L6 selects πW\pi W. The resolute rule of line L7 is not neutral: for the ballots (0,1)(0, 1) and (1,0)(1, 0), W={0,1}W = \{0, 1\} for the profile and for its image under the swap of 0 and 1, and line L7 returns 0 in both cases.

Claim 8 (monotonicity). Let w∈W(P)w \in W(P), and let QQ be PP with ww moved up one place on one ballot, passing the candidate xx. Then w∈W(Q)w \in W(Q).

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. Write pQp_Q for the strengths in QQ. A path that starts at ww never enters ww again, so it does not use the link x→wx \to w. A strongest path from ww to any bb in PP is a path in QQ too, with the same or a stronger link w→xw \to x, so pQ(w,b)≥p(w,b)p_Q(w, b) \ge p(w, b). A path that ends at ww never leaves ww before, so it does not use the link w→xw \to x. A strongest path from any bb to ww in QQ is a path in PP too, since a link x→wx \to w in QQ has g(x,w)=gQ(x,w)+2>0g(x, w) = g_Q(x, w) + 2 > 0, and each of its links is at least as strong in PP; so p(b,w)≥pQ(b,w)p(b, w) \ge p_Q(b, w). Then pQ(w,b)≥p(w,b)≥p(b,w)≥pQ(b,w)p_Q(w, b) \ge p(w, b) \ge p(b, w) \ge p_Q(b, w) for every b≠wb \ne w.

Claim 9 (winning votes). With full rankings, the link strengths nP(x,y)n_P(x, y) for g(x,y)>0g(x, y) > 0 give the same relation ≻S\succ_S.

Proof. nP(x,y)=(n+g(x,y))/2n_P(x, y) = (n + g(x, y))/2, an increasing function ff of the margin, and ff commutes with min⁡\min and max⁡\max. So every path strength, and every p(x,y)p(x, y) that is not 0, is mapped by ff, and ff is larger than 0 on positive margins. Comparisons between two values of pp are therefore the same under both strengths.

Claim 10 (time). SCHULZE 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 pairs of each ballot once, in O(nm2)O(n m^2) time. Line L2 and line L6 take O(m2)O(m^2) time. Lines L3 to L5 do O(1)O(1) work for each of at most m3m^3 triples. The matrices gg and pp have m2m^2 entries. ■\blacksquare

Complexity

Line L1 takes O(nm2)O(n m^2) time, line L2 takes O(m2)O(m^2) and the three nested loops of lines L3 to L5 take O(m3)O(m^3). Line L6 takes O(m2)O(m^2). 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; the update of line L5 can be done in place, as in Floyd-Warshall. Real elections have few candidates, so the cubic loop is fast in practice.

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 7 candidates.

  • The relation is transitive. If aa beats bb and bb beats cc, then aa beats cc. So WW is never empty, and the relation extends to a ranking.
  • Condorcet and Smith consistent. No path leads from outside the Smith set into it, so every member beats every outsider in the Schulze relation.
  • Pareto. If every voter ranks aa above bb, then aa beats bb in the Schulze relation.
  • Anonymous, and neutral as a correspondence. Only the margins are used, and renaming the candidates renames them. The resolute rule is not neutral, because of the tie rule.
  • Monotone. Raising a winner on one ballot can only make its outgoing links stronger and its incoming links weaker, so it stays a winner.
  • Independent of clones and reversal symmetric. Schulze proved both: adding a near copy of a candidate does not change which of the others wins, and if every ballot is reversed, a unique winner does not stay the winner.
  • No participation. By Moulin's theorem, every Condorcet consistent rule, this one included, has profiles with at least 4 candidates where a voter does better by not voting.
  • Margins and winning votes agree on full rankings. Schulze often uses the number of winning votes nP(a,b)n_P(a, b) as the link strength. With full rankings it is (n+g(a,b))/2(n + g(a, b))/2, an increasing function of the margin, so both give the same relation.

Variants and improvements

  • Winning votes and other strengths. With ballots that leave candidates unranked, link strengths by winning votes, by margins or by ratios give different rules. Schulze recommends winning votes.
  • Sequential dropping. Repeatedly restrict to the Schwartz set, the union of the minimal sets that no outsider beats, and drop the weakest remaining link. This is how the method was first described. The procedure is close to the path form, but the two are not always the same rule.
  • Ranked pairs. Ranked pairs locks majorities greedily from the strongest down. Both rules are Condorcet consistent, monotone and independent of clones, and the example shows that they can disagree.
  • Proportional and multiwinner forms. Schulze also defined a proportional ranking and a multiwinner version based on the same path strengths.

When to use it

Use the Schulze method for single-winner elections with ranked ballots when you want a Condorcet winner whenever there is one, a defensible choice when there is not, and resistance to clones. Its count is easy to automate and to audit, since the strongest path table can be published. If voters must follow the count by hand, ranked pairs or Copeland's method is easier to explain.

Pitfalls

  • Keeping negative links. Line L2 must set p[a][b]=0p[a][b] = 0 when g(a,b)≤0g(a, b) \le 0. A negative entry as a link makes min⁡\min pick it, and then the maximum of line L5 can prefer a path that uses a lost contest.
  • Loop order. The intermediate candidate kk must be the outermost loop, as in Floyd-Warshall. With kk inside, some paths are never found.
  • Testing only one direction. A Schulze winner is a candidate with p[a][b]≥p[b][a]p[a][b] \ge p[b][a] for every bb. A candidate with the largest row sum or the largest single entry is not the same thing.
  • An unstated tie rule. With few voters, WW often has several members. State the tie rule of line L7, or return WW.

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

from typing import Sequence

Ranking = Sequence[int]


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


def strongest_paths(profile: Sequence[Ranking], m: int) -> list[list[int]]:
    """Return p with p[a][b] the strength of the strongest path from a to b.

    A link a -> b has strength M[a][b] when M[a][b] > 0, and there is no link otherwise. The
    strength of a path is its weakest link, and p[a][b] = 0 when there is no path. The
    diagonal is not used. Time O(n m^2 + m^3).
    """
    M = margin_matrix(profile, m)  # @line L1
    p = [[M[a][b] if M[a][b] > 0 else 0 for b in range(m)] for a in range(m)]  # @line L2
    for k in range(m):  # @line L3
        pk = p[k]
        for i in range(m):  # @line L4
            if i == k:
                continue
            pik = p[i][k]
            if pik == 0:
                continue
            pi = p[i]
            for j in range(m):
                if j != i and j != k:
                    via = pik if pik < pk[j] else pk[j]
                    if via > pi[j]:  # @line L5
                        pi[j] = via
    return p


def schulze_winners(profile: Sequence[Ranking], m: int) -> frozenset[int]:
    """Return the Schulze winners: the a with p[a][b] >= p[b][a] for every b."""
    p = strongest_paths(profile, m)
    return frozenset(a for a in range(m)  # @line L6
                     if all(p[a][b] >= p[b][a] for b in range(m) if b != a))


def schulze(profile: Sequence[Ranking], m: int) -> int:
    """Return the Schulze winner; a tie goes to the candidate with the smallest index."""
    return min(schulze_winners(profile, m))  # @line L7


def schulze_ranking(profile: Sequence[Ranking], m: int) -> tuple[int, ...]:
    """Return a ranking that extends the Schulze relation (a above b when p[a][b] > p[b][a]).

    It repeatedly takes the smallest candidate that no remaining candidate beats.
    """
    p = strongest_paths(profile, m)
    left = set(range(m))
    out = []
    while left:
        top = min(a for a in left if all(p[a][b] >= p[b][a] for b in left if b != a))
        out.append(top)
        left.remove(top)
    return tuple(out)
test_schulze_method.py 156 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/schulze-method/. The authors are listed in prov/PFHMFN.jsonl.

import random
from itertools import combinations, permutations

from agtprefs import (check_anonymity, check_condorcet_consistency, check_monotonicity,
                      check_neutrality, check_pareto, condorcet_winner, find_manipulation, margins,
                      pairwise, prefers, random_profile)
from schulze_method import margin_matrix, schulze, schulze_ranking, schulze_winners, strongest_paths

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 brute_paths(weight, m):
    """Strongest paths by trying every simple path; weight[a][b] is 0 when there is no link."""
    p = [[0] * m for _ in range(m)]
    for a in range(m):
        for b in range(m):
            if a == b:
                continue
            others = [c for c in range(m) if c not in (a, b)]
            for k in range(len(others) + 1):
                for mid in permutations(others, k):
                    path = (a,) + mid + (b,)
                    s = min(weight[path[i]][path[i + 1]] for i in range(len(path) - 1))
                    p[a][b] = max(p[a][b], s)
    return p


def winning_votes_winners(P, m):
    N = pairwise(P, m)
    w = [[N[a][b] if N[a][b] > N[b][a] else 0 for b in range(m)] for a in range(m)]
    p = brute_paths(w, m)
    return frozenset(a for a in range(m) if all(p[a][b] >= p[b][a] for b in range(m) if b != a))


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
    p = strongest_paths(EXAMPLE, 4)
    assert [p[A][B], p[A][C], p[A][D]] == [4, 2, 4]
    assert [p[B][A], p[B][C], p[B][D]] == [8, 2, 14]
    assert [p[C][A], p[C][B], p[C][D]] == [20, 4, 26]
    assert [p[D][A], p[D][B], p[D][C]] == [8, 4, 2]
    assert schulze_winners(EXAMPLE, 4) == frozenset({C})
    assert schulze(EXAMPLE, 4) == C
    assert schulze_ranking(EXAMPLE, 4) == (C, B, D, A)


def test_edge_cases():
    assert schulze((), 1) == 0
    assert schulze_winners((), 3) == frozenset({0, 1, 2})
    assert schulze(((2, 0, 1),), 3) == 2
    cycle = ((A, B, C), (B, C, A), (C, A, B))
    assert schulze_winners(cycle, 3) == frozenset({A, B, C})
    assert schulze_ranking(cycle, 3) == (A, B, C)


def test_matches_brute_force_paths():
    rng = random.Random(1)
    for _ in range(200):
        m, n = rng.randint(1, 5), rng.randint(0, 9)
        P = random_profile(rng, m, n)
        M = margin_matrix(P, m)
        assert M == margins(P, m)
        d = [[M[a][b] if M[a][b] > 0 else 0 for b in range(m)] for a in range(m)]
        p = strongest_paths(P, m)
        q = brute_paths(d, m)
        assert all(p[a][b] == q[a][b] for a in range(m) for b in range(m) if a != b)
        assert schulze_winners(P, m) == winning_votes_winners(P, m)


def test_relation_is_transitive_and_has_winners():
    rng = random.Random(2)
    for _ in range(400):
        m, n = rng.randint(1, 7), rng.randint(0, 9)
        P = random_profile(rng, m, n)
        p = strongest_paths(P, m)

        def beats(a, b):
            return p[a][b] > p[b][a]

        for a in range(m):
            for b in range(m):
                for c in range(m):
                    if len({a, b, c}) == 3 and beats(a, b) and beats(b, c):
                        assert beats(a, c)
        W = schulze_winners(P, m)
        assert W
        assert W <= smith_set(P, m)
        r = schulze_ranking(P, m)
        assert sorted(r) == list(range(m))
        assert r[0] == schulze(P, m)
        for i in range(m):
            for j in range(i + 1, m):
                assert not beats(r[j], r[i])


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(schulze_winners, m, n) is None
        assert check_neutrality(schulze_winners, m, n) is None
        assert check_pareto(schulze_winners, m, n) is None
        assert check_condorcet_consistency(schulze_winners, m, n) is None
        assert check_monotonicity(schulze_winners, m, n) is None
        assert check_monotonicity(schulze, 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(schulze_winners, m, n, Ps) is None
        assert check_neutrality(schulze_winners, m, n, Ps) is None
        assert check_pareto(schulze_winners, m, n, Ps) is None
        assert check_condorcet_consistency(schulze_winners, m, n, Ps) is None
        assert check_monotonicity(schulze_winners, m, n, Ps) is None


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


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


def test_large_input():
    rng = random.Random(7)
    P = random_profile(rng, 40, 25)
    p = strongest_paths(P, 40)
    W = schulze_winners(P, 40)
    assert W
    for a in W:
        assert all(p[a][b] >= p[b][a] for b in range(40) if b != a)
    assert schulze_ranking(P, 40)[0] == schulze(P, 40)

History

Markus Schulze described the method in 1997 on a mailing list about election methods, first as a procedure that drops the weakest links one by one, and soon in its path form. It was adopted by many organizations that vote online, among them the Wikimedia Foundation and several Pirate Parties. Schulze published the full analysis in 2011, with proofs of transitivity, monotonicity, independence of clones and reversal symmetry, and with the cubic algorithm. In computational social choice, Parkes and Xia in 2012 and Gaspers and coauthors in 2013 showed that a manipulation by one voter can be found in polynomial time.

References

  1. Markus Schulze, A new monotonic, clone-independent, reversal symmetric, and Condorcet-consistent single-winner election method, Social Choice and Welfare 36(2) (2011), 267-303, the definition by strongest paths, the proof that the relation it defines is transitive, the properties, and the O(C^3) algorithm for C candidates
  2. Felix Brandt, Vincent Conitzer, Ulle Endriss, Jérôme Lang and Ariel D. Procaccia (eds.), Handbook of Computational Social Choice, Cambridge University Press, 2016, Chapter 4 (Felix Fischer, Olivier Hudry and Rolf Niedermeier, Weighted tournament solutions), Section 4.5.2, Schulze's method and its computation with widest paths in O(m^3) time; Chapter 6 (Vincent Conitzer and Toby Walsh, Barriers to manipulation), the polynomial-time manipulation of Schulze's method by one voter
  3. Hervé Moulin, Condorcet's principle implies the no show paradox, Journal of Economic Theory 45(1) (1988), 53-64, the theorem that no Condorcet consistent rule satisfies participation when there are at least 4 candidates and 25 voters

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