예제 #1
0
    def test_simple_pbv(self):

        stay = Candidate("Stay")
        soft = Candidate("Soft Brexit")
        hard = Candidate("Hard Brexit")

        candidates = [stay, soft, hard]

        ballots = [
            Ballot(ranked_candidates=[soft, stay]),
            Ballot(ranked_candidates=[stay, soft]),
            Ballot(ranked_candidates=[stay, soft]),
            Ballot(ranked_candidates=[hard, soft]),
            Ballot(ranked_candidates=[hard, stay, soft]),
        ]

        election_result = pyrankvote.preferential_block_voting(
            candidates, ballots, number_of_seats=1)
        winners = election_result.get_winners()

        self.assertEqual(1, len(winners),
                         "Function should return a list with one item")

        winner = winners[0]
        self.assertEqual(stay, winner, "Winner should be Soft")
    def test_equal_number_of_votes(self):
        trump = Candidate("Donald Trump")
        hillary = Candidate("Hillary Clinton")
        mary = Candidate("Uniting Mary")

        candidates = [trump, hillary, mary]

        ballots = [
            Ballot(ranked_candidates=[trump, mary, hillary]),
            Ballot(ranked_candidates=[trump, mary, hillary]),
            Ballot(ranked_candidates=[mary, trump, hillary]),
            Ballot(ranked_candidates=[hillary, trump, mary]),
            Ballot(ranked_candidates=[hillary, mary, trump])
        ]

        # You can use your own Candidate and Ballot objects as long as they implement the same properties and methods
        election_result = pyrankvote.instant_runoff_voting(candidates, ballots)
        ranking_first_round = election_result.rounds[0].candidate_results
        blank_votes = election_result.rounds[0].number_of_blank_votes

        self.assertEqual(3, len(ranking_first_round),
                         "Function should return a list with one item")
        self.assertListEqual([trump, hillary, mary], [
            candidate_result.candidate
            for candidate_result in ranking_first_round
        ], "Winners should be Per")
        self.assertEqual(
            0.0, blank_votes,
            "Should be zero blank votes as all ballots have ranked all candidates"
        )
def initialize_cand_objs(cand_list):
    """
    :goal: Initialize Candidate() objects from PyRankVote library
    :param cand_list:
    :return:
    """
    if isinstance(cand_list, str):
        return [Candidate(c) for c in cand_list.split(', ')]
    else:
        return [Candidate(c) for c in cand_list]
예제 #4
0
    def test_case2(self):

        per = Candidate("Per")
        paal = Candidate("Pål")
        maria = Candidate("Maria")
        ingrid = Candidate("Ingrid")

        candidates = [per, paal, maria, ingrid]

        # Quote = 3.33 with 10 votes and 2 seat
        ballots = [
            Ballot(ranked_candidates=[per, paal]),
            Ballot(ranked_candidates=[per, paal]),
            Ballot(ranked_candidates=[per, paal]),
            Ballot(ranked_candidates=[per, paal]),
            Ballot(ranked_candidates=[per, paal]),
            Ballot(ranked_candidates=[per, paal]),
            Ballot(ranked_candidates=[per, paal]),
            Ballot(ranked_candidates=[maria, ingrid]),
            Ballot(ranked_candidates=[ingrid, maria]),
            Ballot(ranked_candidates=[ingrid, maria]),
        ]

        # 1. round: Per: 7, Ingrid: 2, Maria: 1, Pål: 0
        #       --> Per is elected and 3.67 votes are transferred to Pål
        # Final round: Per: 3.33, Pål: 3.67, Ingrid: 2, Maria: 1
        #       --> Paal is elected. Since all seats filled, Ingrid and Maria are rejected.

        election_result = pyrankvote.single_transferable_vote(
            candidates, ballots, number_of_seats=2)
        winners = election_result.get_winners()

        self.assertEqual(2, len(winners),
                         "Function should return a list with two items")
        self.assertListEqual([per, paal], winners,
                             "Winners should be Per and Pål")

        round = 0
        votes_round = [
            candidate_vc.number_of_votes
            for candidate_vc in election_result.rounds[round].candidate_results
        ]
        assert_list_almost_equal(self, votes_round, [7, 2, 1, 0], 0.02)

        round = 1
        votes_round = [
            candidate_vc.number_of_votes
            for candidate_vc in election_result.rounds[round].candidate_results
        ]
        assert_list_almost_equal(self, votes_round, [3.33, 3.67, 2, 1], 0.02)
