def simple_model(name, methods, seed=0, numvoters=100, cnum=3, trialnum=1, ndim=1, stol=1, base='linear'): """Simple Election model """ e = spatial.Election(None, None, seed=seed, name=name) v = spatial.Voters(seed=seed, tol=stol, base=base) v.add_random(numvoters, ndim=ndim) msg_base = 'seed=%s, numvoters=%s, cnum=%s, trial=%s, ndim=%s, stol=%s, base=%s' cseed = seed * trialnum for trial in range(trialnum): logger.debug(msg_base, seed, numvoters, cnum, trial, ndim, stol, base) c = spatial.Candidates(v, seed=trial + cseed) c.add_random(cnum, sdev=1.5) e.set_models(voters=v, candidates=c) # Save parameters e.user_data(num_voters=numvoters, num_candidates=cnum, num_dimensions=ndim, voter_tolerance=stol) for method in methods: e.run(etype=method) return e
def test_all(): numvoters = 50 num_candidates = 6 numwinners_list = [1, 3, 5] for ii in range(50): v = spatial.Voters(seed=ii,) v.add_random(numvoters=numvoters, ndim=2, ) c = spatial.Candidates(voters=v, seed=0) c.add_random(cnum=num_candidates, sdev=1.0) e = spatial.Election(voters=v, candidates=c) scores = e.ballotgen.get_honest_ballots( etype=votesim.votemethods.SCORE ) ranks = e.ballotgen.get_honest_ballots( etype=votesim.votemethods.IRV ) for etype in ranked_methods: for numwinners in numwinners_list: runner = eRunner(etype=etype, ballots=ranks, numwinners=numwinners) winners = np.unique(runner.winners) assert len(winners) == numwinners, etype for etype in scored_methods: for numwinners in numwinners_list: runner = eRunner(etype=etype, ballots=scores, numwinners=numwinners) winners = np.unique(runner.winners) assert len(winners) == numwinners, etype
def test_case(): """Test a case that failed during simple test benchmark. After investigation it seems like this is a case where all ballot scores are zero. """ seed = 0 numvoters = 101 cnum = 3 trial = 54 trialnum = 100 ndim = 2 stol = 0.25 base = 'linear' name = 'test' e = spatial.Election(None, None, seed=seed, name=name) v = spatial.Voters(seed=seed, tol=stol, base=base) v.add_random(numvoters, ndim=ndim) cseed = seed * trialnum c = spatial.Candidates(v, seed=trial + cseed) c.add_random(cnum, sdev=1.5) e.set_models(voters=v, candidates=c) ballots = e.ballotgen.get_honest_ballots('maj_judge') result = e.run('maj_judge') assert np.all(result.ties == [0, 1, 2]) return
def test_ranked_bury(): v = spatial.Voters(seed=0) v.add(voter_pref) c = spatial.Candidates(v) c.add(candidate_pref) strategy = { 'tactics': 'bury', 'subset': '', 'ratio': 1, 'underdog': None, 'frontrunnertype': 'eliminate' } s2 = spatial.Strategies(v).add(**strategy) e2 = spatial.Election(voters=v, candidates=c, strategies=s2) e2.run('ranked_pairs') right = [[1, 2, 0], [1, 2, 0], [1, 2, 0], [1, 2, 0], [1, 2, 0], [1, 2, 0], [1, 2, 0], [0, 1, 0], [0, 1, 0], [0, 1, 0], [0, 0, 1], [0, 0, 1], [0, 0, 1], [0, 0, 1], [0, 0, 1]] right = votesim.votemethods.tools.rcv_reorder(right) ballots = e2.result.ballots ballots = votesim.votemethods.tools.rcv_reorder(ballots) assert np.all(right == ballots) return
def test1(self): """Test whether cnum limit is working""" v = spatial.Voters(0) v.add_random(20, 3) c = spatial.Candidates(v, 0) c.add_random(3).build() print(c.data.pref) e = spatial.Election(voters=v, candidates=c) e.user_data(a=0, b=1) print('running plurality') e.run(etype='plurality') print('running irv') e.run(etype='irv') e.run(etype='score') # test dataframe construction df = e.dataframe() assert 'args.user.a' in df.keys() assert 'args.user.b' in df.keys() return df
def model(x, methods): """Define election model here Parameters ---------- x : tuple Input arguments created from generator `case_args` Returns -------- out : Election Election object. """ #time.sleep(1) seed = x cnum = 2 vnum = 10 ndim = 1 strategy = 'candidate' trialnum = 2 e = spatial.Election(None, None, seed=seed, name=BENCHMARK_NAME) v = spatial.Voters(seed=seed, strategy=strategy) v.add_random(vnum, ndim=ndim) for trial in range(trialnum): c = spatial.Candidates(v, seed=trial) c.add_random(cnum, sdev=1.5) e.set_models(voters=v, candidates=c) e.user_data(seed=seed) for method in methods: e.run(etype=method) return e
def test(): v = spatial.Voters(0) v.add_random(20, 1) c = spatial.Candidates(v, 0) c.add([[0], [1], [2]]) e = spatial.Election(voters=v, candidates=c) e.run(etype='irv') e.run(etype='plurality') d2o = e.dataseries(0) d3o = e.dataseries(1) e2 = e.rerun(d2o) e3 = e.rerun(d3o) d2 = e2.dataseries() d3 = e3.dataseries() assert np.all(e.result.ballots == e3.result.ballots) assert d2.equals(d2o) assert d3.equals(d3o) for key, value in d2.items(): print(key) assert np.all(d2[key] == d2o[key])
def test_ranked_deep_bury(): """Test ranked burial tactic. Burial strategies -------------------------- * For #0 voters, their ballots are unchanged as their least favorite is already buried. * For #1 voters, they decide to bury #2. * For #2 voters, they decide to bury #1. Outcomes -------- Burial strategies backfires with #1 and #2 voters, allowing #0 to win. """ v = spatial.Voters(seed=0) v.add(voter_pref) c = spatial.Candidates(v) c.add(candidate_pref) # run honest election e1 = spatial.Election(voters=v, candidates=c) result1 = e1.run('ranked_pairs') # Make sure condorcet winner was found assert 1 in e1.result.winners #run strategic election strategy = { 'tactics': 'deep_bury', 'ratio': 1, 'underdog': None, 'subset': '', 'frontrunnertype': 'eliminate' } s2 = spatial.Strategies(v).add(**strategy) e2 = spatial.Election(voters=v, candidates=c, strategies=s2) e2.run('ranked_pairs', result=result1) # Make sure the correct front runners were tballots = e2.ballotgen.tacticalballots tgroup = list(tballots.root._tactical_groups.values())[0] front_runners = tgroup.front_runners assert 1 in front_runners assert 2 in front_runners # Check that #0 is the winner assert 0 in e2.result.winners ballots = e2.result.ballots ballots = votesim.votemethods.tools.rcv_reorder(ballots) # Check the new tactical rankings right = [[1, 2, 0], [1, 2, 0], [1, 2, 0], [1, 2, 0], [1, 2, 0], [1, 2, 0], [1, 2, 0], [3, 1, 0], [3, 1, 0], [3, 1, 0], [3, 0, 1], [3, 0, 1], [3, 0, 1], [3, 0, 1], [3, 0, 1]] right = votesim.votemethods.tools.rcv_reorder(right) assert np.all(right == ballots) return
def test_plurality_bullet_preferred(): """Test plurality bullet voting strategy. Scenario attributes: - 3 candidate race with 3 concentrated, coincident voter groups >>> Candidates #0 #1 #2 >>> Preference locations = [-1, 0.5, 1] >>> Number of voters = [ 7, 3, 5] - If voters are honest, plurality candidate #0 should win with 7 votes - If voters are strategic and consider only the top two candidates, Candidate #1 supporters also lean towards #2 - therefore candidate #2 should win with 3 + 5 = 8 votes. """ pref = [-1]*7 + [0.5]*3 + [1]*5 pref = np.array(pref)[:, None] v = spatial.Voters(seed=0) v.add(pref) cpref = [-1, .5, 1] cpref = np.array(cpref)[:, None] c = spatial.Candidates(v) c.add(cpref) ##################################################################### # Run honest election e1 = spatial.Election(voters=v, candidates=c) e1.run('plurality') tally1 = e1.result.runner.output['tally'] result1 = e1.result ##################################################################### # Run strategic election strategy1 = {'tactics' : 'bullet_preferred', 'ratio' : 1, 'subset' : 'underdog', 'underdog' : None,} s = spatial.Strategies(v) s.add(**strategy1) e1.set_models(strategies=s) e1.run('plurality', result=result1) tally2 = e1.result.runner.output['tally'] result2 = e1.result # Check honest vote tally assert np.all(tally1 == np.array([7, 3, 5])) # Check strategic vote tally assert np.all(tally2 == np.array([7, 0, 8])) # Check honest winner assert 0 in result1.winners # Check strategic winner assert 2 in result2.winners return
def test2(): """Check that seed correctly re-set""" v = spatial.Voters(seed=10) v.add_random(20, 1) c = spatial.Candidates(v, seed=5) c.add_random(2) e = spatial.Election(voters=v, candidates=c, seed=0) e.run(etype='plurality') s = e.dataseries() v = spatial.Voters(seed=1) v.add_random(5, 1) c = spatial.Candidates(v, seed=5) c.add_random(2) e = spatial.Election(voters=v, candidates=c, seed=0) er = e.rerun(s) assert er.voters[0].seed == 10 assert er.voters[0]._pref.__len__() == 20 return
def test1(self): v = spatial.Voters(0) voters = np.array([[-2,-1,0,1,2,]]).T v.add(voters) c = spatial.Candidates(v, 0) clocs = np.array([[-1, 0, 1]]).T c.add(clocs) e = spatial.Election(v, c) e.run('score') self.assertTrue(np.all(e.result.winners == 1))
def test1(): v = spatial.Voters(seed=0, ) v.add_random(50) seed = None c = spatial.Candidates( voters=v, seed=seed, ) c.add_random(12) e = spatial.Election(voters=v, candidates=c, seed=2) # e.run(method=ranked_pairs, btype='rank') e.run(etype='ranked_pairs')
def run_majority_metric(seed=0): v = spatial.Voters(seed=seed, tol=None) v.add_random(100) c = spatial.Candidates(v, seed=seed) c.add_random(3) c.add_random(2, sdev=2) e = spatial.Election(v, c, seed=seed) e.run('plurality') # Retrieve output ties = e.result.ties winners = e.result.winners ballots = e.result.ballots stats = ElectionStats(voters=v.data, candidates=c.data) # check plurality stat is correct stat_winner = stats.candidates.winner_plurality print('stat winner =', stat_winner) print('election winner=', winners) votecount = ballots.sum(axis=0) votecount2 = stats.candidates._winner_plurality_calcs[2] # Make sure counts for plurality are the same for election & metric assert np.all(votecount == votecount2) print(votecount) if len(ties) == 0: assert stat_winner in winners maxvotes = np.max(votecount) numvoters = len(ballots) # check majority winner stat if maxvotes > numvoters / 2: s = ('there should be majority winner, ' '%s out of %s' % (maxvotes, numvoters)) print(s) assert stats.candidates.winner_majority in winners
def model( methods, name, ndim, error_mean, error_width, clim_mean, clim_width, seed=1, cnum=8, trialnum=1000, numvoters=100, strategy='candidate', ): # seed = kwargs.get('seed', 1) # methods = kwargs['methods'] # name = kwargs['name'] # ndim = kwargs['ndim'] # error_mean = kwargs['error_mean'] # error_width = kwargs['error_width'] # cnum = kwargs['cnum'] e = spatial.Election(None, None, seed=seed, name=name) v = spatial.ErrorVoters(seed=seed, strategy=strategy) v.add_random( numvoters=numvoters, ndim=ndim, error_mean=error_mean, error_width=error_width, clim_mean=clim_mean, clim_width=clim_width, ) for trial in range(trialnum): c = spatial.Candidates(v, seed=trial) c.add_random(cnum, sdev=3) e.set_models(voters=v, candidates=c) e.user_data( strategy=strategy, num_dimensions=ndim, num_candidates=cnum, error_mean=error_mean, error_width=error_width, ) for method in methods: e.run(etype=method) return e
def test_spatial(self): numvoters = 99 num_candidates = 20 for ii in range(50): v = spatial.Voters(seed=ii,) v.add_random(numvoters=numvoters, ndim=2, ) c = spatial.Candidates(voters=v, seed=0) c.add_random(cnum=num_candidates, sdev=1.0) e = spatial.Election(voters=v, candidates=c) scores = e.ballotgen.get_honest_ballots( etype=votesim.votemethods.SCORE ) winners, ties, output = score.sequential_monroe(scores, numwin=6) return
def test_plurality_chain(): """Test re-using honest election data to initialize strategic runs.""" pref = [-1]*7 + [-0.5]*2 + [0.5]*3 + [1]*5 pref = np.array(pref)[:, None] v = spatial.Voters(seed=0) v.add(pref) # Generate candidate preferences cpref = [-1, -.5, .5, 1] cpref = np.array(cpref)[:, None] c = spatial.Candidates(v) c.add(cpref) # Run honest e1 = spatial.Election(voters=v, candidates=c) e1.run('plurality',) tally1 = e1.result.runner.output['tally'] result1 = e1.result assert np.all(tally1 == np.array([7, 2, 3, 5])) # Run tactical strategy = {'tactics' : 'bullet_preferred', 'ratio' : 1, 'underdog' : None, 'subset' : '' } s1 = spatial.Strategies(v).add(**strategy) e1.set_models(strategies=s1) e1.run('plurality', result=result1) tally2 = e1.result.runner.output['tally'] assert np.all(tally2 == np.array([9, 0, 0, 8])) # Run one sided strategy = {'tactics' : 'bullet_preferred', 'ratio' : 1, 'underdog' : None, 'subset' : 'underdog'} s1 = spatial.Strategies(v).add(**strategy) e1.set_models(strategies=s1) e1.run('plurality', result=result1) tally3 = e1.result.runner.output['tally'] assert np.all(tally3 == np.array([7, 2, 0, 8])) return locals()
def test_rerunner(self): v = spatial.Voters(0) v.add_random(20, 1) c = spatial.Candidates(v, 0) c.add([[0], [1], [2]]) e = spatial.Election(voters=v, candidates=c) e.run(etype='irv') e.run(etype='plurality') series = e.dataseries() e2 = e.rerun(series) series2 = e2.dataseries() for key in series2.keys(): print(key, series[key]) assert np.all(series[key] == series2[key])
def test_score_compare(self): """Sequential monroe ought to devolve to score at numwinners=1""" numvoters = 50 num_candidates = 6 for ii in range(50): v = spatial.Voters(seed=ii,) v.add_random(numvoters=numvoters, ndim=2, ) c = spatial.Candidates(voters=v, seed=0) c.add_random(cnum=num_candidates, sdev=1.0) e = spatial.Election(voters=v, candidates=c) scores = e.ballotgen.get_honest_ballots( etype=votesim.votemethods.SCORE ) winners1, ties1, output = score.sequential_monroe(scores, numwin=1) winners2, ties2, output = score.score(scores, numwin=1) assert np.all(winners1 == winners2) assert np.all(ties1 == ties2)
def test_run(): for seed in range(50): v = spatial.Voters(seed=seed) v.add_random(20) c = spatial.Candidates(v, seed=seed) c.add_random(6) e = spatial.Election( voters=v, candidates=c, seed=0, ) e.run('maj_judge') # scores = e.output[0]['round_history'] scores = e.result.runner.output['round_history'] print('ratings for each elimination round') print(scores) print('winner=%s' % e.result.winners) print('')
def test_plurality_ratio(): """Test adjusted the ratio of tactical to honest voters""" v = spatial.Voters(seed=0) v.add_random(100) c = spatial.Candidates(voters=v, seed=1) c.add_random(5) e1 = spatial.Election(voters=v, candidates=c) result1 = e1.run('plurality') tally1 = e1.result.runner.output['tally'] print('---------------------------------------') for tacti_num in [0, 10, 25, 50, 75, 100]: ratio = tacti_num / 100. strategy = {'tactics' : 'bullet_preferred', 'ratio' : ratio, 'underdog' : None, 'subset' : ''} s1 = spatial.Strategies(v).add(**strategy) e1.set_models(strategies=s1) e1.run('plurality', result=result1) tally2 = e1.result.runner.output['tally'] print('vote tally =', tally2) bgen = e1.ballotgen tactical_ballots = bgen.tacticalballots num_tactical_voters = len(tactical_ballots.group_index['tactical-0']) # check that tactical voters number is correct assert num_tactical_voters == tacti_num # check that total voters in group index is correct. group_index = tactical_ballots.group_index count1 = len(group_index['honest-0']) count2 = len(group_index['tactical-0']) assert count1 + count2 == 100 count3 = len(group_index['topdog-0']) count4 = len(group_index['underdog-0']) assert count3 + count4 == count2 return
def test_ranked_deep_bury_onesided(): """Test one sided burial strategy. For one-sided, only the under-dog voters vote tactically. * Honest Condorcet winner is Candidate #1. * Runner up is Candidate #2. * Therefore only #2 voters vote strategically in this scenario. Outcomes ------- It seems like burial backfires again in this scenario. """ v = spatial.Voters(seed=0) v.add(voter_pref) c = spatial.Candidates(v) c.add(candidate_pref) strategy = { 'tactics': 'deep_bury', 'subset': 'underdog', 'ratio': 1, 'underdog': None, 'frontrunnertype': 'eliminate' } s2 = spatial.Strategies(v).add(**strategy) e2 = spatial.Election(voters=v, candidates=c, strategies=s2) e2.run('ranked_pairs') right = [[1, 2, 3], [1, 2, 3], [1, 2, 3], [1, 2, 3], [1, 2, 3], [1, 2, 3], [1, 2, 3], [3, 1, 2], [3, 1, 2], [3, 1, 2], [3, 0, 1], [3, 0, 1], [3, 0, 1], [3, 0, 1], [3, 0, 1]] right = votesim.votemethods.tools.rcv_reorder(right) ballots = e2.result.ballots ballots = votesim.votemethods.tools.rcv_reorder(ballots) assert np.all(right == ballots) return
def model( methods, ndim, error_mean, error_width, clim_mean, clim_width, seed=1, cnum=8, trialnum=1000, numvoters=100, strategy='candidate', ): e = spatial.Election(None, None, seed=seed, name=BENCHMARK_NAME) v = spatial.ErrorVoters(seed=seed, strategy=strategy) v.add_random( numvoters=numvoters, ndim=ndim, error_mean=error_mean, error_width=error_width, clim_mean=clim_mean, clim_width=clim_width, ) for trial in range(trialnum): c = spatial.Candidates(v, seed=trial) c.add_random(cnum, sdev=3) e.set_models(voters=v, candidates=c) e.user_data( num_dimensions=ndim, num_candidates=cnum, error_mean=error_mean, error_width=error_width, ) for method in methods: e.run(etype=method) return e
def test(): seed = None for i in range(10): v = spatial.Voters(seed=seed) v.add_random(20, 3) c = spatial.Candidates(v, seed=seed) c.add_random(4) e = spatial.Election(v, c, scoremax=5) b = e.ballotgen.honest_ballot_dict # e.result. p1 = condcalcs.pairwise_scored_matrix(b['rate']) p2 = condcalcs.pairwise_rank_matrix(b['rank']) p3 = condcalcs.pairwise_scored_matrix(b['score']) w1, *args = condcalcs.condorcet_winners_check(matrix=p1) w2, *args = condcalcs.condorcet_winners_check(matrix=p2) w3, *args = condcalcs.condorcet_winners_check(matrix=p3) s1 = condcalcs.smith_set(vm=p1) s2 = condcalcs.smith_set(vm=p2) s3 = condcalcs.smith_set(vm=p3) print('') print(w1, w2, w3) print(s1, s2, s3) w, t, o = condorcet.smith_score(b['score']) print('winner', w) print(o) assert np.all(p1 == p2) if len(w1) > 0: assert w1 == w2
def model( name, methods, seed=0, numvoters=100, cnum=3, trialnum=1, ndim=1, strategy='candidate', stol=1, ): """Define election model here """ e = spatial.Election(None, None, seed=seed, name=name) v = spatial.Voters(seed=seed, strategy=strategy, stol=stol) v.add_random(numvoters, ndim=ndim) v.electionStats.set_categories([], fulloutput=True) cseed = seed * trialnum for trial in range(trialnum): c = spatial.Candidates(v, seed=trial + cseed) c.add_random(cnum, sdev=1.5) e.set_models(voters=v, candidates=c) # Save parameters e.user_data(num_voters=numvoters, num_candidates=cnum, num_dimensions=ndim, strategy=strategy, voter_tolerance=stol) for method in methods: e.run(etype=method) return e
import numpy as np import pandas as pd #votesim.logconfig.setInfo() #votesim.logconfig.setDebug() votesim.logconfig.setWarning() outputfile = 'election3way.pkl' types = [ 'irv', 'score', 'star', 'plurality', 'smith_minimax', 'approval50', 'approval75' ] metric_name = 'stats.regret.vsp' v = spatial.SimpleVoters(0) v.add_random(500, ndim=1) c = spatial.Candidates(v, 0) e = spatial.Election(v, None, seed=0, scoremax=5) ### Develop parametric study variables distances = np.linspace(0, 3, 20)[1:] skew = np.linspace(0, 1, 10)[1:-1] offset = np.linspace(0, 0.5, 10) ### Loop through parameters loop_product = itertools.product(distances, skew, offset) data = [] for ii, (d, s, o) in enumerate(loop_product): print(ii, end=',') c.reset() a = np.array([0, s, 1]) - 0.5 a = a * d + o
'approval50', 'approval75', 'ranked_pairs' ] filename = 'electionNd_data.pkl.zip' cnums = np.arange(2, 8) iters = itertools.product(strategies, ndims, cnums) e = spatial.Election(None, None, seed=seed) itercount = 0 for (strategy, ndim, cnum) in iters: v = spatial.SimpleVoters(seed=seed, strategy=strategy) v.add_random(numvoters, ndim=ndim) itercount += 1 print(itercount) for trial in range(trialnum): c = spatial.Candidates(v, seed=trial) c.add_random(cnum, sdev=1.5) c.add_random(cnum, sdev=3) e.set_models(voters=v, candidates=c) for method in methods: e.run(etype=method) print('building dataframe') df = e.dataframe() print('pickling') df.to_pickle(filename)
def tactical_model_v2( name: str, methods: list, seed=0, numvoters=51, cnum=5, cstd=1.5, ndim=1, tol=None, ratio=1.0, ) -> spatial.Election: """Tactical Election model that test every single candidate as an underdog, and tests topdog resistance using bullet voting. """ e = spatial.Election(None, None, seed=seed, name=name) # Construct base strategy strategy_base = {} strategy_base['ratio'] = ratio strategy_base['subset'] = 'underdog' # Create underdog strategy strategy2 = strategy_base.copy() # Create topdog strategy strategy3 = strategy_base.copy() strategy3['tactics'] = ['bullet_preferred'] strategy3['subset'] = 'topdog' # Generate voters v = spatial.Voters(seed=seed, tol=tol, base='linear') v.add_random(numvoters, ndim=ndim) # Generate candidates c = spatial.Candidates(v, seed=seed) c.add_random(cnum, sdev=cstd) e.set_models(voters=v, candidates=c) # Construct election identification eid = ( seed, numvoters, cnum, ndim, ) for method in methods: # Set empty (honest) strategy e.set_models(strategies=spatial.StrategiesEmpty()) e.user_data(eid=eid, strategy='honest') result1 = e.run(etype=method) winner = result1.winners[0] stats_honest = result1.stats underdog_list = list(range(cnum)) underdog_list.remove(winner) # test each underdog for underdog in underdog_list: strategy2['underdog'] = underdog strategy3['underdog'] = underdog # test each tactic tactics = get_tactics(method) for tactic in tactics: strategy2['tactics'] = tactic # Run one-sided strategy s = spatial.Strategies(v).add(**strategy2) e.set_models(strategies=s) e.user_data(eid=eid, strategy='one-sided') result2 = e.run(etype=method, result=result1) # Create tactical comparison output, add to output tactic_compare = TacticCompare(e_strat=result2.stats, e_honest=stats_honest) e.append_stat(tactic_compare) # Run two-sided strategy with top-dog bullet vote. s.add(**strategy3) e.set_models(strategies=s) e.user_data(eid=eid, strategy='two-sided') result3 = e.run(etype=method, result=result1) # Create tactical comparison output, add to output tactic_compare = TacticCompare(e_strat=result3.stats, e_honest=stats_honest) e.append_stat(tactic_compare) return e
def test_plurality_onesided(): """Test plurality one sided voting strategy. - #0 would win if #1 voters are strategic. - #3 will win if #1 are honest and #2 voters use one-sided strategy. >>> Candidates #0 #1 #2 #3 >>> Preference locations = [-1, -0.5, 0.5, 1] >>> Number of voters = [ 7, 2, 3, 5] """ # Generate voter preferences pref = [-1]*7 + [-0.5]*2 + [0.5]*3 + [1]*5 pref = np.array(pref)[:, None] v = spatial.Voters(seed=0) v.add(pref) # Generate candidate preferences cpref = [-1, -.5, .5, 1] cpref = np.array(cpref)[:, None] c = spatial.Candidates(v) c.add(cpref) ##################################################################### # Run honest election e1 = spatial.Election(voters=v, candidates=c) e1.run('plurality') tally1 = e1.result.runner.output['tally'] result1 = e1.result assert np.all(tally1 == np.array([7, 2, 3, 5])) assert 0 in e1.result.winners ##################################################################### # Run one-sided tactical election strategy1 = {'tactics' : 'bullet_preferred', 'ratio' : 1, 'subset' : 'underdog', 'underdog' : None,} strat1 = spatial.Strategies(v).add(**strategy1) e2 = spatial.Election(voters=v, candidates=c, strategies=strat1) result2 = e2.run('plurality', result=result1) tally2 = result2.runner.output['tally'] assert np.all(tally2 == np.array([7, 2, 0, 8])) assert 3 in result2.winners # Test metric comparison system. tc = TacticCompare(e_strat=result2.stats, e_honest=result1.stats, ) # e2.electionStats.add_output(tc) stats2 = result2.stats stats1 = result1.stats print('---------------------------------------') print('one-sided regret change =', tc.regret) print('') print('one-sided VSE change = ', tc.regret_efficiency_candidate) print('') print('VSE tactical = ', stats2.winner.regret_efficiency_candidate) print('VSE honest = ', stats1.winner.regret_efficiency_candidate) ##################################################################### # Run full tactical election strategy1 = {'tactics' : 'bullet_preferred', 'ratio' : 1, 'underdog' : None, 'subset' : ''} strat1 = spatial.Strategies(v).add(**strategy1) e3 = spatial.Election(voters=v, candidates=c, strategies=strat1) result3 = e3.run('plurality', result=result1) tally3 = result3.runner.output['tally'] assert np.all(tally3 == np.array([9, 0, 0, 8])) assert 0 in result3.winners # Test metric comparison system. tc = TacticCompare(e_strat=result3.stats, e_honest=result1.stats, ) print('') print('two-sided regret change =', tc.regret) print('two-sided VSE change = ', tc.regret_efficiency_candidate) docs = result3.output_docs # Try to append new output to election results e3.append_stat(tc) df = e3.dataframe() # pdb.set_trace() return df
import numpy as np import sys import votesim from votesim.votesystems import tools from votesim.models import vcalcs, spatial import matplotlib.pyplot as plt ### Create two simulations using 2 strategies voternum = 1000 candidates = [-0.3, 0.1, 0.4] candidates = np.atleast_2d(candidates).T v1 = spatial.SimpleVoters(seed=0, strategy='candidate') v1.add_random(voternum) c1 = spatial.Candidates(voters=v1, seed=0) c1.add(candidates) v1.calc_ratings(c1.candidates) v2 = spatial.SimpleVoters(seed=0, strategy='voter') v2.add_random(voternum) c2 = spatial.Candidates(voters=v2, seed=0) c1.add(candidates) v2.calc_ratings(c1.candidates) hist, bins = np.histogram(v1.voters, bins=20, density=True) bins = (bins[0:-1] + bins[1:]) / 2. for i in range(3): d1 = v1.voters
from votesim.strategy.stratrunner import StrategicRunner logging.basicConfig() logger = logging.getLogger('votesim.strategy') logger.setLevel(logging.WARNING) method = 'plurality' cnum = 5 vnum = 31 ndim = 2 name = 'strat-1' record = None for seed in range(10, 30): v = spatial.Voters(seed=seed) v.add_random(vnum, ndim=ndim) c = spatial.Candidates(v, seed=seed) c.add_random(cnum, sdev=1.5) srunner = StrategicRunner(name, method, voters=v, candidates=c, record=record) record = srunner.record print('\n') print('VSE honest', srunner.vse_honest) print('VSE 1-sided', srunner.vse_onesided) try: print('VSE change, underdog', np.max(srunner.dvse_underdogs)) except: pass