Algorithm Search⌘K

Algorithmcore

Single transferable vote

Also called STV.

Elects a committee from ranked ballots by quota, transferring surplus votes of elected candidates and votes of eliminated ones.

Time
O(L + m^2) worst
Space
O(n + m) extra
Where
L = the total length of the ballots; k = the number of seats; m = the number of candidates; n = the number of voters
Properties
not comparison baseddeterministiciterative
Origin
Carl Andrae, Thomas Hare, Henry Richmond Droop, 1857

The single transferable vote (STV) elects a committee of kk members from ranked ballots. A candidate is elected when its tally reaches a quota, and its surplus above the quota moves on to the next choices of its voters. When nobody reaches the quota, the weakest candidate is eliminated and its ballots move on. With one seat it is instant-runoff voting; with more seats it gives each large enough group of like-minded voters a share of the seats. It uses quotas, but it is a voting rule on ballots, not an apportionment method for parties.

In plain words

Each voter ranks the candidates. A candidate needs a fixed number of votes, the quota, to win a seat. Count the first choices. If a candidate has the quota or more, it wins, and the votes it does not need are passed on to the next choices on its ballots, each ballot at a reduced value. If nobody has the quota, the candidate with the fewest votes drops out, and its ballots go to their next choices at full value. Repeat until all seats are filled. Few votes are wasted: a vote helps elect one candidate, or it moves on.

The problem

There are mm candidates A={0,…,m−1}A = \{0, \ldots, m - 1\}, nn voters and k≥1k \ge 1 seats. Voter ii gives a ballot rir_i, a sequence of distinct candidates, best first, which may be truncated. The input is the preference profile P=(r1,…,rn)P = (r_1, \ldots, r_n) and kk; the output is a list WW of min⁡(k,m)\min(k, m) winners, in the order of election.

Let VV be the number of nonempty ballots. The Droop quota is q=⌊V/(k+1)⌋+1q = \lfloor V/(k + 1) \rfloor + 1, the smallest whole number such that no k+1k + 1 candidates can all reach it. The Hare quota is q=V/kq = V/k. Each ballot has a weight wiw_i, at first 1, and counts for its first candidate that is still continuing. The tally t(a)t(a) is the sum of the weights of the ballots that count for aa.

The rule of this page moves surpluses by the inclusive Gregory method: when ee is elected with t(e)≥qt(e) \ge q, every ballot that counts for ee moves on with its weight multiplied by f=(t(e)−q)/t(e)f = (t(e) - q)/t(e). Ties are broken by index: the largest tally is elected with the smallest index among ties, and the smallest tally is eliminated with the largest index among ties, as on the instant-runoff page. When the continuing candidates are no more than the empty seats, they are all elected.

The algorithm

As in instant-runoff voting, each candidate has a pile of the ballots that count for it, and each ballot has a pointer to its current entry. MOVE(i)(i) advances the pointer of ballot ii to its next entry that is still in CC, puts ii on that pile and adds wiw_i to that tally. If there is no such entry, the ballot is exhausted.

  1. SINGLE-TRANSFERABLE-VOTE(P, m, k) ▷ P = (r_1, ..., r_n), each ballot best first
  2. 1V ← the number of nonempty ballots; q ← ⌊V/(k + 1)⌋ + 1
  3. 2C ← {0, ..., m - 1}; W ← empty list; w[i] ← 1 and ptr[i] ← 1 for each ballot i
  4. 3put each nonempty ballot i on pile[r_i[1]]; t(a) ← the sum of w[i] over pile[a]
  5. 4while |W| < k and C is not empty do
  6. 5if |C| ≤ k - |W| then
  7. 6append C to W by decreasing t, then by index; return W
  8. 7e ← the a in C with the largest t(a), the smallest index among ties; if t(e) ≥ q then
  9. 8C ← C \ {e}; append e to W
  10. 9f ← (t(e) - q) / t(e)
  11. 10for each ballot i on pile[e] do w[i] ← f · w[i]; MOVE(i)
  12. 11else x ← the a in C with the smallest t(a), the largest index among ties
  13. 12C ← C \ {x}
  14. 13for each ballot i on pile[x] do MOVE(i)
  15. 14return W