예제 #5
0
    def get_candidates_and_ballots(self):
        stay = Candidate("Stay")
        soft = Candidate("Soft Brexit")
        hard = Candidate("Hard Brexit")

        candidates = [stay, soft, hard]

        ballots = [
            Ballot(ranked_candidates=[stay, soft, hard]),
            Ballot(ranked_candidates=[hard, soft, stay]),
            Ballot(ranked_candidates=[soft, stay, hard]),
        ]

        return candidates, ballots
예제 #6
0
    async def resetname(self, context, student_id: int):
        if student_id not in helpers.preferred_names:
            await context.send(
                'The supplied student ID has not updated their name')
            return

        async with helpers.current_live_post_lock.reader_lock:
            if helpers.current_live_post:
                await context.send(
                    'I\'m afraid you can\'t reset a name whilst a vote is ongoing, '
                    f'please wait until the vote has finished, or end it early using `{helpers.PREFIX}end`'
                )
                return

            del helpers.preferred_names[student_id]

            union_name = helpers.get_members()[student_id]

            for post in helpers.standing:
                if student_id in helpers.standing[post]:
                    helpers.standing[post][student_id] = (
                        Candidate(union_name),
                        helpers.standing[post][student_id][1],
                        context.author.id)
        helpers.save_names()
        helpers.save_standing()

        helpers.log(f'The name used for {student_id} has been reset')
        await context.send(f'The name used for {student_id} has been reset')
예제 #7
0
    def test_candidates_have_most_second_votes(self):
        stay = Candidate("Stay")
        soft = Candidate("Soft Brexit")
        hard = Candidate("Hard Brexit")
        extra = Candidate("Extra")

        candidates = [stay, soft, hard, extra]

        ballots = [
            Ballot(ranked_candidates=[stay, soft, hard]),
            Ballot(ranked_candidates=[stay, soft, hard]),
            Ballot(ranked_candidates=[stay, soft]),
            Ballot(ranked_candidates=[extra, hard, stay]),
            Ballot(ranked_candidates=[soft, stay, hard]),
            Ballot(ranked_candidates=[soft, stay, hard]),
            Ballot(ranked_candidates=[soft, stay, hard]),
        ]
        manager = self.get_election_manager(candidates, ballots)

        stay_vc, soft_vc, hard_vc, extra_vc = [
            manager._candidate_vote_counts[stay],
            manager._candidate_vote_counts[soft],
            manager._candidate_vote_counts[hard],
            manager._candidate_vote_counts[extra]
        ]

        is_stay_ranked_first = manager._candidate1_has_most_second_choices(
            stay_vc, extra_vc, 1)
        self.assertEqual(is_stay_ranked_first, True,
                         "Stay should rank before extra")

        is_hard_ranked_first = manager._candidate1_has_most_second_choices(
            hard_vc, extra_vc, 1)
        self.assertEqual(
            is_hard_ranked_first, True,
            "Hard, should rank before extra, because hard has more 2nd alternative votes"
        )

        is_stay_ranked_first = manager._candidate1_has_most_second_choices(
            stay_vc, soft_vc, 1)
        self.assertEqual(
            is_stay_ranked_first, True,
            "Stay should rank before soft, even though they have equal number of votes, and equal number of "
            "second votes, because stay has more 3rd alternative votes.")
예제 #8
0
    def get_election_res(pred_df, id_orig, n_ans):
        df = pred_df[pred_df.id.str.startswith(id_orig)]
        candidates = [Candidate(el) for el in df.answers.unique()]
        ballots = [
            Ballot(ranked_candidates=[
                Candidate(vote) for vote in df[df.id == id_].answers
            ]) for id_ in df.id.unique()
        ]

        if len(candidates) <= n_ans:
            return list(df.answers)
        if args['voting'] == 'pbv':
            election_result = pyrankvote.preferential_block_voting(
                candidates, ballots, min(n_ans, len(candidates)))
        else:
            election_result = pyrankvote.single_transferable_vote(
                candidates, ballots, min(n_ans, len(candidates)))

        return election_result
