forked from electionscience/vse-sim
-
Notifications
You must be signed in to change notification settings - Fork 0
/
methods.py
2139 lines (1919 loc) · 83.8 KB
/
methods.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
from mydecorators import autoassign, cached_property, setdefaultattr, decorator
import random
from numpy.lib.scimath import sqrt
from numpy.core.fromnumeric import mean, std
from numpy.lib.function_base import median
from numpy.ma.core import floor, ceil
from numpy import percentile, argsort, sign
from test.test_binop import isnum
from debugDump import *
from math import log, nan
from stratFunctions import *
from dataClasses import *
class Borda(Method):
candScore = staticmethod(mean)
nRanks = 999 # infinity
@classmethod
def results(cls, ballots, **kwargs):
"""
>>> Borda.results([[3,2,1,0]]*5+[[0,3,2,1]]*2)
[0.5357142857142857, 0.5714285714285714, 0.32142857142857145, 0.07142857142857142]
"""
if type(ballots) is not list:
ballots = list(ballots)
n = len(ballots[0])
return list(map(lambda x: mean(x)/n,zip(*ballots)))
@staticmethod
def fillPrefOrder(voter, ballot,
whichCands=None, #None means "all"; otherwise, an iterable of cand indexes
lowSlot=0,
nSlots=None, #again, None means "all"
remainderScore=None #what to give candidates that don't fit in nSlots
):
venum = list(enumerate(voter))
if whichCands:
venum = [venum[c] for c in whichCands]
prefOrder = sorted(venum,key=lambda x:-x[1]) #high to low
Borda.fillCands(ballot, prefOrder, lowSlot, nSlots, remainderScore)
#modifies ballot argument, returns nothing.
@staticmethod
def fillCands(ballot,
whichCands, #list of tuples starting with cand id, in descending order
lowSlot=0,
nSlots=None, #again, None means "all"
remainderScore=None #what to give candidates that don't fit in nSlots
):
if nSlots is None:
nSlots = len(whichCands)
cur = lowSlot + nSlots - 1
for i in range(nSlots):
ballot[whichCands[i][0]] = cur
cur -= 1
if remainderScore is not None:
i += 1
while i < len(whichCands):
ballot[whichCands[i][0]] = remainderScore
i += 1
#modifies ballot argument, returns nothing.
@classmethod
def honBallot(cls, utils, **kw):
ballot = [0] * len(utils)
cls.fillPrefOrder(utils, ballot)
return ballot
@classmethod
def vaBallot(cls, utils, electabilities, polls=None, winProbs=None,
pollingUncertainty=.3, info='e', **kw):
"""Uses a mix of compromising and burial.
>>> Borda.vaBallot((0,1,2,3), [.2, .4, .4, .2])
[1, 0, 3, 2]
"""
if info == 'p':
electabilities = polls
if not winProbs:
winProbs = pollsToProbs(electabilities, pollingUncertainty)
expectedUtility = sum(u*p for u, p in zip(utils, winProbs))
scores = [(u - expectedUtility)*p for u, p in zip(utils, winProbs)]
ballot = [0] * len(utils)
cls.fillPrefOrder(scores, ballot)
return ballot
@classmethod
def fillStratBallot(cls, voter, polls, places, n, stratGap, ballot,
frontId, frontResult, targId, targResult):
"""Mutates the `ballot` argument to be a strategic ballot.
>>> Borda.stratBallot(Voter([-4,-5,-2,-1]), [4,5,2,1])
[3, 0, 1, 2]
"""
nRanks = min(cls.nRanks,n)
if stratGap <= 0:
ballot[frontId], ballot[targId] = (nRanks - 1), 0
else:
ballot[frontId], ballot[targId] = 0, (nRanks - 1)
nRanks -= 2
if nRanks > 0:
cls.fillCands(ballot, places[2:][::-1],
lowSlot=1, nSlots=nRanks, remainderScore=0)
# (don't) return dict(strat=ballot, isStrat=isStrat, stratGap=stratGap)
RankedMethod = Borda #alias
RatedMethod = RankedMethod #Should have same strategies available, plus more
class Plurality(RankedMethod):
nRanks = 2
compLevels = [3]
@classmethod
def results(cls, ballots, **kwargs):
"""
>>> Plurality.results([[1,0]]*3+[[0,1]]*2)
[0.6, 0.4]
"""
if type(ballots) is not list:
ballots = list(ballots)
return list(map(mean,zip(*ballots)))
@staticmethod
def oneVote(utils, forWhom):
ballot = [0] * len(utils)
ballot[forWhom] = 1
return ballot
@classmethod
def honBallot(cls, utils, **kw):
"""Takes utilities and returns an honest ballot
>>> Plurality.honBallot(Voter([-3,-2,-1]))
[0, 0, 1]
"""
#return cls.oneVote(utils, cls.winner(utils))
ballot = [0] * len(utils)
cls.fillPrefOrder(utils, ballot,
nSlots = 1, lowSlot=1, remainderScore=0)
return ballot
@classmethod
def vaBallot(cls, utils, electabilities=None, polls=None, pollingUncertainty=.15,
winProbs=None, info='e', **kw):
"""Uses compromising without a specific target
>>> Plurality.vaBallot((0,1,2), [.3, .3, .2])
[0, 1, 0]
>>> Plurality.vaBallot((0,1,10), [.3, .3, .2])
[0, 0, 1]
"""
if info == 'p':
electabilities = polls
if not winProbs:
winProbs = pollsToProbs(electabilities, pollingUncertainty)
expectedUtility = sum(u*p for u, p in zip(utils, winProbs))
scores = [(u - expectedUtility)*p for u, p in zip(utils, winProbs)]
return cls.oneVote(scores, scores.index(max(scores)))
@classmethod
def compBallot(cls, utils, intensity, candToHelp, candToHurt, **kw):
"""
>>> Plurality.compBallot((0,1,10), 3, candToHelp=1, candToHurt=0)
[0, 1, 0]
>>> Plurality.compBallot((0,1,10), 3, candToHelp=2, candToHurt=0)
[0, 0, 1]
"""
if intensity < 3 or utils[candToHelp] <= utils[candToHurt]:
return super().compBallot(utils, intensity, candToHelp, candToHurt, **kw)
else:
return cls.oneVote(utils, candToHelp)
#
# @classmethod
# def xxstratBallot(cls, voter, polls, places, n,
# frontId, frontResult, targId, targResult):
# """Takes utilities and returns a strategic ballot
# for the given "polling" info.
#
# >>> Plurality().stratBallotFor([4,2,1])(Plurality, Voter([-4,-2,-1]))
# [0, 1, 0]
# """
# stratGap = voter[targId] - voter[frontId]
# if stratGap <= 0:
# #winner is preferred; be complacent.
# isStrat = False
# strat = cls.oneVote(voter, frontId)
# else:
# #runner-up is preferred; be strategic in iss run
# isStrat = True
# #sort cuts high to low
# #cuts = (cuts[1], cuts[0])
# strat = cls.oneVote(voter, targId)
# return dict(strat=strat, isStrat=isStrat, stratGap=stratGap)
def top2(noRunoffMethod):
"""Returns a top-2 variant of the given voting method
"""
class Top2Version(noRunoffMethod):
"""Ballots are (r1Ballot, r2Preferences) tuples
"""
@classmethod
def results(cls, ballots):
r1Ballots, r2Preferences = zip(*ballots)
baseResults = super().results(r1Ballots)
(runnerUp,top) = sorted(range(len(baseResults)), key=lambda i: baseResults[i])[-2:]
upset = sum(sign(rank[runnerUp] - rank[top]) for rank in r2Preferences)
if upset > 0:
baseResults[runnerUp] = baseResults[top] + 0.01
return baseResults
@classmethod
def prefOrder(cls, utils):
order = [0]*len(utils)
Borda.fillPrefOrder(utils, order)
return order
@classmethod
def honBallot(cls, utils, **kw):
return super().honBallot(utils, **kw), cls.prefOrder(utils)
@classmethod
def vaBallot(cls, utils, electabilities=None, polls=None, winProbs=None,
pollingUncertainty=.15, info='e', probFunc=adaptiveTieFor2, **kw):
if info == 'p':
electabilities = polls
if not winProbs:
winProbs = probFunc(electabilities, pollingUncertainty)
return (super().vaBallot(utils, winProbs=winProbs,
pollingUncertainty=pollingUncertainty),
cls.prefOrder(utils))
@classmethod
def bulletBallot(cls, utils, **kw):
return super().bulletBallot(utils), cls.prefOrder(utils)
@classmethod
def compBallot(cls, utils, intensity, candToHelp, candToHurt, **kw):
return (super().compBallot(utils, intensity, candToHelp, candToHurt),
cls.prefOrder(utils))
@classmethod
def diehardBallot(cls, utils, intensity, candToHelp, candToHurt, **kw):
return (super().diehardBallot(utils, intensity, candToHelp, candToHurt),
cls.prefOrder(utils))
@classmethod
def stratBallot(cls, voter, *args, **kws):
return (super().stratBallot(voter, *args, **kws),
cls.prefOrder(voter))
@classmethod
def abstain(cls, utils, **kw):
return [0]*len(utils), [0]*len(utils)
Top2Version.__name__ = noRunoffMethod.__name__ + "Top2"
return Top2Version
class PluralityTop2(top2(Plurality)):
"""top2(Plurality).vaBallot can yield ridiculous results when used by the entire electorate
since it's based on causal decision theory. This class fixes that.
>>> PluralityTop2.results([([0, 0, 1], [0, 1, 2])]*3+[([1, 0, 0], [2, 1, 0])]*2)
[0.4, 0.0, 0.6]
>>> PluralityTop2.results([([0, 0, 1], [0, 1, 2])]*5+[([1, 0, 0], [2, 1, 0])]*4+[([0, 1, 0], [1, 2, 0])]*2)
[0.46454545454545454, 0.18181818181818182, 0.45454545454545453]
>>> PluralityTop2.honBallot((0,1,5,2,3))
([0, 0, 1, 0, 0], [0, 1, 4, 2, 3])
>>> PluralityTop2.compBallot((0,1,10), 3, candToHelp=1, candToHurt=0)
([0, 1, 0], [0, 1, 2])
>>> PluralityTop2.stratBallot([0,1,2,3],[.51,.5,.49,.4])
([0, 1, 0, 0], [0, 1, 2, 3])
"""
@classmethod
def vaBallot(cls, utils, electabilities=None, **kw):
"""
>>> PluralityTop2.vaBallot((0,1,2), [.3, .3, .2])
([0, 0, 1], [0, 1, 2])
>>> PluralityTop2.vaBallot((0,1,2,3), [.3, .3, .2, .1])
([0, 0, 1, 0], [0, 1, 2, 3])
"""
if electabilities and utils.index(max(utils)) == electabilities.index(max(electabilities)):
return cls.honBallot(utils)
else: return super().vaBallot(utils, electabilities=electabilities, **kw)
def makeScoreMethod(topRank=10, asClass=False):
class Score0to(Method):
"""Score voting, 0-10.
Strategy establishes pivots
>>> Score().stratBallotFor([0,1,2])(Score, Voter([5,6,7]))
[0, 0, 10]
>>> Score().stratBallotFor([2,1,0])(Score, Voter([5,6,7]))
[0, 10, 10]
>>> Score().stratBallotFor([1,0,2])(Score, Voter([5,6,7]))
[0, 5.0, 10]
Strategy (kinda) works for ties
>>> Score().stratBallotFor([1,0,2])(Score, Voter([5,6,6]))
[0, 10, 10]
>>> Score().stratBallotFor([1,0,2])(Score, Voter([6,6,7]))
[0, 0, 10]
>>> Score().stratBallotFor([1,0,2])(Score, Voter([6,7,6]))
[10, 10, 10]
>>> Score().stratBallotFor([1,0,2])(Score, Voter([6,5,6]))
[10, 0, 10]
"""
#>>> qs += [Score().resultsFor(PolyaModel()(101,2),Score.honBallot)[0] for i in range(800)]
#>>> std(qs)
#2.770135393419682
#>>> mean(qs)
#5.1467202970297032
bias2 = 2.770135393419682
#>>> qs5 = [Score().resultsFor(PolyaModel()(101,5),Score.honBallot)[0] for i in range(400)]
#>>> mean(qs5)
#4.920247524752476
#>>> std(qs5)
#2.3536762480634343
bias5 = 2.3536762480634343
compLevels = [1,2]
diehardLevels = [1,2, 4]
@classmethod
def candScore(cls,scores):
"""Takes the list of votes for a candidate; returns the candidate's score.
Don't just use mean because we want to normalize to [0,1]"""
return mean(scores)/cls.topRank
@classmethod
def interpolatedBallot(cls, utils, lowThreshold, highThreshold):
"""
>>> Score.interpolatedBallot([0,1,2,3,4,5], 1.5, 3.5)
[0, 0, 1.0, 4.0, 5, 5]
"""
ballot = []
for util in utils:
if util < lowThreshold:
ballot.append(0)
elif util > highThreshold:
ballot.append(cls.topRank)
else:
ballot.append(floor((cls.topRank + .99)*(util-lowThreshold)/(highThreshold-lowThreshold)))
return ballot
def __str__(self):
if self.topRank == 1:
return "IdealApproval"
return self.__class__.__name__ + str(self.topRank)
@classmethod
def honBallot(cls, utils, **kw):
"""Takes utilities and returns an honest ballot (on 0..10)
honest ballots work as expected
>>> Score().honBallot(Score, Voter([5,6,7]))
[0.0, 5.0, 10.0]
>>> Score().resultsFor(DeterministicModel(3)(5,3),Score().honBallot)["results"]
[4.0, 6.0, 5.0]
"""
#raise Exception("NOT")
#bot = min(utils)
#scale = max(utils)-bot
#return [floor((cls.topRank + .99) * (util-bot) / scale) for util in utils]
return cls.mean0iBallot(utils, exp=1)
@classmethod
def zeroInfoBallot(cls, utils, exp=2, bottomSD=float('inf'), **kw):
"""
Casts an honest ballot without the use of any polling data.
Less influenced by exceptionally bad candidates than honBallot when bottomSD is low.
When exp > 1, spreads out the top scores more than the bottom ones.
>>> Score.zeroInfoBallot([0,1.1,2], 2)
[0.0, 1.0, 5.0]
>>> Score.zeroInfoBallot([0,1.1,2], .5)
[0.0, 4.0, 5.0]
>>> Score.zeroInfoBallot([0,1,2,3,4,5,6], 2)
[0.0, 0.0, 0.0, 0.0, 2.0, 3.0, 5.0]
>>> Score.zeroInfoBallot([-10,1,2,3,4,5,6], 2,2)
[0.0, 2.0, 3.0, 3.0, 4.0, 5.0, 5.0]
>>> Score.zeroInfoBallot([-10,1,2,3,4,5,6], 2,1)
[0.0, 1.0, 1.0, 2.0, 3.0, 4.0, 5.0]
"""
expectedUtility = sum(utils)/len(utils)
effectiveWorst = max(min(utils), expectedUtility - bottomSD*std(utils))
adjustedUtils = [max(u - effectiveWorst, 0)**exp for u in utils]
return cls.interpolatedBallot(adjustedUtils, 0, max(adjustedUtils))
@classmethod
def mean0iBallot(cls, utils, exp=1, **kw):
"""
Casts an honest ballot without the use of any polling data.
"""
meanUtility = sum(utils)/len(utils)
bestUtility = max(utils)
bottom = max(bestUtility - 2*(bestUtility-meanUtility), min(utils))
adjustedUtils = [max(u - bottom, 0)**exp for u in utils]
return cls.interpolatedBallot(adjustedUtils, 0, max(adjustedUtils))
@classmethod
def exaggeratedBallot(cls, utils, pickiness=0.4, **kw):
"""Returns a ballot based on utils and pickiness
with all candidates receiving either 0 or the maximum score.
pickiness=0 corresponds to vaBallot with equal polling for all candidates
pickiness=1 corresponds to bullet voting
pickiness=0.4 seems about optimal under KSModel
"""
expectedUtility = sum(u for u in utils)/len(utils)
best = max(utils)
normalizedUtils = [(u - expectedUtility)/(best - expectedUtility)
for u in utils]
return [cls.topRank if u >= pickiness else 0 for u in normalizedUtils]
@classmethod
def vaBallot(cls, utils, electabilities=None, polls=None, winProbs=None,
pollingUncertainty=.15, info='e', **kw):
if info == 'p':
electabilities = polls
if not winProbs:
winProbs = pollsToProbs(electabilities, pollingUncertainty)
expectedUtility = sum(u*p for u, p in zip(utils, winProbs))
return [cls.topRank if u > expectedUtility else 0 for u in utils]
@classmethod
def vaIntermediateBallot(cls, utils, electabilities=None, polls=None,
winProbs=None, pollingUncertainty=.15, midScoreWillingness=0.7, info='e', **kw):
"""Uses significant, but not total, strategic exaggeration
>>> Score.vaIntermediateBallot([0,1,2,3,4,5], [.6,.4,.4,.4,.4,.5])
[0.0, 3.0, 5, 5, 5, 5]
"""
if info == 'p':
electabilities = polls
if not winProbs:
winProbs = pollsToProbs(electabilities, pollingUncertainty)
expectedUtility = sum(u*p for u, p in zip(utils, winProbs))
if all(u == utils[0] for u in utils[1:]):
return [0]*len(utils)
lowThreshold = max(min(utils), expectedUtility - midScoreWillingness*std(utils))
highThreshold = min(max(utils), expectedUtility + midScoreWillingness*std(utils))
#this is wrong. We should use a standard deviation that's weighted
#by each candidate's chance of winning
return cls.interpolatedBallot(utils, lowThreshold, highThreshold)
@classmethod
def diehardBallot(cls, utils, intensity, candToHelp, candToHurt, **kw):
if intensity < 1 or utils[candToHelp] <= utils[candToHurt]:
return super().diehardBallot(utils, intensity, candToHelp, candToHurt, **kw)
if intensity == 1:
return cls.interpolatedBallot(utils, utils[candToHurt], utils[candToHelp])
if intensity == 4:
return cls.bulletBallot(utils)
else:
return [cls.topRank if u >= utils[candToHelp] else 0 for u in utils]
@classmethod
def compBallot(cls, utils, intensity, candToHelp, candToHurt, **kw):
if intensity < 1 or utils[candToHelp] <= utils[candToHurt]:
return super().diehardBallot(utils, intensity, candToHelp, candToHurt, **kw)
if intensity == 1:
return cls.interpolatedBallot(utils, utils[candToHurt], utils[candToHelp])
else:
return [cls.topRank if u > utils[candToHurt] else 0 for u in utils]
@classmethod
def bulletBallot(cls, utils, **kw):
best = utils.index(max(utils))
ballot = [0]*len(utils)
ballot[best] = cls.topRank
return ballot
@classmethod
def fillStratBallot(cls, voter, polls, places, n, stratGap, ballot,
frontId, frontResult, targId, targResult):
"""Returns a (function which takes utilities and returns a strategic ballot)
for the given "polling" info."""
cuts = [voter[frontId], voter[targId]]
if stratGap > 0:
#sort cuts high to low
cuts = (cuts[1], cuts[0])
if cuts[0] == cuts[1]:
strat = [(cls.topRank if (util >= cuts[0]) else 0) for util in voter]
else:
strat = [max(0,min(cls.topRank,floor(
(cls.topRank + .99) * (util-cuts[1]) / (cuts[0]-cuts[1])
)))
for util in voter]
for i in range(n):
ballot[i] = strat[i]
Score0to.topRank = topRank
if asClass:
return Score0to
return Score0to()
class Score(makeScoreMethod(5, True)):
"""
>>> Score.honBallot((0,1,2,3,4,5,6,7,8,9,10,11))
[0.0, 0.0, 1.0, 1.0, 2.0, 2.0, 3.0, 3.0, 4.0, 4.0, 5.0, 5.0]
>>> Score.vaBallot((0,1,2,3),[.4,.4,.4,.4])
[0, 0, 5, 5]
>>> Score.vaBallot((0,1,2,3),[.4,.4,.4,.6])
[0, 0, 0, 5]
>>> Score.vaBallot((0,1,2,3),[.6,.4,.4,.4])
[0, 5, 5, 5]
"""
pass
class Approval(makeScoreMethod(1,True)):
diehardLevels = [1, 4]
compLevels = [1,3]
@classmethod
def zeroInfoBallot(cls, utils, electabilities=None, polls=None, pickiness=0.4, **kw):
"""Returns a ballot based on utils and pickiness
pickiness=0 corresponds to vaBallot with equal polling for all candidates
pickiness=1 corresponds to bullet voting
pickiness=0.4 seems about optimal under KSModel
>>> Approval.zeroInfoBallot([1,2,3,10], pickiness=0)
[0, 0, 0, 1]
>>> Approval.zeroInfoBallot([1,2,3,-10], pickiness=0)
[1, 1, 1, 0]
>>> Approval.zeroInfoBallot([1,2,3,-10], pickiness=0.6)
[0, 1, 1, 0]
"""
expectedUtility = sum(u for u in utils)/len(utils)
best = max(utils)
normalizedUtils = [(u - expectedUtility)/(best - expectedUtility)
for u in utils]
return [1 if u >= pickiness else 0 for u in normalizedUtils]
@classmethod
def honBallot(cls, utils, **kw):
return Approval.zeroInfoBallot(utils, pickiness=0.4)
@classmethod
def diehardBallot(cls, utils, intensity, candToHelp, candToHurt, **kw):
"""
>>> Approval.diehardBallot([-10,1,2,3,4,10],1,4,2)
[0, 0, 0, 0, 1, 1]
"""
if intensity == 1:
return super().diehardBallot(utils, 2, candToHelp, candToHurt, **kw)
else:
return super().diehardBallot(utils, intensity, candToHelp, candToHurt, **kw)
@classmethod
def compBallot(cls, utils, intensity, candToHelp, candToHurt, **kw):
"""
>>> Approval.compBallot([-10,1,2,3,4,20],1,4,2)
[0, 0, 0, 1, 1, 1]
>>> Approval.compBallot([-10,1,2,3,4,20],0,4,2)
[0, 0, 0, 0, 0, 1]
"""
if intensity == 1:
return super().compBallot(utils, 2, candToHelp, candToHurt, **kw)
elif intensity == 3:
return Plurality.compBallot(utils, 3, candToHelp, candToHurt, **kw)
else:
return super().compBallot(utils, intensity, candToHelp, candToHurt, **kw)
class ApprovalTop2(top2(Approval)):
"""
>>> ApprovalTop2.vaBallot([0,1,10],[.5,.5,.2])
([0, 0, 1], [0, 1, 2])
>>> ApprovalTop2.vaBallot([0,1,2,10],[.5,.5,.3,.2])
([0, 0, 1, 1], [0, 1, 2, 3])
"""
@classmethod
def vaBallot2(cls, utils, electabilities=None, polls=None, winProbs=None,
pollingUncertainty=.15, info='e', **kw):
if info == 'p':
electabilities = polls
if not winProbs:
winProbs = pollsToProbs(electabilities, pollingUncertainty)
return [1 if
sum((u1 - u2)*p1*p2*(1-p1-p2) for u2, p2 in zip(utils, winProbs)) > 0 else 0
for u1, p1 in zip(utils, winProbs)], cls.prefOrder(utils)
@classmethod
def zeroInfoBallot(cls, utils, **kw):
return super().zeroInfoBallot(utils, **kw), cls.prefOrder(utils)
@classmethod
def diehardBallot(cls, utils, intensity, candToHelp, candToHurt, **kw):
"""
>>> ApprovalTop2.diehardBallot([0, 8, 9, 10], 4, 2, 1)
([0, 0, 0, 1], [0, 1, 2, 3])
>>> ApprovalTop2.diehardBallot([0, 8, 9, 10], 1, 2, 1)
([0, 0, 1, 1], [0, 1, 2, 3])
"""
if intensity == 4:
return cls.bulletBallot(utils)
else:
return super().diehardBallot(utils, intensity, candToHelp, candToHurt, **kw)
def BulletyApprovalWith(bullets=0.5, asClass=False):
class BulletyApproval(Score(1,True)):
bulletiness = bullets
def __str__(self):
return "BulletyApproval" + str(round(self.bulletiness * 100))
@classmethod
def honBallot(cls, utils, **kw):
"""Takes utilities and returns an honest ballot (on 0..10)
honest ballots work as expected
>>> Score().honBallot(Score, Voter([5,6,7]))
[0.0, 5.0, 10.0]
>>> Score().resultsFor(DeterministicModel(3)(5,3),Score().honBallot)["results"]
[4.0, 6.0, 5.0]
"""
if random.random() > cls.bulletiness:
return cls.__bases__[0].honBallot(cls, utils)
best = max(utils)
return [1 if util==best else 0 for util in utils]
if asClass:
return BulletyApproval
return BulletyApproval()
def oldCoefficients(utils, electabilities, pollingUncertainty=0.15, scoreImportance=0.17, probFunc=adaptiveTieFor2):
"""Don't use"""
winProbs = pollsToProbs(electabilities, pollingUncertainty)
runoffCoefficients = [[(u1 - u2)*p1*p2
for u2, p2 in zip(utils, winProbs)]
for u1, p1 in zip(utils, winProbs)]
eRunnerUpUtil = sum(u*p for u, p in zip(utils, probFunc(electabilities)))
#scoreCoefficients[i] is how vauable it is for i to have a high score
scoreCoefficients = [(u-eRunnerUpUtil)*p*scoreImportance
for u, p in zip(utils, probFunc(electabilities))]
return scoreCoefficients, runoffCoefficients
def getCoefficients(utils, electabilities, pollingUncertainty=0.15, scoreImportance=0.2):
"""Don't use"""
nCands = len(utils)
winProbs = pollsToProbs(electabilities, pollingUncertainty)
scoreC = [0]*nCands
runoffC = [[(u1 - u2)*p1*p2
for u2, p2 in zip(utils, winProbs)]
for u1, p1 in zip(utils, winProbs)]
for winner in range(nCands):
runnerUpProbs = list(pollsToProbs(electabilities[:winner] + electabilities[winner+1:], pollingUncertainty))
runnerUpProbs = runnerUpProbs[:winner] + [0] + runnerUpProbs[winner:]
for runnerUp in range(nCands):
if winner == runnerUp: continue
orderProb = winProbs[winner] * runnerUpProbs[runnerUp]
#minF, maxF = min(winner, runnerUp), max(winner, runnerUp)
#thirdProbs = pollsToProbs(
#electabilities[:minF] + electabilities[minF+1:maxF] + electabilities[maxF+1:], pollingUncertainty)
for third in range(nCands):
if third == winner or third == runnerUp:
continue
upsetProb = pollsToProbs([electabilities[winner], (electabilities[runnerUp] + electabilities[third])/2], pollingUncertainty)[1]
scoreC[third] += orderProb*runnerUpProbs[third]*upsetProb*(utils[third] - utils[runnerUp])*scoreImportance
return scoreC, runoffC
def simpleCoefficients(utils, electabilities, pollingUncertainty=0.3, scoreImportance=0.3):
"""Gives the score and runoff coefficients for STAR's vaBallot."""
nCands = len(utils)
winProbs = pollsToProbs(electabilities, pollingUncertainty)
scoreC = [sum((u1 - u2)*p1*p2*(1-p1-p2)*scoreImportance #approximates the probability that 1 and 2 will tie for the second runoff slot and the win in the runoff
for u2, p2 in zip(utils, winProbs))
for u1, p1 in zip(utils, winProbs)]
runoffC = [[(u1 - u2)*p1*p2
for u2, p2 in zip(utils, winProbs)]
for u1, p1 in zip(utils, winProbs)]
return scoreC, runoffC
def makeSTARMethod(topRank=5):
"STAR Voting"
score0to = makeScoreMethod(topRank,True)
class STAR0to(score0to):
stratTargetFor = Method.stratTarget3
diehardLevels = [1,2,3,4]
compLevels = [1,2,3]
@classmethod
def results(cls, ballots, **kwargs):
"""STAR results.
>>> STAR().resultsFor(DeterministicModel(3)(5,3),Irv().honBallot)["results"]
[0, 1, 2]
>>> STAR().results([[0,1,2]])[2]
2
>>> STAR().results([[0,1,2],[2,1,0]])[1]
0
>>> STAR().results([[0,1,2]] * 4 + [[2,1,0]] * 3 + [[1,2,0]] * 2)
[2, 0, 1]
"""
baseResults = super(STAR0to, cls).results(ballots, **kwargs)
(runnerUp,top) = sorted(range(len(baseResults)), key=lambda i: baseResults[i])[-2:]
upset = sum(sign(ballot[runnerUp] - ballot[top]) for ballot in ballots)
if upset > 0:
baseResults[runnerUp] = baseResults[top] + 0.01
return baseResults
@classmethod
def vaBallot(cls, utils, electabilities=None, polls=None, winProbs=None,
pollingUncertainty=.3, scoreImportance=0.3, info='e', coeffFunc=simpleCoefficients, **kw):
"""
>>> STAR.vaBallot([0,1,2,3,4,5],[.5,.5,.5,.5,.5,.5],scoreImportance=0.1)
[0.0, 1.0, 2.0, 3.0, 4.0, 5.0]
>>> STAR.vaBallot([0,1,2,3,4,5],[.5,.5,.5,.5,.5,.5],scoreImportance=0.2)
[0.0, 0.0, 1.0, 4.0, 5.0, 5.0]
>>> STAR.vaBallot([0,1,2,3,4,5],[.5,.5,.5,.5,.5,.5],scoreImportance=3)
[0.0, 0.0, 0.0, 5.0, 5.0, 5.0]
>>> STAR.vaBallot([0,1,2,3,4,5],[.6,.5,.5,.5,.5,.5],scoreImportance=0.2)
[0.0, 1.0, 2.0, 5.0, 5.0, 5.0]
"""
if info == 'p':
electabilities = polls
#if not winProbs:
#winProbs = pollsToProbs(electabilities, pollingUncertainty)
#runoffCoefficients[i][j] is how valuable it is to score i over j
#scoreCoefficients[i] is how vauable it is for i to have a high score
scoreCoefficients, runoffCoefficients = coeffFunc(utils, electabilities, pollingUncertainty, scoreImportance)
#create a tentative ballot
numCands = len(utils)
bot = min(utils)
scale = max(utils)-bot
ballot = [floor((cls.topRank + .99) * (util-bot) / scale) for util in utils]
#optimize the ballot
improvementFound = True
while improvementFound:
improvementFound = False
for cand in range(numCands):
#Should cand be scored higher?
if (ballot[cand] < cls.topRank and
sum(runoffCoefficients[cand][j]*sign(ballot[cand] + 1 - ballot[j])
for j in range(numCands))
+ scoreCoefficients[cand]
> sum(runoffCoefficients[cand][j]*sign(ballot[cand] - ballot[j])
for j in range(numCands))):
ballot[cand] += 1
improvementFound = True
#Should cand be scored lower?
elif (ballot[cand] > 0 and
sum(runoffCoefficients[cand][j]*sign(ballot[cand] - 1 - ballot[j])
for j in range(numCands))
- scoreCoefficients[cand]
> sum(runoffCoefficients[cand][j]*sign(ballot[cand] - ballot[j])
for j in range(numCands))):
ballot[cand] -= 1
improvementFound = True
return ballot
@classmethod
def compBallot(cls, utils, intensity, candToHelp, candToHurt, baseBallotFunc=None, **kw):
"""Intensity determines the strategy used. 0 naive, 1 is honest, 2 semi-honest, 3 is favorite betrayal
>>> STAR.compBallot([0,1,2,3,4,5,6,7],0,5,3)
[0.0, 0.0, 1.0, 2.0, 3.0, 4.0, 5.0, 5.0]
>>> STAR.compBallot([0,1,2,3,4,5,6,7],1,5,3)
[0, 0, 0, 0, 3.0, 4, 5.0, 5.0]
>>> STAR.compBallot([0,1,2,3,4,5,6,7],2,5,3)
[0, 0, 0, 0, 3.0, 5, 5, 5]
>>> STAR.compBallot([0,1,2,3,4,5,6,7],3,5,3)
[0, 0, 0, 0, 1, 5, 1, 1]
"""
if baseBallotFunc is None: baseBallotFunc = cls.honBallot
baseBallot = baseBallotFunc(utils, candToHelp=candToHelp, candToHurt=candToHurt, **kw)
helpUtil, hurtUtil = utils[candToHelp], utils[candToHurt]
if intensity < 1 or helpUtil <= hurtUtil:
return baseBallot
if intensity == 1:
for i, u in enumerate(utils):
if u >= helpUtil:
baseBallot[i] = cls.topRank
elif u > hurtUtil:
baseBallot[i] = cls.topRank - 1#max(, baseBallot[i])
elif u == hurtUtil:
baseBallot[i] = min(1, baseBallot[i])
elif u < hurtUtil:
baseBallot[i] = 0
if intensity == 2:
for i, u in enumerate(utils):
if u > hurtUtil:
baseBallot[i] = cls.topRank
elif u <= hurtUtil:
baseBallot[i] = 0
if intensity >= 3:
baseBallot = [1 if u > hurtUtil else 0 for u in utils]
baseBallot[candToHelp] = cls.topRank
return baseBallot
@classmethod
def diehardBallot(cls, utils, intensity, candToHelp, candToHurt, electabilities=None, polls=None,
baseBallotFunc=None, info='p', **kw):
"""Intensity determines the strategy used. 0 naive, 1 is honest, 2 semi-honest, 3 is pushover,
and 4 is bullet voting
>>> STAR.diehardBallot([0,1,2,3,4,5,6,7],1,5,3)
[0.0, 0.0, 1, 1, 3.0, 5, 5, 5]
>>> STAR.diehardBallot([0,1,2,3,4,5,6,7],2,5,3)
[0, 0, 0, 0, 3.0, 5, 5, 5]
>>> STAR.diehardBallot([0,1,2,3,4,5,6,7],3,5,3,polls=[.4,.6,.4,.6,.4,.5,.4,.6])
[4, 0, 4, 0, 4, 5, 5, 5]
>>> STAR.diehardBallot([0,1,2,3,4,5,6,7],4,5,3)
[0, 0, 0, 0, 0, 0, 0, 5]
"""
if info == 'e':
polls = electabilities
if baseBallotFunc is None: baseBallotFunc = cls.honBallot
baseBallot = baseBallotFunc(utils, polls=polls, candToHelp=candToHelp, candToHurt=candToHurt, **kw)
helpUtil, hurtUtil = utils[candToHelp], utils[candToHurt]
if intensity < 1 or helpUtil <= hurtUtil:
return baseBallot
if intensity == 1:
for i, u in enumerate(utils):
if u <= hurtUtil:
baseBallot[i] = 0
elif u < helpUtil:
baseBallot[i] = 1
elif u == helpUtil:
baseBallot[i] = max(cls.topRank - 1, baseBallot[i])
elif u > helpUtil:
baseBallot[i] = cls.topRank
if intensity == 2:
for i, u in enumerate(utils):
if u < helpUtil:
baseBallot[i] = 0
elif u >= helpUtil:
baseBallot[i] = cls.topRank
if intensity == 3:
for i, u in enumerate(utils):
if u >= helpUtil:
baseBallot[i] = cls.topRank
elif polls[i] < polls[candToHelp]:
baseBallot[i] = cls.topRank - 1
else:
baseBallot[i] = 0
baseBallot[candToHurt] = 0
if intensity == 4:
return cls.bulletBallot(utils)
return baseBallot
@classmethod
def always510Ballot(cls, utils, **kw):
"""Gives the first choice candidate a 5, second choice a 1, and last choice a 0.
Only really intended for three-candidate elections.
>>> STAR.always510Ballot([9,5,10])
[1, 0, 5]
"""
return [cls.topRank if u == max(utils) else 0 if u == min(utils) else 1 for u in utils]
@classmethod
def never23Ballot(cls, utils, **kw):
"""Gives the first choice a 5, last a 0, and everyone else 1 or 4
>>> STAR.never23Ballot([0,2,3,5])
[0, 1, 4, 5]
"""
high, low = max(utils), min(utils)
ballot = []
for u in utils:
if u == high:
ballot.append(cls.topRank)
elif u == low:
ballot.append(0)
elif high - u < u - low:
ballot.append(cls.topRank - 1)
else:
ballot.append(1)
return ballot
@classmethod
def utilGapBallot(cls, utils, **kw):
"""With six or fewer candidates, gives each candidate a different score.
With five or fewer candidates, there is only one gap between scores
and it occurs where there is the greatest gap in utilities.
With seven or more candidates, the canddiates with the most similar
utilities are given the same scores.
Does not work well when some utilities are equal.
>>> STAR.utilGapBallot([0,6,5,7])
[0, 4, 3, 5]
>>> STAR.utilGapBallot([0,6,5,2])
[0, 5, 4, 1]
>>> STAR.utilGapBallot([0,1,2])
[0, 1, 5]
>>> STAR.utilGapBallot([0,1,2,3,4,10,11,13])
[0, 0, 1, 1, 2, 3, 4, 5]
"""
sortedUtils = sorted(enumerate(utils), key=lambda x: x[1])
high, low = max(utils), min(utils)
n = len(utils)
ballot = [0]*n
if n <= cls.topRank + 1:
maxGap = 0
gapLoc = None
for i in range(n-1):
if sortedUtils[i + 1][1] - sortedUtils[i][1] >= maxGap:
maxGap = sortedUtils[i + 1][1] - sortedUtils[i][1]
gapLoc = (sortedUtils[i + 1][1] + sortedUtils[i][1])/2
for rank, (cand, util) in enumerate(sortedUtils):
if util < gapLoc:
ballot[cand] = rank
else:
ballot[cand] = rank + cls.topRank + 1 - n
else:
utilRanges = [[u,u] for u in sorted(utils)]
#use a greedy algorithm to put most similar utilities together
while len(utilRanges) > cls.topRank + 1:
minSpread = float('inf')
minLoc = None
for i in range(len(utilRanges) - 1):
spread = utilRanges[i+1][1] - utilRanges[i][0]
if spread < minSpread:
minSpread = spread
minLoc = i
utilRanges[minLoc][1] = utilRanges[minLoc+1][1]
del utilRanges[minLoc+1]
score = 0
for cand, util in sortedUtils:
if util > utilRanges[score][1]:
score += 1
ballot[cand] = score
return ballot
@classmethod
def top6Ballot(cls, utils, electabilities=None, polls=None, info='e', **kw):
"""Gives each of the six most viable candidates a different score
and other candidates the score of the frontrunner their utility is the closest to.
>>> STAR.top6Ballot([0,1,2,3,4,5,6,7,8,9,20], [.3,.4,.35,.41,.42,.43,.2,.3,.415,.41,.1])
[0, 0, 0, 1, 2, 3, 3, 4, 4, 5, 5]
"""
if len(utils) <= cls.topRank:
return cls.utilGapBallot(utils)
if info == 'e':
polls = electabilities
frontrunnerIDs = sorted(enumerate(polls), key = lambda x: -x[1])[:cls.topRank+1]
frontUtils = sorted(utils[i] for i, _ in frontrunnerIDs)
ballot = []
for u in utils:
if u >= frontUtils[cls.topRank]:
ballot.append(cls.topRank)
else:
i = 0
while u > frontUtils[i+1]:
i += 1
if u - frontUtils[i] <= frontUtils[i+1] - u:
ballot.append(i)
else:
ballot.append(i+1)
return ballot
#@classmethod
#def defaultfgs(cls):
#return super().defaultfgs()\
#+ [(cls.top6Ballot, targs) for targs in [selectRand, select21]]
if topRank==5:
STAR0to.__name__ = "STAR"
else:
STAR0to.__name__ = "STAR" + str(topRank)
return STAR0to
class STAR(makeSTARMethod(5)): pass
def toVote(cutoffs, util):
"""maps one util to a vote, using cutoffs.
Used by Mav, but declared outside to avoid method binding overhead."""
for vote in range(len(cutoffs)):
if util <= cutoffs[vote]:
return vote
return vote + 1
class Mav(Method):
"""Majority Approval Voting
"""
#>>> mqs = [Mav().resultsFor(PolyaModel()(101,5),Mav.honBallot)[0] for i in range(400)]
#>>> mean(mqs)
#1.5360519801980208
#>>> mqs += [Mav().resultsFor(PolyaModel()(101,5),Mav.honBallot)[0] for i in range(1200)]
#>>> mean(mqs)
#1.5343069306930679
#>>> std(mqs)
#1.0970202515275356