Lines L1 to L3 compute the quota and do the first count. Each pass of the loop is one round: line L5 fills the last seats when no choice is left, lines L7 to L10 elect a candidate and pass on its surplus, and lines L11 to L13 eliminate a candidate and pass on its ballots at full weight. All weights are exact fractions. The code also returns a log of the tallies of every round, which is how counts are published. With the Hare quota and no ballots, q=0q = 0, so the code also asks t(e)>0t(e) > 0 on line L7.

Example

Five candidates a,b,c,d,ea, b, c, d, e and 20 ballots compete for k=3k = 3 seats, so q=⌊20/4⌋+1=6q = \lfloor 20/4 \rfloor + 1 = 6.

ballots ranking
9 a≻ba \succ b
2 b≻ab \succ a
4 c≻dc \succ d
3 d≻cd \succ c
2 e≻de \succ d
round aa bb cc dd ee action
1 9 2 4 3 2 elect aa; f=3/9=1/3f = 3/9 = 1/3
2 5 4 3 2 eliminate ee
3 5 4 5 eliminate cc
4 5 9 2 left for 2 seats: elect dd, then bb

In round 1, aa has 9≥69 \ge 6 and is elected. Its surplus is 33, so each of its 9 ballots moves to bb with weight 1/31/3, and bb gets 2+3=52 + 3 = 5. In round 2 nobody has 6, and ee has the fewest votes; its 2 ballots go to dd. In round 3, cc is eliminated and its 4 ballots go to dd. Then two candidates are left for two seats. The committee is {a,b,d}\{a, b, d\}. The 11 voters of the aa and bb group get two seats and the 9 voters of the cc, dd and ee group get one. If the three candidates with the most first choices won, the committee would be {a,c,d}\{a, c, d\}, and the larger group would get only one seat.

Correctness

The proof shows four things. The piles and pointers give the same tallies as a recount of all ballots in each round, because a ballot that counts for a continuing candidate keeps counting for it. The rule returns min⁡(k,m)\min(k, m) distinct winners. Votes are conserved: the continuing tallies, qq for each candidate elected by quota, and the weight of the exhausted ballots always sum to VV, so each candidate elected by quota keeps exactly qq votes. And the rule has proportionality for solid coalitions: if at least jqj q voters rank all members of a set SS above everyone else, with j≤min⁡(k,∣S∣)j \le \min(k, |S|), then at least jj members of SS are elected. The proof of the last fact uses only conservation and (k+1)q>V(k + 1) q > V, which holds for both quotas.

Proof: Correctness and properties of the single transferable votefull

Let A={0,…,m−1}A = \{0, \ldots, m - 1\} be the candidates and k≥1k \ge 1 the number of seats. The input is a list of ballots, each a sequence of distinct candidates, best first, possibly truncated. Empty ballots are dropped, and VV is the number of the other ballots. The quota is q=⌊V/(k+1)⌋+1q = \lfloor V/(k + 1) \rfloor + 1 (Droop) or q=V/kq = V/k (Hare). In both cases (k+1)q>V(k + 1) q > V. Every claim below holds for both quotas.

The direct rule keeps a set CC of continuing candidates, a list WW of winners and a weight wiw_i for each ballot, with wi=1w_i = 1 at the start. Ballot ii counts for the first entry of rir_i that is in CC, if there is one; otherwise it is exhausted. Let t(a)t(a) be the sum of the weights of the ballots that count for aa. One round of the direct rule is:

  1. If ∣C∣≤k−∣W∣|C| \le k - |W|, append all of CC to WW by decreasing tt and then by index, and stop.
  2. Else let ee be the candidate of CC with the largest tt, the smallest index among ties. If t(e)≥qt(e) \ge q and t(e)>0t(e) > 0, multiply the weight of each ballot that counts for ee by f=(t(e)−q)/t(e)f = (t(e) - q)/t(e), remove ee from CC and append it to WW.
  3. Else remove from CC the candidate with the smallest tt, the largest index among ties.

The rule stops when ∣W∣=k|W| = k or CC is empty. The test file has an implementation of this direct rule, which recounts all ballots in every round.

Claim 1 (invariant). At the start of each pass of line L4, the set CC, the list WW and the weights of the method are those of the direct rule after the same number of rounds. For every a∈Ca \in C, pile[a]pile[a] is the set of ballots that count for aa, and the tally of aa is the sum of their weights. For each ballot ii on pile[a]pile[a], ri[ptr[i]]=ar_i[ptr[i]] = a, and every entry of rir_i before position ptr[i]ptr[i] is outside CC.