예제 #9
0
def run_election(
        candidate_weights: List[Tuple[str, float]]) -> ElectionResults:
    candidates = [Candidate(p[0]) for p in candidate_weights]
    weights = np.array([p[1] for p in candidate_weights])
    adjusted_weights = weights / weights.sum()

    ballots = [
        generate_ballot(candidates, adjusted_weights) for v in range(VOTERS)
    ]
    results = instant_runoff_voting(candidates, ballots)
    return results
예제 #10
0
def calculateElectionResults(election):
    for i in election.questions:
        q = Question.query.filter_by(id=i).first()
        if q.voteType == "FPTP":
            winnerVote = {"first": {"description": "", "count": 0}}
            ties = list()
            for name, details in q.votes["answers"].items():
                if details["count"] > winnerVote[next(iter(winnerVote))]["count"]:
                    winnerVote = {name: details}
                    ties = []
                elif details["count"] == winnerVote[next(iter(winnerVote))]["count"]:
                    ties += [{name: details}]

            q.votes["results"] = [winnerVote] + ties
            audit = f"Answer {next(iter(winnerVote))} won by having highest number of votes, {winnerVote[next(iter(winnerVote))]['count']}."
            if len(ties) == 0:
                audit += " There were no ties."
            else:
                audit += f" There were ties as well: "
                for tie in ties:
                    audit += (
                        ", ".join([next(iter(tie)), str(tie[next(iter(tie))]["count"])])
                        + "; "
                    )
            q.votes["audit"] = audit

            flag_modified(q, "votes")

            db.session.add(q)
            db.session.flush()
        elif q.voteType == "STV":
            candidates = list(map(lambda x: Candidate(x["name"]), q.votes["answers"]))

            fullBallots = ballotify(q.votes["ballots"], candidates)

            results = pyrankvote.single_transferable_vote(
                candidates, fullBallots, number_of_seats=1
            )
            winner = results.get_winners()
            print(f"Winner for STV question: {winner}")
            print(f"Audit for STV question:\n{results}")

            winnerDetails = list(
                filter(lambda x: x["name"] == str(winner[0]), q.votes["answers"])
            )
            print(winnerDetails)

            q.votes["results"] = winnerDetails
            q.votes["audit"] = str(results)
            flag_modified(q, "votes")

            db.session.add(q)
            db.session.flush()
    db.session.commit()
예제 #11
0
    def test_simple_pbv_with_second_selection_if_equal(self):

        stay = Candidate("Stay")
        soft = Candidate("Soft Brexit")
        hard = Candidate("Hard Brexit")

        candidates = [stay, soft, hard]

        ballots = [
            Ballot(ranked_candidates=[stay, soft, hard]),
            Ballot(ranked_candidates=[hard, soft, stay]),
            Ballot(ranked_candidates=[soft, stay, hard]),
        ]

        election_result = pyrankvote.preferential_block_voting(
            candidates, ballots, number_of_seats=2)
        winners = election_result.get_winners()

        self.assertEqual(2, len(winners),
                         "Function should return a list with two items")
        self.assertIn(soft, winners, "Soft should be one of the winners")
        self.assertIn(stay, winners, "Stay should be one of the winners")
    def test_simple_case2(self):

        per = Candidate("Per")
        paal = Candidate("Pål")
        askeladden = Candidate("Askeladden")

        candidates = [per, paal, askeladden]

        ballots = [
            Ballot(ranked_candidates=[askeladden, per]),
            Ballot(ranked_candidates=[per, paal]),
            Ballot(ranked_candidates=[per, paal]),
            Ballot(ranked_candidates=[paal, per]),
            Ballot(ranked_candidates=[paal, per, askeladden]),
        ]

        election_result = pyrankvote.instant_runoff_voting(candidates, ballots)
        winners = election_result.get_winners()

        self.assertEqual(1, len(winners),
                         "Function should return a list with one item")
        self.assertListEqual([per], winners, "Winners should be Per")
