Subversion Repositories Local Hare Voting

Rev

Rev 46 | Rev 52 | 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
 
51 jtkorb 33
class Universe:
34
    p = 1               # probability of this universe existing
35
    winners = None
36
    losers = None
37
    tally = None
38
 
39
    def getP(self):
40
        print "instance p =", self.p
41
        print "class p =", Universe.p
42
 
43
print Universe.p
44
x = Universe()
45
print x.p
46
x.p = 5
47
print Universe.p
48
print x.p
49
x.getP()
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
    nBallots = len(ballots)
183
    quota = int(math.ceil((nBallots + 1.0)/(nWinners + 1)))
184
 
45 jtkorb 185
    trace("INPUT SUMMARY AND SINGLE RUN TRACE")
15 jtkorb 186
    trace("\t%d ballots" % nBallots)
187
    trace("\tChoosing %s winners" % nWinners)
188
    trace("\tNeed ceil((%d + 1)/(%d + 1)) = %d ballots to win" %
21 jtkorb 189
          (nBallots, nWinners, quota))
15 jtkorb 190
 
45 jtkorb 191
    # Create initial tally and statistics
15 jtkorb 192
    #
193
    tally = {}
194
    for ballot in ballots:
195
        candidate = ballot[0]
196
        if not tally.has_key(candidate):
197
            tally[candidate] = []
198
        tally[candidate].append(ballot)
45 jtkorb 199
 
200
    total1st = {}
201
    total2nd = {}
202
    totalMrk = {}
203
 
204
    for ballot in ballots:
205
        for c in ballot:
206
            total1st[c] = 0
207
            total2nd[c] = 0
208
            totalMrk[c] = 0
209
 
210
    for ballot in ballots:
211
        total1st[ballot[0]] += 1
212
        if len(ballot) > 1:
213
            total2nd[ballot[1]] += 1
214
        for c in ballot:
215
            totalMrk[c] += 1
216
 
217
    trace("\n\tBALLOT MARKS\t1ST\t2ND\tNONE")
218
    candidates = totalMrk.keys()
219
    candidates.sort()
220
    for c in candidates:
221
        trace("\t%-16s%3d\t%3d\t%4d" % (c, total1st[c], total2nd[c], len(ballots)-totalMrk[c]))
15 jtkorb 222
    traceTally(quota, tally)
223
 
224
    winners = []
225
    losers = []
226
 
227
    while len(winners) < nWinners:
228
        winner = findWinner(winners, losers, tally, quota, nWinners)
229
        if winner:
230
            winners.append(winner)
231
            trace("\nSELECTION #%d: %s" % (len(winners), winner))
232
            redistributeWinner(winner, winners, losers, tally, quota)
233
        else:
234
            loser = findLoser(losers, winners, tally)
235
            if loser:
236
                losers.append(loser)
237
                trace("\nELIMINATED: %s" % loser)
238
                redistributeLoser(loser, losers, winners, tally, quota)
239
            else:
240
                trace("Not enough chosen candidates to fill all positions")
241
                break
39 jtkorb 242
    trace("\nNumber of random choices made: %d" % randcalls)
15 jtkorb 243
 
244
    return winners
245