forked from lkpetrich/Preference-Voting
/
PrefVote.py
2288 lines (1881 loc) · 56.1 KB
/
PrefVote.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python
#
# For doing various preference-based voting algorithms
# From individual preferences, it finds overall preferences with various algorithms
#
# MakeWeighted(Ballots) -- unweighted to weighted, all weights 1
#
# BallotBox objects -- init with weighted ballots:
# list of (weight, (candidates in prefence order))
#
#
# The arg BBox is a ballot-box object
#
# The functions return a sorted list (candidate,count)
# downward by count, then upward by candidate, unless specified otherwise
#
# TotalCount(BBox): returns the sum of the weights
#
# AllVotes(BBox): count of all votes together: adds up all the weights
#
# TopOne(BBox): count the top one of each ballot
#
# MinusBottom(BBox): count the unselected ones
# or the bottom one of each ballot
#
# TopNum(BBox, Num): count the top Num of each ballot
# for simulating approval voting
#
# Borda(BBox): uses the Borda count:
# counting with ((num candidates) + 1 - rank)
#
# ModBorda(BBox): uses a modification of the Borda count:
# counting with ((num votes in ballot) + 1 - rank)
#
# CumulBorda(BBox): like ModBorda, but divides each ballot's counts
# by that ballot's total count, thus simulating cumulative voting
#
# Dowdall(BBox): like Borda, uses a different weighting:
# 1, 1/2, 1/3, 1/4, ...
#
# MajorityJudgment(BBox): sorts the candidates
# by the weighted medians of their ranks
#
#
# These runoff methods return a list of results of rounds,
# each of them like the previous functions' output
#
# TopNumList(BBox): returns a list of all TopNum round results
# Bucklin's method cuts off when some candidate gets a majority
#
# WinnerDropping(BBox, DoRound, GetWinner): returns a list of
# DoRound results, with the winner of each one dropped from the count
# Needs GetWinner for getting the winner from each round's results
#
# TopTwoRunoff(BBox, DoFirstRound=TopOne, DoSecondRound=TopOne):
# The first round selects the top two candidates,
# and in the second round, they go head to head.
#
# For STAR voting, use Borda or some other ranks-to-ratings method
# for the first round.
#
# SequentialRunoff(BBox, ThresholdFunc=min, DoRound=TopOne):
# repeats without the candidates who got the fewest votes,
# continues until all the candidates are used up.
# With its defaults, it is Instant Runoff Voting
# With DoRound = Borda or ModBorda, it's Baldwin
# With that DoRound and also ThresholdFunc = Average, it's Nanson
# With DoRound = MinusBottom, it's Coombs
#
# SingleTransferableVote(BBox, Num): fill N seats (N is second arg)
# in a manner much like sequential runoff / IRV
# Appends a list of each round's winners or losers to that round's results
# + or -, then the list
# Also adds a fake round that lists the winners
#
# CPOSTV(BBox, Num): fill N seats (N is second arg)
# Comparison of Pairs of Outcomes by Single Transferable Vote
# Finds all the possible outcomes and does pairwise comparisons,
# creating a Condorcet matrix for them
# This code uses the Schulze method to find the winning set
#
# SchulzeSTV(BBox, Num): fill N seats (N is second arg)
# Schulze STV compares sets of candidates that differ
# by only one candidate, creating a Condorcet matrix for them
# This code uses the Schulze method to find the winning set
#
#
# Condorcet methods
#
# CondorcetWinnerIndex(PrefMat)
# Returns index if there is one, None otherwise
#
# CondorcetWinner(BBox)
# Returns (True,winner) if there is one, (False,) otherwise
#
# CondorcetLoserIndex(PrefMat)
# Returns index if there is one, None otherwise
#
# CondorcetLoser(BBox)
# Returns (True,loser) if there is one, (False,) otherwise
#
# CondorcetBorda(BBox)
# Does a version of the Borda count with the Condorcet matrix
#
# CondorcetFlipBorda(BBox)
# Does a flipped version, with minus the transpose,
# to rank by losing instead of winning
#
# CondorcetCmbnBorda(BBox)
# Combines both of the previous ratings for sorting, winning then losing
#
# CondorcetWithFallback(BBox, fallback=Borda, settype="All")
# Black's method. It tries to find the Condorcet winner,
# and if it fails to do so, then falls back on another method
# evaluated on some subset of the candidates: "All", "Smith", "Schwartz".
# Returns (True, Condorcet winner) or (False, fallback-method output)
#
# CondorcetSequentialRunoff(BBox, CWn=False, CLs=False,
# ThresholdFunc=min, DoRound=TopOne):
# Like SequentialRunoff, with the addition of
# CWn: use the Condorcet winner
# CLs: drop the Condorcet loser
#
# Schulze(BBox)
# Schulze's beatpath method
# Returns simple list of candidates from winners to losers
#
# Copeland(BBox)
# Copeland's pairwise-aggregation method
# Returns sorted list of (candidate, score)
#
# Minimax(BBox, Which): second arg is which sort:
# "wins" -- winning votes
# "marg" -- margins
# "oppo" -- pairwise opposition
# Returns sorted list of (candidate, score)
#
# KemenyYoung(BBox)
# The Kemeny-Young method
# It goes as n! for n candidates,
# so it may need to use simulated annealing or something similar
# for a large number of candidates.
# Returns simple list of candidates from winners to losers
#
# Dodgson(BBox)
# Dodgson's method
# It goes as n! for n candidates
# Finds all permutations of the ballot preferences,
# then finds the Condorcet winner (if any) for each permutation
# Returns a list of (candidate, distance)
# where distance is the smallest permutation distance
# that made that candidate a Condorcet winner.
#
# Permutation distance =
# Minimum number of interchanges from ascending order to that permutation
# I find that value to be (length) - (number of cycles)
#
# RankedPairs(BBox, Which="oppo")
# Tideman's ranked-pairs method
# Like Kemeny-Young, but with simple hill-climbing optimization
# Returns simple list of candidates from winners to losers
#
# Which is like for Minimax.
# Tideman's original method has "oppo" (the default)
# Maximize Affirmed Majorities has "wins"
#
# Maximum Affirmed Majorities and Maximum Majority Voting
# seem identical to it
#
# Maximal lotteries - Wikipedia - https://en.wikipedia.org/wiki/Maximal_lotteries
# [1503.00694] Consistent Probabilistic Social Choice - https://arxiv.org/abs/1503.00694
# http://econweb.ucsd.edu/~jsobel/172aw02/notes9.pdf
# Find (row # beat col #) - (col # beat row #) matrix:
# C = Condorcet matrix
# D = C - transpose(C)
# Find a probability vector p for the candidates:
# p.D > 0
# For solving by linear programming:
# Maximize w with p.D >= w
# Minimize v with p.D <= v
# where sum of p = 1 and p >= 0
#
# MaximalSet(BBox, Type)
# Returns the Condorcet maximal set
# Type = "Smith": each member beats all those outside of it
# Type = "Schwartz": union of all sets of candidates
# where each member beats or ties all those outside of it,
# but which has no proper subset with that property
#
# MaximalSetSequence(BBox, Type)
# Makes a sequence of maximal sets by removing them
# from the candidates as it goes
#
# MaximalSetSequentialRunoff(BBox, Type, CWn=False, CLs=False,
# ThresholdFunc=min, DoRound=TopOne):
# Like SequentialRunoff, with the addition of the type of the maximal set:
# "Smith" or "Schwartz".
#
# Extra Methods
#
# DescendingSolidCoalitions(BBox)
# Descending Solid Coalitions
# Equivalent to Descending Acquiescing Coalitions
# because there are no tied preferences here
# Returns its winner(s)
# Turns preference numbering of candidates into an order
# Assumes 1-based numbers
def CandPrefNumsToOrder(Cands, PrefNums):
Ballot = len(Cands)*[None]
for c,k in zip(Cands,PrefNums):
Ballot[k-1] = c
return tuple(Ballot)
# Does so on an object with (candidates, list of (weight,numbering))
def CWLPrefNumsToOrder(CWL):
Cands = CWL[0]
WLs = CWL[1]
Ballots = [(WL[0], CandPrefNumsToOrder(Cands, WL[1])) for WL in WLs]
return tuple(Ballots)
# If one has unweighted ballots, make them weighted
def MakeWeighted(Ballots):
return tuple(((1,b) for b in Ballots))
# Setup for ballots in BallotBox
def BallotSetup(Ballots):
return tuple([(b[0],tuple(b[1])) for b in Ballots if len(b[1]) > 0])
# These accessors lazy initing of calculated quantities:
# Candidates -- sorted list of candidates
# Condorcet matrix
def Candidates(self):
if self._Candidates == None:
CandSet = set()
for Ballot in self.Ballots:
CandSet |= set(Ballot[1])
CandList = list(CandSet)
CandList.sort()
self._Candidates = tuple(CandList)
return self._Candidates
def CondorcetMatrix(self):
if self._CondorcetMatrix == None:
Cands = self.Candidates()
NumCands = len(Cands)
self._CondorcetMatrix = [NumCands*[0] for k in xrange(NumCands)]
CandIndices = {}
for k, Cand in enumerate(Cands):
CandIndices[Cand] = k
for Ballot in self.Ballots:
# Ranks -- ranked candidates get from at least 1 to NumCands
# (max rank)
# Unranked ones get 0
Weight = Ballot[0]
Votes = Ballot[1]
Ranks = NumCands*[0]
for k, Vote in enumerate(Votes):
Ranks[CandIndices[Vote]] = NumCands - k
# First index: winner
# Second index: loser
for k1 in xrange(NumCands):
for k2 in xrange(NumCands):
if Ranks[k1] > Ranks[k2]:
self._CondorcetMatrix[k1][k2] += Weight
return self._CondorcetMatrix
# Container for ballots
# Members:
# Candidates
# Ballots: list of (weight, list of candidates in preference order)
class BallotBox:
# Members:
def __init__(self, Ballots):
self.Ballots = BallotSetup(Ballots)
# Lazy init:
self._Candidates = None
self._CondorcetMatrix = None
BallotBox.Candidates = Candidates
BallotBox.CondorcetMatrix = CondorcetMatrix
# Ballot processing
# Function arg: ballot member. Returns whether or not to keep the member
def ProcessBallots(BBox, ProcessFunction):
NewBallots = []
for Ballot in BBox.Ballots:
Weight = Ballot[0]
Votes = Ballot[1]
NewVotes = []
for Vote in Votes:
if ProcessFunction(Vote):
NewVotes.append(Vote)
NewBallots.append((Weight,tuple(NewVotes)))
return BallotBox(NewBallots)
def KeepCandidates(BBox, Cands):
return ProcessBallots(BBox, lambda bc: bc in Cands)
def RemoveCandidates(BBox, Cands):
return ProcessBallots(BBox, lambda bc: bc not in Cands)
# Vote-count functions
# In case we want to do fractions:
# Arg: BallotBox object
def TotalCount(BBox):
Count = 0
for Ballot in BBox.Ballots:
Count += Ballot[0]
return Count
# a and b are (Cand, Count)
# Sort reverse by count, then forward by cand
def CCSortFunction(a,b):
rc = - cmp(a[1],b[1])
if rc != 0: return rc
return cmp(a[0],b[0])
# Generic count function
# Args:
# BallotBox object
# Count function, with args
# Counts: dict with candidate-name keys
# Weight: from ballot
# Votes: list of candidates in preference order)
# Cands: list of candidates, in case that might be needed by the count
def BBoxCounter(BBox, CountFunction):
Cands = BBox.Candidates()
Counts = {}
for Cand in Cands:
Counts[Cand] = 0
for Ballot in BBox.Ballots:
CountFunction(Counts, Ballot[0], Ballot[1], Cands)
CountList = [Counts[Cand] for Cand in Cands]
CandCounts = zip(Cands,CountList)
CandCounts.sort(CCSortFunction)
return tuple(CandCounts)
# Simple counting
def AllVotesFunction(Counts, Weight, Votes, Cands):
for Vote in Votes:
Counts[Vote] += Weight
def AllVotes(BBox):
return BBoxCounter(BBox, AllVotesFunction)
# http://en.wikipedia.org/wiki/First-past-the-post_voting
def TopOneFunction(Counts, Weight, Votes, Cands):
if len(Votes) >= 1:
Counts[Votes[0]] += Weight
def TopOne(BBox):
return BBoxCounter(BBox, TopOneFunction)
def MinusBottomFunction(Counts, Weight, Votes, Cands):
Unselected = tuple(set(Cands) - set(Votes))
if len(Unselected) > 0:
for Vote in Unselected:
Counts[Vote] -= Weight
elif len(Votes) >= 1:
Counts[Votes[-1]] -= Weight
def MinusBottom(BBox):
return BBoxCounter(BBox, MinusBottomFunction)
# http://en.wikipedia.org/wiki/Bucklin_voting
def TopNumFunction(Counts, Weight, Votes, Cands, Num):
NumAdj = min(len(Votes),Num)
for k in xrange(NumAdj):
Counts[Votes[k]] += Weight
def TopNum(BBox,Num):
return BBoxCounter(BBox, lambda Cn,Wt,Vt,Ca: TopNumFunction(Cn,Wt,Vt,Ca,Num))
def TopNumList(BBox):
Cands = BBox.Candidates()
NumCands = len(Cands)
return tuple((TopNum(BBox,k+1) for k in xrange(NumCands)))
# Rank counting
# http://en.wikipedia.org/wiki/Borda_count
def BordaFunction(Counts, Weight, Votes, Cands):
MaxNum = len(Cands)
for k,Vote in enumerate(Votes):
Counts[Vote] += Weight*(MaxNum - k)
def Borda(BBox):
return BBoxCounter(BBox, BordaFunction)
def ModBordaFunction(Counts, Weight, Votes, Cands):
MaxNum = len(Votes)
for k,Vote in enumerate(Votes):
Counts[Vote] += Weight*(MaxNum - k)
def ModBorda(BBox):
return BBoxCounter(BBox, ModBordaFunction)
# http://en.wikipedia.org/wiki/Cumulative_voting
def CumulBordaFunction(Counts, Weight, Votes, Cands):
MaxNum = len(Votes)
IndCount = {}
for k,Vote in enumerate(Votes):
if Vote not in IndCount: IndCount[Vote] = float(0)
IndCount[Vote] += Weight*(MaxNum - k)
ICTotal = float(0)
for k,Vote in enumerate(Votes):
ICTotal += IndCount[Vote]
for k,Vote in enumerate(Votes):
Counts[Vote] += (Weight*IndCount[Vote])/ICTotal
def CumulBorda(BBox):
return BBoxCounter(BBox, CumulBordaFunction)
def DowdallFunction(Counts, Weight, Votes, Cands):
MaxNum = len(Cands)
for k,Vote in enumerate(Votes):
Counts[Vote] += Weight/float(k+1)
def Dowdall(BBox):
return BBoxCounter(BBox, DowdallFunction)
# https://en.wikipedia.org/wiki/Majority_judgment
def WeightedMedian(wtrnks):
# Sort by ranks and find cumulative weights
wrsort = list(wtrnks)
wrsort.sort(lambda a,b: cmp(a[0],b[0]))
totwt = 0
cwtrks = []
for rk, wt in wrsort:
cwr = (rk, totwt)
cwtrks.append(cwr)
totwt += wt
hftot = 0.5*totwt
# Search through to find contributors to the median:
# those that make the boolean variable addmdn true.
# Add up their contributions in rksum (sum of ranks)
# and rkcnt (count of ranks).
rksum = 0.; rkcnt = 0
n = len(cwtrks)
for k in xrange(n):
addmdn = cwtrks[k][1] <= hftot
if addmdn:
if k < n-1:
addmdn = cwtrks[k+1][1] >= hftot
else:
addmdn = True
if addmdn:
rksum += cwtrks[k][0]; rkcnt += 1
# Finally, the median
return rksum/rkcnt
def MajorityJudgment(BBox):
Cands = BBox.Candidates()
NumCands = len(Cands)
CandRanks = []
for Ballot in BBox.Ballots:
wt, prefs = Ballot
for k,pref in enumerate(prefs):
CandRanks.append( (pref, NumCands-k, wt) )
for Cand in Cands:
if Cand not in prefs:
CandRanks.append( (Cand, 0, wt) )
CandRankLists = {}
for Cand in Cands:
CandRankLists[Cand] = []
for CREntry in CandRanks:
CandRankLists[CREntry[0]].append(CREntry[1:3])
CandWMs = [(Cand, WeightedMedian(CandRankLists[Cand])) for Cand in Cands]
CandWMs.sort(CCSortFunction)
return tuple(CandWMs)
# Multistep methods
def WinnerDropping(BBox, DoRound, GetWinner):
NewBBox = BBox
rounds = []
while len(NewBBox.Ballots) > 0:
res = DoRound(NewBBox)
rounds.append(res)
NewBBox = RemoveCandidates(NewBBox, [GetWinner(res)])
return tuple(rounds)
# http://en.wikipedia.org/wiki/Contingent_vote
# http://en.wikipedia.org/wiki/Two-round_system
def TopTwoRunoff(BBox, DoFirstRound=TopOne, DoSecondRound=TopOne):
rounds = []
res = DoFirstRound(BBox)
rounds.append(res)
if len(res) == 0: return tuple(rounds)
# Find top two or top ones with the same vote
# Using res being sorted
TopTwoCands = []
MaxVotes = res[0][1]
for r in res:
if r[1] != MaxVotes:
if len(TopTwoCands) >= 2: break
MaxVotes = r[1]
TopTwoCands.append(r[0])
TopTwoCands.sort()
TopTwoCands = tuple(TopTwoCands)
NewBBox = KeepCandidates(BBox, TopTwoCands)
res = DoSecondRound(NewBBox)
rounds.append(res)
return tuple(rounds)
# http://en.wikipedia.org/wiki/Instant-runoff_voting
# http://en.wikipedia.org/wiki/Exhaustive_ballot
# http://en.wikipedia.org/wiki/Nanson%27s_method
# http://en.wikipedia.org/wiki/Coombs%27_method
def SequentialRunoff(BBox, ThresholdFunc=min, DoRound=TopOne):
NewBBox = BBox
rounds = []
while len(NewBBox.Ballots) > 0:
res = DoRound(NewBBox)
rounds.append(res)
BottomCands = []
VoteThreshold = ThresholdFunc([r[1] for r in res])
for r in res:
if r[1] <= VoteThreshold:
BottomCands.append(r[0])
BottomCands.sort()
BottomCands = tuple(BottomCands)
NewBBox = RemoveCandidates(NewBBox, BottomCands)
return tuple(rounds)
def Average(lst):
return float(sum(lst))/float(len(lst))
# http://en.wikipedia.org/wiki/Single_transferable_vote
def SingleTransferableVote(BBox, Num):
# The Hagenbach-Bischoff quota,
# a fractional version of the Droop quota
# http://en.wikipedia.org/wiki/Hagenbach-Bischoff_quota
Quota = TotalCount(BBox)/(Num + 1.0)
NewBBox = BBox
rounds = []
Winners = []
while len(NewBBox.Ballots) > 0 and len(Winners) < Num:
res = TopOne(NewBBox)
# Check for winners
# Find top candidates with the same Vote
TopCands = []
MaxVotes = res[0][1]
for r in res:
if r[1] != MaxVotes: break
TopCands.append(r[0])
TopCands.sort()
TopCands = tuple(TopCands)
ExcessVotes = MaxVotes - Quota
if ExcessVotes >= 0:
# Adjust weights to use winners' excess votes
NewBallots = []
for Weight, Votes in NewBBox.Ballots:
if Votes[0] in TopCands:
Weight = (Weight * ExcessVotes) / MaxVotes
NewBallots.append((Weight,Votes))
NewBBox = BallotBox(NewBallots)
NewBBox = RemoveCandidates(NewBBox, TopCands)
Winners.extend(TopCands)
rounds.append(tuple(list(res) + [('+',TopCands)]))
continue
# Check for losers
# Find bottom ones with the same vote
BottomCands = []
MinVotes = res[-1][1]
for r in reversed(res):
if r[1] != MinVotes: break
BottomCands.append(r[0])
BottomCands.sort()
BottomCands = tuple(BottomCands)
NewBBox = RemoveCandidates(NewBBox, BottomCands)
rounds.append(tuple(list(res) + [('-',BottomCands)]))
rounds.append((tuple(Winners),))
return tuple(rounds)
# http://en.wikipedia.org/wiki/CPO-STV
# Subsets with length sslen
# of a range of integers from 0 to rnglen-1
def RangeSubsets(rnglen, sslen):
RSS = [[]]
for ns in xrange(sslen):
NewRSS = []
for SS in RSS:
base = max(SS)+1 if len(SS) > 0 else 0
for k in xrange(base,rnglen-sslen+ns+1):
NewSS = SS + [k]
NewRSS.append(NewSS)
RSS = NewRSS
return RSS
# Subsets with length sslen
# of a list
def ListSubsets(lst, sslen):
rss = RangeSubsets(len(lst),sslen)
return [[lst[n] for n in ss] for ss in rss]
# The main event
# Returns sets of candidates and a Condorcet matrix for them
def CPOSTVMatrix(BBox, Num):
Quota = TotalCount(BBox)/(Num + 1.0)
Cands = BBox.Candidates()
# Find all possible sets of Num candidates
CandPosses = ListSubsets(Cands,Num)
ncp = len(CandPosses)
CprMat = [ncp*[0] for k in xrange(ncp)]
CS = set(Cands)
for k1 in xrange(ncp-1):
Cands1 = CandPosses[k1]
CS1 = set(Cands1)
for k2 in xrange(k1+1,ncp):
Cands2 = CandPosses[k2]
CS2 = set(Cands2)
InBoth = CS1 & CS2
InNeither = CS - (CS1 | CS2)
# Eliminate candidates in neither possibilities
NewBBox = RemoveCandidates(BBox, InNeither)
TotalOverThreshold = 0
# Eliminate over-threshold candidates in both possibilities
while True:
res = TopOne(NewBBox)
VotesOverThreshold = {}
for r in res:
if r[0] in InBoth and r[1] >= Quota:
VotesOverThreshold[r[0]] = r[1]
CandsOverThreshold = VotesOverThreshold.keys()
NumOverThreshold = len(CandsOverThreshold)
if NumOverThreshold <= 0: break
TotalOverThreshold += NumOverThreshold
NewBallots = []
for Weight, Votes in NewBBox.Ballots:
if Votes[0] in CandsOverThreshold:
TotalVotes = VotesOverThreshold[Votes[0]]
Weight = (Weight * (TotalVotes - Quota)) / TotalVotes
NewBallots.append((Weight,Votes))
NewBBox = BallotBox(NewBallots)
NewBBox = RemoveCandidates(NewBBox, CandsOverThreshold)
Total1 = Total2 = Quota*TotalOverThreshold
for r in res:
if r[0] in Cands1:
Total1 += r[1]
if r[0] in Cands2:
Total2 += r[1]
CprMat[k1][k2] = Total1
CprMat[k2][k1] = Total2
return (CandPosses, CprMat)
# http://en.wikipedia.org/wiki/Schulze_STV
# Much like CPO-STV, but comparing sets of candidates that differ by only one member
# Returns sets of candidates and a Condorcet matrix for them
def SchulzeSTVMatrix(BBox,Num):
Cands = BBox.Candidates()
# Find all possible sets of Num candidates
CandPosses = ListSubsets(Cands,Num)
# Turn into sets for convenience
CandPossSets = map(set,CandPosses)
# Find the score of each set relative to each other set
ncp = len(CandPosses)
ScoreMat = [ncp*[0] for k in xrange(ncp)]
for i in xrange(ncp):
CPOrig = CandPosses[i]
for j in xrange(ncp):
scnddiff = list(CandPossSets[j] - CandPossSets[i])
if len(scnddiff) != 1: continue
sdval = scnddiff[0]
ncpogt = Num*[0]
for Ballot in BBox.Ballots:
wt, prefs = Ballot
if sdval not in prefs: continue
sdvix = prefs.index(sdval)
for k, cpoval in enumerate(CPOrig):
if cpoval not in prefs: continue
cpovix = prefs.index(cpoval)
if cpovix < sdvix:
ncpogt[k] += wt
ScoreMat[i][j] = min(ncpogt)
return (CandPosses, ScoreMat)
# Condorcet methods
# http://en.wikipedia.org/wiki/Condorcet_method
def Condorcet(BBox,CondorcetCandPM):
Cands = BBox.Candidates()
PrefMat = BBox.CondorcetMatrix()
return CondorcetCandPM(Cands,PrefMat)
def CondorcetCandPMPrefOrder(Cands,PrefMat,PrefOrderFunction):
PrefOrder = PrefOrderFunction(PrefMat)
return tuple((Cands[PO] for PO in PrefOrder))
def CondorcetPrefOrder(BBox,PrefOrderFunction):
return Condorcet(BBox, lambda Cands, PrefMat: \
CondorcetCandPMPrefOrder(Cands,PrefMat,PrefOrderFunction))
def CondorcetCandPMPrefCount(Cands,PrefMat,PrefCountFunction):
PrefCount = PrefCountFunction(PrefMat)
CandCounts = zip(Cands, PrefCount)
CandCounts.sort(CCSortFunction)
return tuple(CandCounts)
def CondorcetPrefCount(BBox,PrefCountFunction):
return Condorcet(BBox, lambda Cands, PrefMat: \
CondorcetCandPMPrefCount(Cands,PrefMat,PrefCountFunction))
def CondorcetWinnerIndex(PrefMat):
n = len(PrefMat)
for i in xrange(n):
wix = i
for j in xrange(n):
if j != i and PrefMat[i][j] <= PrefMat[j][i]:
wix = None
break
if wix != None: return wix
return None
def CondorcetWinner(BBox):
Cands = BBox.Candidates()
PrefMat = BBox.CondorcetMatrix()
wix = CondorcetWinnerIndex(PrefMat)
if wix != None:
return (True,Cands[wix])
else:
return (False,)
def CondorcetLoserIndex(PrefMat):
n = len(PrefMat)
for i in xrange(n):
lix = i
for j in xrange(n):
if j != i and PrefMat[i][j] >= PrefMat[j][i]:
lix = None
break
if lix != None: return lix
return None
def CondorcetLoser(BBox):
Cands = BBox.Candidates()
PrefMat = BBox.CondorcetMatrix()
lix = CondorcetLoserIndex(PrefMat)
if lix != None:
return (True,Cands[lix])
else:
return (False,)
def CondorcetBordaCount(PrefMat):
return tuple(map(sum,PrefMat))
def CondorcetBorda(BBox):
return CondorcetPrefCount(BBox,CondorcetBordaCount)
def CondorcetFlipBordaCount(PrefMat):
n = len(PrefMat)
cnts = n*[0]
for i in xrange(n):
cnt = 0
for j in xrange(n):
cnt += PrefMat[j][i]
cnts[i] = - cnt
return tuple(cnts)
def CondorcetFlipBorda(BBox):
return CondorcetPrefCount(BBox,CondorcetFlipBordaCount)
def CondorcetCmbnBordaCount(PrefMat):
cnt1 = CondorcetBordaCount(PrefMat)
cnt2 = CondorcetFlipBordaCount(PrefMat)
return tuple(zip(cnt1,cnt2))
def CondorcetCmbnBorda(BBox):
return CondorcetPrefCount(BBox,CondorcetCmbnBordaCount)
# Black's method
def CondorcetWithFallback(BBox, fallback=Borda, settype="All"):
cond = CondorcetWinner(BBox)
if cond[0]:
return cond
else:
if settype == "All":
fbblts = BBox
else:
fbblts = KeepCandidates(BBox, MaximalSet(BBox,"Smith"))
return (False, fallback(fbblts))
def CondorcetSequentialRunoff(BBox, CWn=False, CLs=False, \
ThresholdFunc=min, DoRound=TopOne):
NewBBox = BBox
rounds = []
while len(NewBBox.Ballots) > 0:
if CWn:
condwin = CondorcetWinner(NewBBox)
if condwin[0]:
rounds.append((1,condwin[1]))
break
if CLs:
condlose = CondorcetLoser(NewBBox)
if condlose[0]:
rounds.append((-1,condlose[1]))
NewBBox = RemoveCandidates(NewBBox, [condlose[1]])
continue
res = DoRound(NewBBox)
rounds.append((0,res))
BottomCands = []
VoteThreshold = ThresholdFunc([r[1] for r in res])
for r in res:
if r[1] <= VoteThreshold:
BottomCands.append(r[0])
BottomCands.sort()
BottomCands = tuple(BottomCands)
NewBBox = RemoveCandidates(NewBBox, BottomCands)
return tuple(rounds)
# http://en.wikipedia.org/wiki/Schulze_method
def SchulzeOrdering(BPMat,i,j):
rc = - cmp(BPMat[i][j],BPMat[j][i])
if rc != 0: return rc
return cmp(i,j)
def OrderingMatrix(n, ordf):
return tuple(( tuple(( ordf(i,j) for j in xrange(n) )) for i in xrange(n) ))
def ListOrderFromMatrix(ordmat):
n = len(ordmat)
Ordering = range(n)
Ordering.sort(lambda i,j: ordmat[i][j])
return tuple(Ordering)
def ListOrderFromMatFunc(n, ordf):
ordmat = OrderingMatrix(n, ordf)
return ListOrderFromMatrix(ordmat)
def BeatpathMatrix(PrefMat):
n = len(PrefMat)
# Initial matrix
BPMat = [n*[0] for k in xrange(n)]
for i in xrange(n):
for j in xrange(n):
if j != i:
if PrefMat[i][j] > PrefMat[j][i]:
BPMat[i][j] = PrefMat[i][j]
# Otherwise zero - BPMat initialized to that
# Variant of the Floyd-Warshall algorithm
for i in xrange(n):
for j in xrange(n):
if j != i:
for k in xrange(n):
if i != k and j != k:
BPMat[j][k] = \
max(BPMat[j][k], min(BPMat[j][i],BPMat[i][k]))
return BPMat
def SchulzePrefOrder(PrefMat):
n = len(PrefMat)
# Beatpaths
BPMat = BeatpathMatrix(PrefMat)
# Sorted List
return ListOrderFromMatFunc(n, lambda i,j: SchulzeOrdering(BPMat,i,j))
def Schulze(BBox): return CondorcetPrefOrder(BBox,SchulzePrefOrder)
# Sorters for multiseat methods mentioned earlier
def SortWithSchulze(CandPrefMat):
Cands, PrefMat = CandPrefMat
CandsOrdered = CondorcetCandPMPrefOrder(Cands, PrefMat, SchulzePrefOrder)
if len(CandsOrdered) > 0:
return CandsOrdered[0]
else:
return None
def CPOSTV(BBox, Num): return SortWithSchulze(CPOSTVMatrix(BBox, Num))
def SchulzeSTV(BBox, Num): return SortWithSchulze(SchulzeSTVMatrix(BBox, Num))
# http://en.wikipedia.org/wiki/Copeland%27s_method
def CopelandPrefCount(PrefMat):
n = len(PrefMat)
Count = n*[0]
for k1 in xrange(n):
for k2 in xrange(n):
Count[k1] += cmp(PrefMat[k1][k2],PrefMat[k2][k1])
return Count
def Copeland(BBox): return CondorcetPrefCount(BBox,CopelandPrefCount)
# http://en.wikipedia.org/wiki/Minimax_condorcet
def ModifiedPrefMat(PrefMat,Which):
n = len(PrefMat)
ModMat = [n*[0] for i in xrange(n)]
if Which == "wins":
for i in xrange(n):
for j in xrange(n):
if PrefMat[i][j] > PrefMat[j][i]:
ModMat[i][j] = PrefMat[i][j]
else:
ModMat[i][j] = 0
elif Which == "marg":
for i in xrange(n):
for j in xrange(n):
ModMat[i][j] = PrefMat[i][j] - PrefMat[j][i]
elif Which == "oppo":
for i in xrange(n):
for j in xrange(n):
ModMat[i][j] = PrefMat[i][j]
return ModMat
def MinimaxPrefCount(PrefMat,Which):
ModMat = ModifiedPrefMat(PrefMat,Which)
n = len(PrefMat)
Scores = n*[0]
for k in xrange(n):
Score = None
for kx in xrange(n):