예제 #13
0
    def test_case3(self):

        per = Candidate("Per")
        paal = Candidate("Pål")
        maria = Candidate("Maria")
        ingrid = Candidate("Ingrid")

        candidates = [per, paal, maria, ingrid]

        # Quote = 4.67 with 11 votes and 2 seat
        ballots = [
            Ballot(ranked_candidates=[per, paal]),
            Ballot(ranked_candidates=[per, paal]),
            Ballot(ranked_candidates=[per, paal]),
            Ballot(ranked_candidates=[per, paal]),
            Ballot(ranked_candidates=[per, paal]),
            Ballot(ranked_candidates=[per, paal]),
            Ballot(ranked_candidates=[per, paal]),
            Ballot(ranked_candidates=[per, paal]),
            Ballot(ranked_candidates=[maria, ingrid]),
            Ballot(ranked_candidates=[ingrid, maria]),
            Ballot(ranked_candidates=[ingrid, maria]),
        ]

        # 1. round: Per: 7, Ingrid: 2, Maria: 1, Pål: 0
        #       --> Per is elected and 3.33 votes are transfered to Pål
        # 2. round: Pål: 3.33, Ingrid: 2, Maria: 1
        #       --> Maria is excluded and her one vote is transfered to Ingrid
        # 3. round: Pål: 3.33, Ingrid: 3
        #       --> Pål is elected

        election_result = pyrankvote.single_transferable_vote(
            candidates, ballots, number_of_seats=2)
        winners = election_result.get_winners()

        self.assertEqual(2, len(winners),
                         "Function should return a list with two items")
        self.assertListEqual([per, paal], winners,
                             "Winners should be Per and Pål")
    def test_case3(self):
        trump = Candidate("Donald Trump")
        hillary = Candidate("Hillary Clinton")
        mary = Candidate("Uniting Mary")

        candidates = [trump, hillary, mary]

        ballots = [
            Ballot(ranked_candidates=[trump, mary, hillary]),
            Ballot(ranked_candidates=[trump, mary, hillary]),
            Ballot(ranked_candidates=[hillary, mary, trump]),
            Ballot(ranked_candidates=[hillary, mary, trump]),
            Ballot(ranked_candidates=[hillary, mary])
        ]

        # You can use your own Candidate and Ballot objects as long as they implement the same properties and methods
        election_result = pyrankvote.instant_runoff_voting(candidates, ballots)

        winners = election_result.get_winners()

        self.assertEqual(1, len(winners),
                         "Function should return a list with one item")
        self.assertListEqual([hillary], winners, "Winners should be Per")
예제 #15
0
    def test_simple_pbv2(self):

        per = Candidate("Per")
        paal = Candidate("Pål")
        askeladden = Candidate("Askeladden")

        candidates = [per, paal, askeladden]

        ballots = [
            Ballot(ranked_candidates=[askeladden, per]),
            Ballot(ranked_candidates=[per, paal]),
            Ballot(ranked_candidates=[per, paal]),
            Ballot(ranked_candidates=[paal, per]),
            Ballot(ranked_candidates=[paal, per, askeladden]),
        ]

        election_result = pyrankvote.preferential_block_voting(
            candidates, ballots, number_of_seats=1)
        winners = election_result.get_winners()

        self.assertEqual(1, len(winners),
                         "Function should return a list with one item")
        self.assertListEqual([per], winners, "Winners should be Per")
예제 #16
0
    def test_case1_simple(self):

        per = Candidate("Per")
        paal = Candidate("Pål")
        askeladden = Candidate("Askeladden")

        candidates = [per, paal, askeladden]

        ballots = [
            Ballot(ranked_candidates=[askeladden, per]),
            Ballot(ranked_candidates=[per, paal]),
            Ballot(ranked_candidates=[per, paal]),
            Ballot(ranked_candidates=[paal, per]),
            Ballot(ranked_candidates=[paal, per, askeladden]),
        ]

        election_result = pyrankvote.single_transferable_vote(
            candidates, ballots, number_of_seats=2)
        winners = election_result.get_winners()

        self.assertEqual(2, len(winners),
                         "Function should return a list with two items")
        self.assertListEqual([per, paal], winners,
                             "Winners should be Per and Pål")
예제 #17
0
    async def setup(self, context, *post):
        post = ' '.join(post)
        matching_posts = helpers.match_post(post)
        if matching_posts:
            await context.send(f'{post} already exists')
            return

        helpers.standing[post] = {
            0: (Candidate('RON (Re-Open Nominations)'), '*****@*****.**', 42)
        }

        helpers.save_standing()

        helpers.log(f'The post of {post} has been created')
        await context.send(f'The post of {post} has been created')