Proof. By induction on the number of rounds. At the start, C=AC = A, every weight is 1, and line L3 puts every ballot on the pile of its first entry, with the pointer at that entry. Assume the claim before a round. Then the tallies are the values t(a)t(a) of the direct rule, so line L5 makes the same test as step 1, and line L7 picks the same ee as step 2. In the fill case both rules append the same list and stop.

In the elect case, line L8 removes ee and appends it to WW, as in step 2. The ballots that count for ee are those of pile[e]pile[e]. Line L10 multiplies their weights by ff, as in step 2, and moves each one. A move advances the pointer past every entry that is not in CC, so the ballot goes to the pile of its first entry in the new CC, or it is exhausted. A ballot that counted for some a≠ea \ne e still counts for aa, because its earlier entries were outside the old CC and so are outside the new one; the method does not touch it. If f=0f = 0, the ballots of pile[e]pile[e] have weight 0 in the direct rule from now on, and the method drops them; in both rules they add 0 to every later tally. The tally of each pile grows by the weights of the ballots that join it, so the tallies stay correct.

The eliminate case is the same with f=1f = 1: line L11 picks the same candidate xx as step 3, line L12 removes it, and line L13 moves the ballots of pile[x]pile[x] with their weights unchanged.

Claim 2 (termination and output). The method stops after at most mm rounds and returns min⁡(k,m)\min(k, m) distinct candidates.

Proof. Each round that does not stop removes one candidate from CC, so there are at most mm rounds. A candidate enters WW only when it leaves CC, so the winners are distinct. Let s=k−∣W∣s = k - |W| be the number of empty seats. If m≤km \le k, step 1 applies in the first round and WW gets all mm candidates. If m>km > k, then ∣C∣−s|C| - s starts at m−k>0m - k > 0. An election lowers ∣C∣|C| and ss by 1 each, so it keeps ∣C∣−s|C| - s. An elimination lowers ∣C∣−s|C| - s by 1. So the count either fills all seats in step 2, or it reaches ∣C∣−s=0|C| - s = 0 and step 1 elects exactly the ss candidates that are left. In both cases ∣W∣=k|W| = k.

Claim 3 (conservation of votes). At the start of each round,

∑a∈Ct(a)+q⋅∣W∣+X=V,\sum_{a \in C} t(a) + q \cdot |W| + X = V,

where XX is the total weight of the exhausted ballots. So each candidate elected in step 2 keeps exactly qq votes.

Proof. At the start the tallies sum to VV, WW is empty and X=0X = 0. An elimination moves each ballot of the eliminated candidate, with its weight, to another pile or to the exhausted ballots, so the sum does not change. An election of ee removes t(e)t(e) from the tallies; the ballots of pile[e]pile[e] go on with the total weight f⋅t(e)=t(e)−qf \cdot t(e) = t(e) - q, to other piles or to XX, and ∣W∣|W| grows by 1, which adds qq. So the sum does not change.

Claim 4 (proportionality for solid coalitions). Let S⊆AS \subseteq A and j≥1j \ge 1 with j≤min⁡(k,∣S∣)j \le \min(k, |S|). Suppose at least jqj q ballots rank all members of SS above every other candidate (in any order among themselves, and with any continuation, or none, after SS). Then the rule elects at least jj members of SS.

Proof. Let BB be the set of these ballots, so ∣B∣≥jq|B| \ge j q, and let eSe_S be the number of members of SS in WW. We show that the following holds at the start of every round in which eS<je_S < j:

(a) every ballot of BB counts for a member of S∩CS \cap C;

(b) ∑a∈S∩Ct(a)≥(j−eS) q\sum_{a \in S \cap C} t(a) \ge (j - e_S) \, q;

(c) ∣S∩C∣≥j−eS|S \cap C| \ge j - e_S.

