Subversion Repositories Remote Hare Voting

Rev

Rev 53 | Rev 55 | 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
##
51 jtkorb 22
##      % svn co http://www.bikmort.com/hare
24 jtkorb 23
##
15 jtkorb 24
 
25
import sys
26
import math 
27
import random
28
 
45 jtkorb 29
fdOut = None
15 jtkorb 30
fTrace = 1
39 jtkorb 31
randcalls = 0
15 jtkorb 32
 
53 jtkorb 33
class Universe:
54 jtkorb 34
    id = 0                              # id of last create Universe
53 jtkorb 35
 
54 jtkorb 36
    def __init__(self, p, nWinners, nBallots, quota):
37
        Universe.id += 1
38
        self.id = Universe.id
39
        self.p = p
40
        self.nBallots = nBallots
41
	self.nWinners = nWinners
42
        self.quota = quota
43
        self.winners = []
44
        self.losers = []
45
        self.tally = {}
46
 
53 jtkorb 47
    def getP(self):
48
        print "instance p =", self.p
49
        print "class p =", Universe.p
50
 
15 jtkorb 51
def trace(s):
45 jtkorb 52
    global fTrace, fdOut
53
    if fTrace: print >>fdOut, s
15 jtkorb 54
    return
55
 
56
def findWinner(winners, losers, tally, quota, nWinners):
39 jtkorb 57
    global randcalls
51 jtkorb 58
    cWin = quota        # number of votes for highest winner
59
    lWin = []           # list of candidates with highest votes
39 jtkorb 60
    for c in tally.keys():
61
        if c not in losers and c not in winners and len(tally[c]) >= cWin:
62
            if len(tally[c]) == cWin:
63
                lWin.append(c)
64
            else:
65
                lWin = [c]
66
                cWin = len(tally[c])
67
    if len(lWin) == 1:
68
        return lWin[0]
69
    elif len(lWin) > 1:
70
        trace("\tselecting winning candidate randomly from %s" % lWin)
71
        randcalls += 1
72
        return random.choice(lWin)
15 jtkorb 73
 
74
    # Check to see if only enough candidates remain
40 jtkorb 75
    ## TODO: sort by len(tally[c]) to choose larger winners first
76
    ## randomize and count if some with equal votes
15 jtkorb 77
    n = 0
78
    last = ""
40 jtkorb 79
    for c in tally.keys():
80
        if c not in winners and c not in losers:
81
            last = c
15 jtkorb 82
            n = n + 1
83
    if nWinners - len(winners) >= n:
40 jtkorb 84
        trace("\tremaining winner(s) have fewer than quota (%d) ballots" %
85
            quota)
15 jtkorb 86
        return last
87
    return
88
 
89
def redistributeWinner(winner, winners, losers, tally, quota):
39 jtkorb 90
    global randcalls
15 jtkorb 91
    excess = len(tally[winner]) - quota
92
    if excess <= 0:
21 jtkorb 93
        trace("\tno excess ballots to redistribute")
15 jtkorb 94
    else:
51 jtkorb 95
        lEffective = gatherEffectiveBallots(winner, winners, losers, tally)
44 jtkorb 96
        nRedistribute = min(excess, len(lEffective))
97
        trace("\tredistributing %d effective of %d excess ballot(s) at random from %s" %
98
              (nRedistribute, excess, winner))
99
        for ballot in random.sample(lEffective, nRedistribute):
39 jtkorb 100
            randcalls += 1
44 jtkorb 101
            trace("\trandom choice = %s" % ballot)
102
            tally[winner].remove(ballot)
103
            redistributeBallot(ballot, winners, losers, tally)
104
            nRedistribute -= 1
15 jtkorb 105
    traceTally(quota, tally)
106
 
44 jtkorb 107
def gatherEffectiveBallots(winner, winners, losers, tally):
108
    lEffective = []
109
    for ballot in tally[winner]:
110
        for candidateTo in ballot:
111
           if candidateTo not in winners and candidateTo not in losers:
112
                lEffective.append(ballot)
113
                break
114
    return lEffective
115
 
116
def redistributeBallot(ballot, winners, losers, tally):
15 jtkorb 117
    for candidateTo in ballot:
21 jtkorb 118
        if candidateTo not in winners and candidateTo not in losers:
119
            trace("\tto %s: %s" % (candidateTo, ballot))
120
            if not tally.has_key(candidateTo): tally[candidateTo] = []
121
            tally[candidateTo].append(ballot)
122
            ballot = ""
123
            break
15 jtkorb 124
    if ballot:
21 jtkorb 125
        trace("\tineffective ballot dropped: %s" % ballot)
15 jtkorb 126
 
127
def findLoser(losers, winners, tally):
39 jtkorb 128
    global randcalls
15 jtkorb 129
    cMin = sys.maxint  # least number of votes for candidate loser
130
    lMin = []          # list of candidates with least votes
131
    for c in tally.keys():
132
        if c not in losers and c not in winners and len(tally[c]) <= cMin:
21 jtkorb 133
            if len(tally[c]) == cMin:
134
                lMin.append(c)
135
            else:
136
                lMin = [c]