예제 #18
0
    def test_simple_pbv(self):

        per = Candidate("Per")
        paal = Candidate("Pål")
        askeladden = Candidate("Askeladden")

        candidates = [per, paal, askeladden]

        ballots = [
            Ballot(ranked_candidates=[askeladden, per]),
            Ballot(ranked_candidates=[per, paal]),
            Ballot(ranked_candidates=[per, paal]),
            Ballot(ranked_candidates=[paal, per]),
            Ballot(ranked_candidates=[paal, per, askeladden]),
        ]

        election_result = pyrankvote.preferential_block_voting(
            candidates, ballots, number_of_seats=2)
        winners = election_result.get_winners()

        self.assertEqual(2, len(winners),
                         "Function should return a list with two items")
        self.assertIn(per, winners, "Per should be one of the winners")
        self.assertIn(paal, winners, "Pål should be one of the winners")
예제 #19
0
def make_candidate_list(df):

    frame = inspect.currentframe().f_code.co_name

    # make a list of candidates
    utils.print_message(frame, "Making list of Candidates.")
    candidate_names = []  # just for assembling the ballots
    candidates = []  # to contain the Candidate objects

    # for each item in the dataframe:
    for item in df.iterrows():
        # get the candidate's surname and add it to both lists
        c = item[1][0].split(',')[0]
        candidate_names.append(c)
        candidates.append(Candidate(c))
    # show the list of Candidate objects
    if VERBOSE:
        print(candidates)

    return candidates, candidate_names
예제 #20
0
    async def changename(self, context, *name):

        name = ' '.join(name)
        if not name:
            await context.send(
                f'Must supply the name you are wanting to change to, usage: `{helpers.PREFIX}changename <NAME>`'
            )
            return
        if name.startswith('\''):
            name = name.strip('\'')

        author = context.author.id
        if author not in helpers.registered_members:
            await context.send(
                'It looks like you\'re not registered yet, you must first register using '
                f'`{helpers.PREFIX}register <STUDENT NUMBER>` before you can update your name'
            )
            return

        async with helpers.current_live_post_lock.reader_lock:
            if helpers.current_live_post:
                await context.send(
                    'I\'m afraid you can\'t change your name whilst a vote is ongoing, '
                    'please wait until the vote has finished')
                return

            author_id = helpers.registered_members[author]
            helpers.preferred_names[author_id] = name

            for post in helpers.standing:
                if author_id in helpers.standing[post]:
                    helpers.standing[post][author_id] = (
                        Candidate(name), helpers.standing[post][author_id][1],
                        author)
        helpers.save_names()
        helpers.save_standing()

        await context.send(f'The bot now recognises your name to be {name}')
        helpers.log(
            f'{context.author.name}({author_id}) has changed their name to {name}'
        )
예제 #21
0
def make_ballots(df, candidate_names, voters_list, top_N):

    frame = inspect.currentframe().f_code.co_name

    # make an empty list of ballots
    ballots = []

    # # make a list of voters (should match the input spreadsheet)
    # voters_list = ['voter1', 'voter2', 'voter3']

    utils.print_message(frame, "Making ballots.")
    for voter in voters_list:
        # get the list of rankings for the current voter
        ranks = df[voter].to_list()
        # candidates not rated end up with an empty entry in the list = ''
        # we can't use that for comparison, so let's set unrated candidates to a
        # low preference - say 99, then use map to convert everything
        # to a list of ints
        ranks = list(map(int, [99 if r == '' else r for r in ranks]))

        # create an empty ballot and fill it with candidate names for this voter
        # b = []
        b = [name for _, name in sorted(zip(ranks, candidate_names))]

        # we allow only the top N candidates
        b = b[:top_N]

        if VERBOSE:
            utils.print_message(
                frame,
                "{1}'s top-{2} ballot from most to least preferred = {0}".
                format(b, voter, top_N))

        # add this ballot to the list of ballots
        ballots.append(Ballot(ranked_candidates=[Candidate(x) for x in b]))

    # show the ballots
    if VERBOSE:
        print("list of all ballots: {0}".format(ballots))

    return ballots
