Subversion Repositories Remote Hare Voting

Rev

Rev 24 | Rev 40 | Go to most recent revision | Details | Compare with Previous | Last modification | View Log | RSS feed

Rev Author Line No. Line
15 jtkorb 1
## Compute Hare Ballot
2
##
3
## Tim Korb (jtk@cs.purdue.edu), May 2007
4
##
5
## A few definitions and notes...
6
##
7
## tally: dictionary in which the keys are candidate names and the
8
## values are lists of ballots currently assigned to that candidate
9
##
10
## ballot: list of candidates in the order determined by the voter
11
##
12
## winners: list of candidates that have reached the quota of ballots
13
## or have remained in the running long enough to be declared a winner
14
##
15
## losers: list of candidates that have been eliminated from the running
16
##
17
## Note that plurals are generally used to indicate lists of other
18
## items, e.g., ballots is a list of ballot items.
19
##
24 jtkorb 20
## To download the complete source distribution, use Subversion:
21
##
22
##	% svn co http://www.bikmort.com/hare
23
##
15 jtkorb 24
 
25
import sys
26
import math 
27
import random
28
 
29
fTrace = 1
39 jtkorb 30
randcalls = 0
15 jtkorb 31
 
32
def trace(s):
33
    global fTrace
34
    if fTrace: print s
35
    return
36
 
37
def findWinner(winners, losers, tally, quota, nWinners):
39 jtkorb 38
    global randcalls
39
    cWin = quota       # number of votes for highest winner
40
    lWin = []          # list of candidates with highest votes
41
    for c in tally.keys():
42
        if c not in losers and c not in winners and len(tally[c]) >= cWin:
43
            if len(tally[c]) == cWin:
44
                lWin.append(c)
45
            else:
46
                lWin = [c]
47
                cWin = len(tally[c])
48
    if len(lWin) == 1:
49
        return lWin[0]
50
    elif len(lWin) > 1:
51
        trace("\tselecting winning candidate randomly from %s" % lWin)
52
        randcalls += 1
53
        return random.choice(lWin)
15 jtkorb 54
 
55
    # Check to see if only enough candidates remain
56
    n = 0
57
    last = ""
58
    for candidate in tally.keys():
59
        if candidate not in winners and candidate not in losers:
60
            last = candidate
61
            n = n + 1
62
    if nWinners - len(winners) >= n:
63
        return last
64
    return
65
 
66
def redistributeWinner(winner, winners, losers, tally, quota):
39 jtkorb 67
    global randcalls
15 jtkorb 68
    excess = len(tally[winner]) - quota
69
    if excess <= 0:
21 jtkorb 70
        trace("\tno excess ballots to redistribute")
15 jtkorb 71
    else:
21 jtkorb 72
        trace("\tredistributing %d excess ballot(s) at random from %s" %
73
              (excess, winner))
74
        while len(tally[winner]) > quota:
75
            i = int(random.uniform(0, len(tally[winner])))
39 jtkorb 76
            randcalls += 1
21 jtkorb 77
            trace("\trandom choice = ballot %d" % (i+1))
78
            ballot = tally[winner][i]
79
            tally[winner] = tally[winner][0:i] + tally[winner][i+1:]
80
            redistributeBallot(ballot, winner, winners, losers, tally)
15 jtkorb 81
    traceTally(quota, tally)
82
 
83
def redistributeBallot(ballot, candidateFrom, winners, losers, tally):
84
    for candidateTo in ballot:
21 jtkorb 85
        if candidateTo not in winners and candidateTo not in losers:
86
            trace("\tto %s: %s" % (candidateTo, ballot))
87
            if not tally.has_key(candidateTo): tally[candidateTo] = []
88
            tally[candidateTo].append(ballot)
89
            ballot = ""
90
            break
15 jtkorb 91
    if ballot:
21 jtkorb 92
        trace("\tineffective ballot dropped: %s" % ballot)
15 jtkorb 93
 