137
                cMin = len(tally[c])
15 jtkorb 138
    if len(lMin) == 0:
139
        return None
39 jtkorb 140
    elif len(lMin) == 1:
141
        return lMin[0]
15 jtkorb 142
    else:
39 jtkorb 143
        trace("\teliminating low candidate randomly from %s" % lMin)
144
        randcalls += 1
15 jtkorb 145
        return random.choice(lMin)
146
 
147
def redistributeLoser(loser, losers, winners, tally, quota):
148
    excess = len(tally[loser])
149
    if excess <= 0:
21 jtkorb 150
        trace("\tno ballots to redistribute")
15 jtkorb 151
    else:
21 jtkorb 152
        trace("\tredistributing %d ballot(s) from %s" % (excess, loser))
153
        while len(tally[loser]) > 0:
154
            ballot = tally[loser][0]
155
            tally[loser] = tally[loser][1:]
44 jtkorb 156
            redistributeBallot(ballot, winners, losers, tally)
15 jtkorb 157
    traceTally(quota, tally)
158
    return
159
 
160
def traceTally(quota, tally):
161
    global fTrace
162
    if not fTrace: return
163
    trace("\nCURRENT ASSIGNMENT OF BALLOTS (%d needed to win)" % quota)
164
    for candidate in tally.keys():
165
        trace("\t%s:" % candidate)
166
        for ballot in tally[candidate]:
167
            trace("\t\t%s" % ballot)
168
    return
169
 
170
# The basic Single Transferable Vote algorithm with Hare quota
171
#
172
# while winners < nWinners:
173
#   if a candidate has more than quota votes:
174
#       redistribute excess votes to next priority candidate
175
#   else:
176
#       eliminate lowest ranking candidate
177
#       redistribute wasted votes to next priority candidate
178
#
179
def dotally(nWinners, ballots):
39 jtkorb 180
    global randcalls
46 jtkorb 181
    randcalls = 0
15 jtkorb 182
 
54 jtkorb 183
    nBallots=len(ballots)
184
    quota=int(math.ceil((nBallots + 1.0)/(nWinners + 1)))
185
 
186
    universe = Universe(1.0, nWinners, nBallots, quota)
187
 
188
    trace("INPUT SUMMARY AND RUN TRACE")
189
    trace("\t%d ballots" % universe.nBallots)
190
    trace("\tChoosing %s winners" % universe.nWinners)
15 jtkorb 191
    trace("\tNeed ceil((%d + 1)/(%d + 1)) = %d ballots to win" %
54 jtkorb 192
          (universe.nBallots, universe.nWinners, universe.quota))
15 jtkorb 193
 
45 jtkorb 194
    # Create initial tally and statistics
15 jtkorb 195
    #
196
    for ballot in ballots:
197
        candidate = ballot[0]
54 jtkorb 198
        if not universe.tally.has_key(candidate):
199
            universe.tally[candidate] = []
200
        universe.tally[candidate].append(ballot)
45 jtkorb 201
 
202
    total1st = {}
203
    total2nd = {}
204
    totalMrk = {}
205
 
206
    for ballot in ballots:
207
        for c in ballot:
208
            total1st[c] = 0
209
            total2nd[c] = 0
210
            totalMrk[c] = 0
211
 
212
    for ballot in ballots:
213
        total1st[ballot[0]] += 1
214
        if len(ballot) > 1:
215
            total2nd[ballot[1]] += 1
216
        for c in ballot:
217
            totalMrk[c] += 1
218
 
219
    trace("\n\tBALLOT MARKS\t1ST\t2ND\tNONE")
220
    candidates = totalMrk.keys()
221
    candidates.sort()
222
    for c in candidates:
223
        trace("\t%-16s%3d\t%3d\t%4d" % (c, total1st[c], total2nd[c], len(ballots)-totalMrk[c]))
54 jtkorb 224
    traceTally(universe.quota, universe.tally)
15 jtkorb 225
 
54 jtkorb 226
    continueTally(universe)
227
    return universe.winners
228
 
229
def continueTally(universe):
230
    while len(universe.winners) < universe.nWinners:
231
        winner = findWinner(universe.winners, universe.losers, universe.tally, universe.quota, universe.nWinners)
15 jtkorb 232
        if winner:
54 jtkorb 233
            universe.winners.append(winner)
234
            trace("\nSELECTION #%d: %s" % (len(universe.winners), winner))
235
            redistributeWinner(winner, universe.winners, universe.losers, universe.tally, universe.quota)
15 jtkorb 236
        else:
54 jtkorb 237
            loser = findLoser(universe.losers, universe.winners, universe.tally)
15 jtkorb 238
            if loser:
54 jtkorb 239
                universe.losers.append(loser)
15 jtkorb 240
                trace("\nELIMINATED: %s" % loser)
54 jtkorb 241
                redistributeLoser(loser, universe.losers, universe.winners, universe.tally, universe.quota)
15 jtkorb 242
            else:
243
                trace("Not enough chosen candidates to fill all positions")
244
                break
39 jtkorb 245
    trace("\nNumber of random choices made: %d" % randcalls)