예제 #22
0
def parse_ballots_csv_file(file_name):
    file_path = os.path.join(TEST_DATA_PATH, file_name)
    with open(file_path) as f:
        csv_file_without_header = list(csv.reader(f))[1:]
        parsed_csv_file = [
            (ballot_id, rank, candidate_name)
            for ballot_id, rank, candidate_name in csv_file_without_header
        ]
        #sorted_csv_file = sorted(parsed_csv_file, key=itemgetter(0,1))
        sorted_csv_file = parsed_csv_file

        candidates = {}
        ballots = []
        last_ballot_id = 0
        ranked_candidates = []

        for ballot_id, rank, candidate_name in sorted_csv_file:
            if ballot_id != last_ballot_id and last_ballot_id != 0:
                ballot = Ballot(ranked_candidates)
                ballots.append(ballot)
                ranked_candidates = []

            last_ballot_id = ballot_id
            if candidate_name == "$UNDERVOTE":
                continue
            if candidate_name == "$OVERVOTE":
                continue
            if candidate_name in candidates:
                candidate = candidates[candidate_name]

            else:
                candidate = Candidate(name=candidate_name)
                candidates[candidate_name] = candidate
            ranked_candidates.append(candidate)

        ballot = Ballot(ranked_candidates)
        ballots.append(ballot)

        return list(candidates.values()), ballots
    def test_simple_case(self):
        per = Candidate("Per")
        paal = Candidate("Pål")
        askeladden = Candidate("Askeladden")

        candidates = [per, paal, askeladden]

        ballots = [
            Ballot(ranked_candidates=[askeladden, per]),
            Ballot(ranked_candidates=[per, paal]),
            Ballot(ranked_candidates=[per, paal]),
            Ballot(ranked_candidates=[paal, per]),
            Ballot(ranked_candidates=[paal, per, askeladden])
        ]

        election_result = pyrankvote.instant_runoff_voting(candidates, ballots)
        winners = election_result.get_winners()

        stay = Candidate("Stay")
        soft = Candidate("Soft Brexit")
        hard = Candidate("Hard Brexit")

        candidates = [stay, soft, hard]

        ballots = [
            Ballot(ranked_candidates=[soft, stay]),
            Ballot(ranked_candidates=[stay, soft]),
            Ballot(ranked_candidates=[stay, soft]),
            Ballot(ranked_candidates=[hard, soft]),
            Ballot(ranked_candidates=[hard, stay, soft]),
        ]

        election_result = pyrankvote.instant_runoff_voting(candidates, ballots)
        winners = election_result.get_winners()

        self.assertEqual(1, len(winners),
                         "Function should return a list with one item")

        winner = winners[0]
        self.assertEqual(stay, winner, "Winner should be Soft")
예제 #24
0
    with open(os.path.join(script_folder, path)) as f:
        reader = csv.reader(f)
        first_row = True
        for row in reader:
            if first_row:
                first_row = False
                continue
            # Skip timestamp and user.
            ballots.append(row[2:])

    # Create Candidate objects for every proposal.
    proposals = {}
    for ballot in ballots:
        for proposal in ballot:
            if proposal not in proposals:
                proposals[proposal] = Candidate(proposal)

    # Create Ballot objects for every ballot.
    processed_ballots = []
    for ballot in ballots:
        ranked = []
        for proposal in ballot:
            ranked.append(proposals[proposal])
            processed_ballots.append(Ballot(ranked_candidates=ranked))

    # Print election results.
    election_result = pyrankvote.single_transferable_vote(
        proposals.values(),
        processed_ballots,
        number_of_seats=NUMBER_OF_WINNERS)
    print(election_result)
예제 #25
0
scope = [
    "https://spreadsheets.google.com/feeds",
    'https://www.googleapis.com/auth/spreadsheets',
    "https://www.googleapis.com/auth/drive.file",
    "https://www.googleapis.com/auth/drive"
]

creds = ServiceAccountCredentials.from_json_keyfile_name("creds.json", scope)

client = gspread.authorize(creds)

sh = client.open("SheetName")
sheet = sh.get_worksheet(0)  #sheetnumber

A = Candidate("CandA")  #1stcandidate
B = Candidate("CandB")  #2ndcandidate
C = Candidate("CandC")  #3rdcandidate
D = Candidate("CandD")  #4thcandidate

dictCandidate = {"A": A, "B": B, "C": C, "D": D}  #dictionary to map it

candidates = [A, B, C, D]


def replace():  #replaces all the names in the sheet with letters
    cellsA = sheet.findall(
        "CandA")  #you need to change their names here as well as above
    i = 0
    while i < len(cellsA):
        cellsA[i].value = 'A'
예제 #26
0
import pyrankvote
from pyrankvote import Candidate, Ballot