94
def findLoser(losers, winners, tally):
39 jtkorb 95
    global randcalls
15 jtkorb 96
    cMin = sys.maxint  # least number of votes for candidate loser
97
    lMin = []          # list of candidates with least votes
98
    for c in tally.keys():
99
        if c not in losers and c not in winners and len(tally[c]) <= cMin:
21 jtkorb 100
            if len(tally[c]) == cMin:
101
                lMin.append(c)
102
            else:
103
                lMin = [c]
104
                cMin = len(tally[c])
15 jtkorb 105
    if len(lMin) == 0:
106
        return None
39 jtkorb 107
    elif len(lMin) == 1:
108
        return lMin[0]
15 jtkorb 109
    else:
39 jtkorb 110
        trace("\teliminating low candidate randomly from %s" % lMin)
111
        randcalls += 1
15 jtkorb 112
        return random.choice(lMin)
113
 
114
def redistributeLoser(loser, losers, winners, tally, quota):
115
    excess = len(tally[loser])
116
    if excess <= 0:
21 jtkorb 117
        trace("\tno ballots to redistribute")
15 jtkorb 118
    else:
21 jtkorb 119
        trace("\tredistributing %d ballot(s) from %s" % (excess, loser))
120
        while len(tally[loser]) > 0:
121
            ballot = tally[loser][0]
122
            tally[loser] = tally[loser][1:]
123
            redistributeBallot(ballot, loser, winners, losers, tally)
15 jtkorb 124
    traceTally(quota, tally)
125
    return
126
 
127
def traceTally(quota, tally):
128
    global fTrace
129
    if not fTrace: return
130
    trace("\nCURRENT ASSIGNMENT OF BALLOTS (%d needed to win)" % quota)
131
    for candidate in tally.keys():
132
        trace("\t%s:" % candidate)
133
        for ballot in tally[candidate]:
134
            trace("\t\t%s" % ballot)
135
    return
136
 
137
# The basic Single Transferable Vote algorithm with Hare quota
138
#
139
# while winners < nWinners:
140
#   if a candidate has more than quota votes:
141
#       redistribute excess votes to next priority candidate
142
#   else:
143
#       eliminate lowest ranking candidate
144
#       redistribute wasted votes to next priority candidate
145
#
146
def dotally(nWinners, ballots):
39 jtkorb 147
    global randcalls
15 jtkorb 148
    nBallots = len(ballots)
149
    quota = int(math.ceil((nBallots + 1.0)/(nWinners + 1)))
150
 
151
    trace("INPUT SUMMARY")
152
    trace("\t%d ballots" % nBallots)
153
    trace("\tChoosing %s winners" % nWinners)
154
    trace("\tNeed ceil((%d + 1)/(%d + 1)) = %d ballots to win" %
21 jtkorb 155
          (nBallots, nWinners, quota))
15 jtkorb 156
 
157
    # Create initial tally
158
    #
159
    tally = {}
160
    for ballot in ballots:
161
        candidate = ballot[0]
162
        if not tally.has_key(candidate):
163
            tally[candidate] = []
164
        tally[candidate].append(ballot)
165
    traceTally(quota, tally)
166
 
167
    winners = []
168
    losers = []
169
 
170
    while len(winners) < nWinners:
171
        winner = findWinner(winners, losers, tally, quota, nWinners)
172
        if winner:
173
            winners.append(winner)
174
            trace("\nSELECTION #%d: %s" % (len(winners), winner))
175
            redistributeWinner(winner, winners, losers, tally, quota)
176
        else:
177
            loser = findLoser(losers, winners, tally)
178
            if loser:
179
                losers.append(loser)
180
                trace("\nELIMINATED: %s" % loser)
181
                redistributeLoser(loser, losers, winners, tally, quota)
182
            else:
183
                trace("Not enough chosen candidates to fill all positions")
184
                break
39 jtkorb 185
    trace("\nNumber of random choices made: %d" % randcalls)
15 jtkorb 186
 
187
    return winners
188