forked from joanbp-dk/Repbased_voting_playground
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathVote.py
More file actions
66 lines (55 loc) · 2.61 KB
/
Vote.py
File metadata and controls
66 lines (55 loc) · 2.61 KB
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
import Testdata
import sys, os
# sys.path.append(os.path.abspath("../pyvoting"))
# import pyvoting as pv
import pandas as pd
from Definitions import Voter, FellowshipCandidate
from typing import Callable
CANDIDATES = Testdata.CANDIDATES
# A quick and dirty voting algorithm.
# Counts all votes and returns the id of the candidate who got the most votes.
# In case of a tie, the winning candidate with the lowest id will be returned.
# This algorithm completely ignores the proven qualifications of both candidates and voters.
def popularity_contest(voters: list[Voter], candidates: list[FellowshipCandidate] = CANDIDATES.values()):
votecount = {}
for candidate in candidates:
votecount[candidate.id] = len([voter for voter in voters if voter.get_single_vote() == candidate])
return sort(votecount)
# return max(votecount, key=votecount.get)
def sort(results):
return dict(sorted(results.items(), key=lambda x: x[1], reverse=True))
def accumulated_scores_voting(voters: list[Voter], candidates: list[FellowshipCandidate] = CANDIDATES.values(), weighing_mechanism: Callable[[Voter], int] = None):
# Note: We ignore candidates for now and just take whatever candidate is provided by voters as a valid candidate.
candidate_scores = {}
for voter in voters:
for candidate, distribution in voter.get_distributed():
id = candidate.id
if id not in candidate_scores:
candidate_scores[id] = 0
if weighing_mechanism is None:
candidate_scores[id] += distribution
else:
candidate_scores[id] += weighing_mechanism(voter, id)
return sort(candidate_scores)
# Unfortunately, the pyvoting package doesn't work as a package because of some broken imports.
# So I'll have to uncomment these methods for a bit until that is fixed.
# def ranked_choice(votes, candidates = Testdata.candidate_names):
# election = pv.RankedChoiceVoting(candidates)
# for voter in votes:
# election.AddBallot(get_as_ballot(voter))
# results = election.RunElection()
# print(results)
# return results
# def tier_list_voting(votes, candidates = Testdata.candidate_names):
# election = pv.TierListVoting(candidates)
# for voter in votes:
# election.AddBallot(get_as_ballot(voter))
# results = election.RunElection()
# print(results)
# return results
def get_as_ballot(voter) -> pd.Series:
ballot = {}
if hasattr(voter, 'weighted_vote'):
for candidate, weight in voter.weighted_vote.candidate_weights.items():
ballot[candidate.id] = weight
return pd.Series(ballot)