# ONE SEAT ELECTION: INSTANT RUNOFF VOTING

bush = Candidate("George W. Bush (Republican)")
gore = Candidate("Al Gore (Democratic)")
nader = Candidate("Ralph Nader (Green)")

candidates = [bush, gore, nader]

# Bush have most first choice votes, but because Ralph Nader-voters want
# Al Gore if Nader is not elected, the elected candidate is Al Gore
ballots = [
    Ballot(ranked_candidates=[bush, nader, gore]),
    Ballot(ranked_candidates=[bush, nader, gore]),
    Ballot(ranked_candidates=[bush, nader]),
    Ballot(ranked_candidates=[bush, nader]),
    Ballot(ranked_candidates=[nader, gore, bush]),
    Ballot(ranked_candidates=[nader, gore]),
    Ballot(ranked_candidates=[gore, nader, bush]),
    Ballot(ranked_candidates=[gore, nader]),
    Ballot(ranked_candidates=[gore, nader])
]

# You can use your own Candidate and Ballot objects as long as they implement the same properties and methods
election_result = pyrankvote.instant_runoff_voting(candidates, ballots)

winners = election_result.get_winners()
# Returns: [<Candidate('Al Gore (Democratic)')>]
예제 #27
0
    help='Path to a CSV file of all the votes (formatted like votes.csv)')
parser.add_argument('n_seats',
                    metavar='<# seats>',
                    type=int,
                    help='Number of open seats to win')
parser.add_argument(
    '--output',
    default=datetime.now().strftime('%Y%m%d_%H%M%S.out'),
    type=str,
    help='Name of file to write output. Default is current date and time.')
args = parser.parse_args()

# Read the votes CSV file, and create a list of candidates based on candidate-names in the CSV header
votes_df = pd.read_csv(args.votes_csv)
candidates = votes_df.columns[1:]
candidates = np.array([Candidate(c[c.rfind('[') + 1:-1]) for c in candidates
                       ])  # Google forms puts candidate names in [brackets]
ballots = []