Note first that (a) follows from (c): each ballot of BB lists all of SS before any other candidate, so if S∩CS \cap C is not empty, its first continuing entry is in S∩CS \cap C. At the start, S∩C=SS \cap C = S, so the sum in (b) is at least ∣B∣≥jq|B| \ge j q, and (c) is ∣S∣≥j|S| \ge j. Assume (a), (b) and (c) at the start of a round of step 2 or step 3, and that eS<je_S < j still holds after it. First (c): an election of a member of SS lowers both sides of (c) by 1, and an election outside SS changes neither. An elimination happens only when every continuing candidate has t<qt < q. Then, by (b), the members of S∩CS \cap C have tallies that sum to at least (j−eS)q(j - e_S) q, each below qq, so there are at least j−eS+1j - e_S + 1 of them, and at least j−eSj - e_S are left after one is removed. So (c) holds after the round, and (a) with it. Now (b): by (a), before and after the round, no ballot of BB is exhausted and none lies on the pile of a candidate outside SS. So the weight of BB, which is ∣B∣|B| at the start of the count, is split between the piles of S∩CS \cap C and the votes kept by the elected members of SS. Each of them keeps qq votes in total by Claim 3, so at most qq from BB, and (b) holds after the round.

Now suppose that eS<je_S < j when the count stops. If it stops in step 1, all of CC is elected, and by (c) this adds at least j−eSj - e_S members of SS, so eS≥je_S \ge j after all. If it stops in step 2 with ∣W∣=k|W| = k, then k−eSk - e_S winners are outside SS, each elected in step 2, and by (a) none of the qq votes that each keeps comes from BB. So the ballots outside BB have a total weight of at least (k−eS)q(k - e_S) q:

V−∣B∣≥(k−eS) q,soV≥(k−eS+j) q≥(k+1) q>V.V - |B| \ge (k - e_S) \, q, \qquad\text{so}\qquad V \ge (k - e_S + j) \, q \ge (k + 1) \, q > V.

This is a contradiction. The count cannot stop with CC empty while eS<je_S < j, by (c). So at least jj members of SS are elected.

Claim 5 (one seat). With k=1k = 1 and the Droop quota, the rule elects the winner of instant-runoff voting with the same elimination tie rule.

Proof. With k=1k = 1, q=⌊V/2⌋+1q = \lfloor V/2 \rfloor + 1, which is more than V/2V/2. Step 1 applies only when one candidate is left, and step 2 elects ee only when t(e)>V/2t(e) > V/2, which is at least half of the ballots that are not exhausted. While nobody has t≥qt \ge q, steps 3 of both rules remove the same candidate. If step 2 elects ee with t(e)>V/2≥T/2t(e) > V/2 \ge T/2, where TT is the number of ballots that are not exhausted, then by Claim 3 of the instant-runoff page, eliminating to the end also elects ee, and so does the instant-runoff rule, which stops at the first majority of the ballots that still count.

Complexity

Let LL be the total length of the ballots. Each move advances a pointer, so all moves together take O(L)O(L) steps. There are at most mm rounds, and each one finds a largest and a smallest tally in O(m)O(m) time. The total is O(L+m2)O(L + m^2) arithmetic operations and O(n+m)O(n + m) extra space, besides the ballots. The weights are fractions, and each surplus transfer multiplies some of them by a new factor, so their bit length can grow with the number of transfers. Counting rules used in practice round the weights to a fixed number of decimals, which keeps every operation O(1)O(1) on a word RAM at the cost of small errors.

Properties

  • Proportionality for solid coalitions. As stated above. With the Droop quota, a group of more than V/(k+1)V/(k + 1) voters who agree on the top of their ballots is sure of a seat. This is the reason the Droop quota is used.
  • One seat. With k=1k = 1 the Droop quota is a majority of all ballots, and the rule elects the winner of instant-runoff voting.
  • Not monotone. It inherits this from instant-runoff voting. With 6 ballots a≻b≻ca \succ b \succ c, 2 ballots b≻a≻cb \succ a \succ c, 4 ballots b≻c≻ab \succ c \succ a, 5 ballots c≻a≻bc \succ a \succ b and one seat, cc is eliminated and aa wins. If the 2 voters of b≻a≻cb \succ a \succ c move aa to the top, bb is eliminated, its 4 ballots go to cc, and cc wins.
  • Anonymity. Only the multiset of ballots matters. The tie rule by index makes it not neutral in ties.
  • Manipulation. It is NP-complete to decide whether one voter can make a given candidate win by a false ballot (Bartholdi and Orlin 1991). See the voting manipulation problem.
  • No Condorcet guarantee. Like instant-runoff voting, it can eliminate a candidate that beats every other in pairs.