# Read the CSV row-by-row and create Ballot objects for pyrankvote
for i, row in votes_df.iterrows():
    # print('Processing vote %d' % i)

    # Extract the ranking votes from our dataframe row. First column is timestamp.
    ranked_vote = row.values[
        1:]  # List of rankings, index j refers to candidate j
    NaNs = (
        ranked_vote != ranked_vote
    )  # True where there are NaNs (candidates that didn't get a ranking)
    ranked_vote[NaNs] = len(
        candidates
예제 #28
0
# Format = [<Ballot>]
votes = []

# Format = [<Student Number>]
voted = []

# Format = {<Discord Username>: <Student Number>}
registered_members = {}

# Format = {<Post>: {<Student Number>: (<Candidate Object>, <Email>), ...}, ...}
standing = {}

# Format = {<Title>: <Description>, ...}
referenda = {}
referendum_options = [Candidate('For'), Candidate('Against')]

# Format = {<Student Number>: <Preferred Name>, ...}
preferred_names = {}

# Format = {<User ID>: [(<Candidate Student ID>, <Message ID>), ...], ...}
voting_messages = {}

current_live_post_lock = aiorwlock.RWLock()
votes_lock = aiorwlock.RWLock()
voted_lock = asyncio.Lock()

def get_members():
    members = society_members.get_members()
    members[0] = 'RON (Re-Open-Nominations)'
예제 #29
0
    def test_example(self):
        popular_moderate = Candidate("William, popular moderate")
        moderate2 = Candidate("John, moderate")
        moderate3 = Candidate("Charles, moderate")
        far_left = Candidate("Thomas, far-left")

        candidates = [popular_moderate, moderate2, moderate3, far_left]

        ballots = [
            Ballot(ranked_candidates=[
                popular_moderate, moderate2, moderate3, far_left
            ]),
            Ballot(ranked_candidates=[
                popular_moderate, moderate2, moderate3, far_left
            ]),
            Ballot(ranked_candidates=[
                popular_moderate, moderate3, moderate2, far_left
            ]),
            Ballot(ranked_candidates=[
                popular_moderate, moderate3, moderate2, far_left
            ]),
            Ballot(ranked_candidates=[
                moderate2, popular_moderate, moderate3, far_left
            ]),
            Ballot(ranked_candidates=[
                moderate2, popular_moderate, moderate3, far_left
            ]),
            Ballot(ranked_candidates=[
                far_left, popular_moderate, moderate2, moderate3
            ]),
            Ballot(ranked_candidates=[
                far_left, popular_moderate, moderate2, moderate3
            ]),
            Ballot(ranked_candidates=[
                far_left, moderate2, popular_moderate, moderate3
            ]),
            Ballot(ranked_candidates=[
                far_left, moderate2, popular_moderate, moderate3
            ]),
        ]

        election_result = pyrankvote.preferential_block_voting(
            candidates, ballots, number_of_seats=2)

        round_nr = 0
        candidates_results_in_round = election_result.rounds[
            round_nr].candidate_results

        ranking_in_round = [
            candidate_result.candidate
            for candidate_result in candidates_results_in_round
        ]
        correct_ranking_in_round = [
            popular_moderate, moderate2, far_left, moderate3
        ]
        self.assertEqual(4, len(ranking_in_round),
                         "All four candidates should be in the result list")
        self.assertListEqual(correct_ranking_in_round, ranking_in_round)

        votes_in_round = [
            candidate_result.number_of_votes
            for candidate_result in candidates_results_in_round
        ]
        correct_votes_in_round = [8, 6, 4, 2]
        assert_list_almost_equal(self, correct_votes_in_round, votes_in_round)

        status_in_round = [
            candidate_result.status
            for candidate_result in candidates_results_in_round
        ]
        correct_status_in_round = [
            CandidateStatus.Elected, CandidateStatus.Elected,
            CandidateStatus.Rejected, CandidateStatus.Rejected
        ]
        self.assertListEqual(correct_status_in_round, status_in_round)

        winners = election_result.get_winners()
        self.assertEqual(2, len(winners),
                         "Function should return a list with two items")

        self.assertIn(popular_moderate, winners, "William should be a winner")
        self.assertIn(moderate2, winners, "John should be a winner")
예제 #30
0
    def test_example(self):
        popular_moderate = Candidate("William, popular moderate")
        moderate2 = Candidate("John, moderate")
        moderate3 = Candidate("Charles, moderate")
        far_left = Candidate("Thomas, far-left")

        candidates = [popular_moderate, moderate2, moderate3, far_left]

        ballots = [
            Ballot(ranked_candidates=[
                popular_moderate, moderate2, moderate3, far_left
            ]),
            Ballot(ranked_candidates=[
                popular_moderate, moderate2, moderate3, far_left
            ]),
            Ballot(ranked_candidates=[
                popular_moderate, moderate3, moderate2, far_left
            ]),
            Ballot(ranked_candidates=[
                popular_moderate, moderate3, moderate2, far_left
            ]),
            Ballot(ranked_candidates=[
                moderate2, popular_moderate, moderate3, far_left
            ]),
            Ballot(ranked_candidates=[
                moderate2, popular_moderate, moderate3, far_left
            ]),
            Ballot(ranked_candidates=[
                far_left, popular_moderate, moderate2, moderate3
            ]),
            Ballot(ranked_candidates=[
                far_left, popular_moderate, moderate2, moderate3
            ]),
            Ballot(ranked_candidates=[
                far_left, moderate2, popular_moderate, moderate3
            ]),
            Ballot(ranked_candidates=[
                far_left, moderate2, popular_moderate, moderate3
            ]),
        ]

        election_result = pyrankvote.single_transferable_vote(
            candidates, ballots, number_of_seats=2)

        round_nr = 0
        candidates_results_in_round = election_result.rounds[
            round_nr].candidate_results
        ranking_in_round = [
            candidate_result.candidate
            for candidate_result in candidates_results_in_round
        ]
        votes_in_round = [
            candidate_result.number_of_votes
            for candidate_result in candidates_results_in_round
        ]
        self.assertEqual(4, len(ranking_in_round),
                         "All four candidates should be list.")
        self.assertListEqual(
            [popular_moderate, far_left, moderate2, moderate3],
            ranking_in_round)
        assert_list_almost_equal(self, [4, 4, 2, 0], votes_in_round)

        self.assertEqual(1, len(election_result.rounds),
                         "Should be only one round")

        winners = election_result.get_winners()
        self.assertEqual(2, len(winners), "Should be two winners")

        self.assertIn(popular_moderate, winners, "William should be a winner")
        self.assertIn(far_left, winners, "John should be a winner")