Variants and improvements

  • The quota. The Hare quota V/kV/k is larger. It can change who gets a surplus and so the result. With the 8 ballots 0≻1≻3≻20 \succ 1 \succ 3 \succ 2, 0≻3≻1≻20 \succ 3 \succ 1 \succ 2, 1≻0≻3≻21 \succ 0 \succ 3 \succ 2, 2≻0≻3≻12 \succ 0 \succ 3 \succ 1, twice 2≻1≻0≻32 \succ 1 \succ 0 \succ 3 and twice 2≻1≻3≻02 \succ 1 \succ 3 \succ 0, and k=2k = 2, the Droop quota 3 elects 2 and then 1, and the Hare quota 4 elects 2 and then 0.
  • The surplus rule. The inclusive Gregory method moves all ballots of the elected candidate at a reduced weight. The last-parcel rule moves only the ballots that arrived last. Some laws, as in Ireland, move whole ballots taken from the pile, so the choice of ballots can change the result. The weighted inclusive Gregory method, used for Scottish local elections, takes the weight of each ballot into account, as this page does.
  • Meek's method. Elected candidates keep exactly qq by an iteration over keep factors, and eliminated or elected candidates are skipped on every ballot, also on ballots that moved before. The quota is computed again as ballots become exhausted. It needs a computer.
  • Other proportional rules. For approval ballots, proportional approval voting, Phragmen's sequential method and the method of equal shares give proportionality in the sense of justified representation. For party lists, use an apportionment method such as the D'Hondt method.

When to use it

Use STV to elect several members from one district when voters rank candidates and you want proportional results without parties or lists. Groups of voters get seats in proportion to their size, and voters can rank across party lines. It needs ranked ballots and a central count, and the count is hard to check by hand when surpluses are fractional. For a single seat, use instant-runoff voting or a Condorcet method. If the goal is a committee that represents every voter by one member, see the Chamberlin-Courant rule.

Pitfalls

  • Which quota. The integer Droop quota, the exact Droop quota V/(k+1)V/(k + 1) and the Hare quota give different counts. With the exact quota V/(k+1)V/(k + 1), k+1k + 1 candidates can all reach it. State the quota.
  • Count the transfer weight, not the ballots. A ballot that moved from a surplus has a weight below 1. A count of ballots instead of weights gives wrong tallies in the later rounds.
  • Exhausted ballots. With truncated ballots, the tallies can sum to less than kqk q, and no one may reach the quota. Line L5 then fills the last seats with the continuing candidates. Without it, the count can stop with empty seats.
  • Ties. The order of elections and the elimination ties can decide seats. Laws often look at earlier rounds or draw lots. Fix the rule and test it.
  • Rounding. Exact fractions grow. If the law rounds weights to a fixed number of decimals, do the same, and do it at the step the law gives, or the published counts will not match.

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))
single_transferable_vote.py 101 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/single-transferable-vote/. The authors are listed in prov/CH8C0N.jsonl.

from fractions import Fraction
from typing import Sequence

Ranking = Sequence[int]


def droop_quota(v: int, k: int) -> Fraction:
    """Return the Droop quota floor(v / (k + 1)) + 1 for v valid ballots and k seats."""
    return Fraction(v // (k + 1) + 1)


def hare_quota(v: int, k: int) -> Fraction:
    """Return the Hare quota v / k for v valid ballots and k seats."""
    return Fraction(v, k)


def stv_count(profile: Sequence[Ranking], m: int, k: int, quota: str = "droop"):
    """Run the single transferable vote and return (winners, log).

    The candidates are 0, ..., m - 1 and k >= 1 is the number of seats. Each ballot ranks
    distinct candidates, best first, and may be truncated. Surplus votes move by the
    inclusive Gregory rule: every ballot on the pile of an elected candidate e moves on with
    its weight multiplied by (t(e) - q) / t(e), where t(e) is the tally of e and q the quota.
    In a round, the continuing candidate with the largest tally is elected if it has at least
    q, ties to the smallest index; otherwise the continuing candidate with the smallest tally
    is eliminated, ties to the largest index. When the continuing candidates are no more than
    the empty seats, all of them are elected, by tally and then by index.

    winners lists the elected candidates in the order of election, min(k, m) of them. Each
    log entry is (action, candidate, tally), where action is "elect", "eliminate" or "fill",
    and tally is the list of the tallies of the continuing candidates at that moment (None for
    the others). All weights are exact fractions.
    """
    valid = [r for r in profile if len(r) > 0]
    v = len(valid)
    q = droop_quota(v, k) if quota == "droop" else hare_quota(v, k)  # @line L1
    continuing = [True] * m  # @line L2
    weight = [Fraction(1)] * v
    ptr = [0] * v
    piles: list[list[int]] = [[] for _ in range(m)]
    tally = [Fraction(0)] * m
    for i, r in enumerate(valid):  # @line L3
        piles[r[0]].append(i)
        tally[r[0]] += 1
    left = m
    winners: list[int] = []
    log = []

    def move(i: int) -> None:
        r = valid[i]
        ptr[i] += 1
        while ptr[i] < len(r) and not continuing[r[ptr[i]]]:
            ptr[i] += 1
        if ptr[i] < len(r):
            piles[r[ptr[i]]].append(i)
            tally[r[ptr[i]]] += weight[i]

    while len(winners) < k and left > 0:  # @line L4
        snapshot = [tally[a] if continuing[a] else None for a in range(m)]
        if left <= k - len(winners):  # @line L5
            rest = sorted((a for a in range(m) if continuing[a]), key=lambda a: (-tally[a], a))
            for a in rest:
                continuing[a] = False
                winners.append(a)
                log.append(("fill", a, snapshot))
            return winners, log  # @line L6
        e = -1
        for a in range(m):
            if continuing[a] and (e == -1 or tally[a] > tally[e]):
                e = a
        if tally[e] >= q and tally[e] > 0:  # @line L7
            continuing[e] = False  # @line L8
            left -= 1
            winners.append(e)
            log.append(("elect", e, snapshot))
            f = (tally[e] - q) / tally[e]  # @line L9
            if f > 0:
                for i in piles[e]:  # @line L10
                    weight[i] *= f
                    move(i)
            piles[e] = []
        else:
            x = -1
            for a in range(m):  # @line L11
                if continuing[a] and (x == -1 or tally[a] <= tally[x]):
                    x = a
            continuing[x] = False  # @line L12
            left -= 1
            log.append(("eliminate", x, snapshot))
            for i in piles[x]:  # @line L13
                move(i)
            piles[x] = []
    return winners, log  # @line L14


def single_transferable_vote(profile: Sequence[Ranking], m: int, k: int, quota: str = "droop") -> list[int]:
    """Return the k winners of the single transferable vote, in the order of election."""
    return stv_count(profile, m, k, quota)[0]
test_single_transferable_vote.py 237 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/single-transferable-vote/. The authors are listed in prov/CH8C0N.jsonl.

import random
import unittest
from fractions import Fraction
from itertools import combinations

from agtprefs import all_rankings, check_anonymity, random_profile
from single_transferable_vote import droop_quota, hare_quota, single_transferable_vote, stv_count

A, B, C, D, E = range(5)
EXAMPLE = [(A, B)] * 9 + [(B, A)] * 2 + [(C, D)] * 4 + [(D, C)] * 3 + [(E, D)] * 2


def recount_stv(profile, m, k, quota="droop"):
    """A second count: it recomputes every tally from the ballots in each round.

    It also checks that the total weight is conserved in every round. It returns the winners.
    """
    ballots = [list(r) for r in profile if len(r) > 0]
    v = len(ballots)
    q = droop_quota(v, k) if quota == "droop" else hare_quota(v, k)
    weight = [Fraction(1)] * v
    cont = set(range(m))
    winners = []
    kept = Fraction(0)

    def top(r):
        for a in r:
            if a in cont:
                return a
        return None

    while len(winners) < k and cont:
        t = {a: Fraction(0) for a in cont}
        exhausted = Fraction(0)
        for r, w in zip(ballots, weight):
            a = top(r)
            if a is None:
                exhausted += w
            else:
                t[a] += w
        assert sum(t.values()) + kept + exhausted == v
        if len(cont) <= k - len(winners):
            winners.extend(sorted(cont, key=lambda a: (-t[a], a)))
            return winners
        best = max(t.values())
        e = min(a for a in cont if t[a] == best)
        if t[e] >= q and t[e] > 0:
            f = (t[e] - q) / t[e]
            for i, r in enumerate(ballots):
                if top(r) == e:
                    weight[i] *= f
            kept += q
            cont.discard(e)
            winners.append(e)
        else:
            worst = min(t.values())
            cont.discard(max(a for a in cont if t[a] == worst))
    return winners


def irv_to_the_end(profile, m):
    """Instant runoff run until one candidate is left; elimination ties to the largest index."""
    cont = set(range(m))
    while len(cont) > 1:
        t = {a: 0 for a in cont}
        for r in profile:
            for a in r:
                if a in cont:
                    t[a] += 1
                    break
        worst = min(t.values())
        cont.discard(max(a for a in cont if t[a] == worst))
    return cont.pop()


def random_ballots(rng, m, n, truncate):
    out = []
    for r in random_profile(rng, m, n):
        if truncate:
            r = r[: rng.randint(0, m)]
        out.append(r)
    return out


def solid_coalitions(profile, m, q):
    """Yield (S, j): the ballots that rank all of S above every other candidate number at least j q."""
    for size in range(1, m + 1):
        for S in combinations(range(m), size):
            s = set(S)
            count = sum(1 for r in profile if len(r) >= size and set(r[:size]) == s)
            j = int(Fraction(count) / q)
            if j >= 1:
                yield s, j


class TestQuotas(unittest.TestCase):
    def test_droop_and_hare(self):
        self.assertEqual(droop_quota(20, 3), 6)
        self.assertEqual(droop_quota(100, 1), 51)
        self.assertEqual(droop_quota(99, 2), 34)
        self.assertEqual(hare_quota(20, 3), Fraction(20, 3))
        for v in range(1, 60):
            for k in range(1, 6):
                q = droop_quota(v, k)
                self.assertGreater((k + 1) * q, v)
                self.assertLessEqual(k * q, v + k)


class TestWorkedExample(unittest.TestCase):
    def test_rounds(self):
        winners, log = stv_count(EXAMPLE, 5, 3)
        self.assertEqual(winners, [A, D, B])
        self.assertEqual([(act, c) for act, c, _ in log], [("elect", A), ("eliminate", E), ("eliminate", C), ("fill", D), ("fill", B)])
        self.assertEqual(log[0][2], [9, 2, 4, 3, 2])
        self.assertEqual(log[1][2], [None, 5, 4, 3, 2])
        self.assertEqual(log[2][2], [None, 5, 4, 5, None])
        self.assertEqual(log[3][2], [None, 5, None, 9, None])

    def test_hare_gives_the_same_set(self):
        self.assertEqual(set(single_transferable_vote(EXAMPLE, 5, 3, "hare")), {A, B, D})

    def test_first_preferences_alone_pick_another_set(self):
        firsts = [sum(1 for r in EXAMPLE if r[0] == a) for a in range(5)]
        top3 = sorted(range(5), key=lambda a: (-firsts[a], a))[:3]
        self.assertEqual(set(top3), {A, C, D})


class TestAgainstRecount(unittest.TestCase):
    def test_random_profiles(self):
        rng = random.Random(11)
        for _ in range(600):
            m = rng.randint(1, 5)
            n = rng.randint(1, 12)
            k = rng.randint(1, m)
            prof = random_ballots(rng, m, n, rng.random() < 0.5)
            for quota in ("droop", "hare"):
                self.assertEqual(single_transferable_vote(prof, m, k, quota), recount_stv(prof, m, k, quota))

    def test_elect_entries_reach_the_quota(self):
        rng = random.Random(12)
        for _ in range(300):
            m = rng.randint(2, 5)
            n = rng.randint(2, 15)
            k = rng.randint(1, m)
            prof = random_ballots(rng, m, n, True)
            v = sum(1 for r in prof if r)
            if v == 0:
                continue
            q = droop_quota(v, k)
            winners, log = stv_count(prof, m, k)
            self.assertEqual(len(winners), k)
            self.assertEqual(len(set(winners)), k)
            for act, c, t in log:
                if act == "elect":
                    self.assertGreaterEqual(t[c], q)
                    self.assertEqual(t[c], max(x for x in t if x is not None))


class TestOneSeat(unittest.TestCase):
    def test_k1_is_instant_runoff(self):
        rng = random.Random(13)
        for _ in range(500):
            m = rng.randint(1, 5)
            n = rng.randint(1, 11)
            prof = random_ballots(rng, m, n, rng.random() < 0.5)
            if not any(prof):
                continue
            self.assertEqual(single_transferable_vote(prof, m, 1), [irv_to_the_end(prof, m)])

    def test_not_monotone(self):
        before = [(A, B, C)] * 6 + [(B, A, C)] * 2 + [(B, C, A)] * 4 + [(C, A, B)] * 5
        after = [(A, B, C)] * 8 + [(B, C, A)] * 4 + [(C, A, B)] * 5
        self.assertEqual(single_transferable_vote(before, 3, 1), [A])
        self.assertEqual(single_transferable_vote(after, 3, 1), [C])


class TestProportionality(unittest.TestCase):
    def check(self, prof, m, k, quota):
        v = sum(1 for r in prof if r)
        q = droop_quota(v, k) if quota == "droop" else hare_quota(v, k)
        W = set(single_transferable_vote(prof, m, k, quota))
        for S, j in solid_coalitions(prof, m, q):
            self.assertGreaterEqual(len(W & S), min(j, k, len(S)))

    def test_planted_coalitions(self):
        rng = random.Random(14)
        for _ in range(300):
            m = rng.randint(2, 5)
            k = rng.randint(1, m)
            size = rng.randint(1, m)
            S = rng.sample(range(m), size)
            prof = random_ballots(rng, m, rng.randint(0, 8), True)
            for _ in range(rng.randint(1, 10)):
                head = S[:]
                rng.shuffle(head)
                tail = [a for a in range(m) if a not in S]
                rng.shuffle(tail)
                prof.append(tuple(head + tail[: rng.randint(0, len(tail))]))
            rng.shuffle(prof)
            for quota in ("droop", "hare"):
                self.check(prof, m, k, quota)

    def test_all_profiles_of_four_voters(self):
        rankings = all_rankings(3)
        for p in combinations(rankings * 4, 4):
            for k in (1, 2):
                self.check(list(p), 3, k, "droop")


class TestQuotaChoice(unittest.TestCase):
    def test_droop_and_hare_differ(self):
        prof = [(0, 1, 3, 2), (0, 3, 1, 2), (1, 0, 3, 2), (2, 0, 3, 1)] + [(2, 1, 0, 3)] * 2 + [(2, 1, 3, 0)] * 2
        self.assertEqual(single_transferable_vote(prof, 4, 2), [2, 1])
        self.assertEqual(single_transferable_vote(prof, 4, 2, "hare"), [2, 0])
        self.assertEqual(single_transferable_vote(prof, 4, 1), [2])


class TestEdgeCases(unittest.TestCase):
    def test_more_seats_than_candidates(self):
        self.assertEqual(single_transferable_vote([(1, 0), (1,)], 2, 3), [1, 0])

    def test_empty_ballots_are_ignored(self):
        prof = [(), (0,), (1, 0), (1,), ()]
        self.assertEqual(single_transferable_vote(prof, 2, 1), [1])

    def test_anonymity(self):
        rng = random.Random(15)
        sample = [random_profile(rng, 4, rng.randint(2, 9)) for _ in range(200)]
        rule = lambda P, m: frozenset(single_transferable_vote(P, m, 2))
        self.assertIsNone(check_anonymity(rule, 4, None, profiles=sample))


if __name__ == "__main__":
    unittest.main()

History

Carl Andrae proposed a rule of this kind in Denmark in 1855, and Thomas Hare published his in Britain in 1857 and 1859, with the quota V/kV/k. Henry Droop (1881) argued for the smaller quota now named after him. The transfer of surpluses at a fraction of their value is named after J. B. Gregory. STV elects the parliaments of Ireland and Malta and the Australian Senate, and Scottish local councils since 2007. Dummett (1984) named the property of proportionality for solid coalitions, and Tideman (1995) surveys the rules and their variants. Bartholdi and Orlin (1991) showed that manipulating the count is NP-complete.

References

  1. Nicolaus Tideman, The single transferable vote, Journal of Economic Perspectives 9(1) (1995), 27-38, the rules of the count, the quotas and the transfer of surpluses; footnote 1 for proportionality for solid coalitions, after Dummett (1984)
  2. H. R. Droop, On methods of electing representatives, Journal of the Statistical Society of London 44(2) (1881), 141-202, the argument for the quota that carries his name
  3. John J. Bartholdi III and James B. Orlin, Single transferable vote resists strategic voting, Social Choice and Welfare 8(4) (1991), 341-354, the proof that it is NP-complete to decide whether a voter can manipulate the rule

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