コード例 #1
0
    async def end(self, context):
        voting_channel = await self.bot.fetch_channel(helpers.VOTING_CHANNEL_ID
                                                      )
        committee_channel = await self.bot.fetch_channel(
            helpers.COMMITTEE_CHANNEL_ID)

        last_live_post = helpers.current_live_post
        async with helpers.current_live_post_lock.writer_lock:
            helpers.current_live_post = None
        helpers.voting_messages.clear()
        async with helpers.voted_lock:
            helpers.voted.clear()

        await voting_channel.send(
            f'Voting has now ended for: {last_live_post[1]}')

        async with helpers.votes_lock.writer_lock:
            if last_live_post[0] == 'POST':
                results = pyrankvote.instant_runoff_voting([
                    i for i, _, _ in helpers.standing[
                        last_live_post[1]].values()
                ], helpers.votes)
            else:
                results = pyrankvote.instant_runoff_voting(
                    helpers.referendum_options, helpers.votes)

            helpers.votes.clear()

        # Announce the scores and the winner to the committee
        winner = results.get_winners()[0]

        helpers.log(f'Result: {results}')
        helpers.log(f'Winner: {winner}')

        if last_live_post[0] == 'POST':
            await committee_channel.send(
                'The votes were tallied as follows:\n'
                f'```{results}```\n'
                f'The winning candidate for the post of {last_live_post[1]} is: {winner}'
            )
        else:
            await committee_channel.send(
                'The votes were tallied as follows:\n'
                f'```{results}```\n'
                f'The result for the referendum on {last_live_post[1]} is: {winner}'
            )

        helpers.log(f'Voting has now ended for: {last_live_post[1]}')
        for voter in helpers.registered_members:
            user = await self.bot.fetch_user(voter)
            await user.send(f'Voting has now ended for: {last_live_post[1]}')
コード例 #2
0
    def test_us_me_2018_06_cd02_primary(self):
        """
        Test Maine 2018 Congress District 2 Democrat Primary Election
        Source: https://ranked.vote/us/me/2018/06/cd02-primary/
        Data source: https://s3.amazonaws.com/ranked.vote-reports/us/me/2018/06/cd02-primary/us_me_2018_06_cd02-primary.normalized.csv.gz
        """

        file_name = "us_me_2018_06_cd02-primary.normalized.csv"
        candidates, ballots = parse_ballots_csv_file(file_name)

        election_result = pyrankvote.instant_runoff_voting(
            candidates, ballots, pick_random_if_blank=False)
        last_round = election_result.rounds[-1]

        blank_votes = last_round.number_of_blank_votes
        correct_blank_votes = 7381
        self.assertEqual(correct_blank_votes, blank_votes)

        number_of_votes = [
            candidate_result.number_of_votes
            for candidate_result in last_round.candidate_results
        ]
        correct_number_of_votes = [23611, 19853, 0, 0]
        assert_list_almost_equal(self, correct_number_of_votes,
                                 number_of_votes)
コード例 #3
0
    def test_us_me_2018_11_cd02(self):
        """
        Maine 2018 Congress District 2 General Election
        Source: https://ranked.vote/us/me/2018/11/cd02/
        Data source: https://s3.amazonaws.com/ranked.vote-reports/us/me/2018/11/cd02/us_me_2018_11_cd02.normalized.csv.gz
        """

        file_name = "us_me_2018_11_cd02.normalized.csv"
        candidates, ballots = parse_ballots_csv_file(file_name)

        election_result = pyrankvote.instant_runoff_voting(
            candidates, ballots, pick_random_if_blank=False)
        last_round = election_result.rounds[-1]

        blank_votes = last_round.number_of_blank_votes
        correct_blank_votes = 14706
        self.assertEqual(correct_blank_votes, blank_votes)

        number_of_votes = [
            candidate_result.number_of_votes
            for candidate_result in last_round.candidate_results
        ]
        correct_number_of_votes = [142440, 138931, 0, 0]
        assert_list_almost_equal(self, correct_number_of_votes,
                                 number_of_votes)
コード例 #4
0
    def test_us_vt_btv_2009_03_mayor(self):
        """
        Burlington 2009 Mayoral Election
        Source: https://ranked.vote/us/vt/btv/2009/03/mayor/
        Data source: https://s3.amazonaws.com/ranked.vote-reports/us/vt/btv/2009/03/mayor/us_vt_btv_2009_03_mayor.normalized.csv.gz
        """

        file_name = "us_vt_btv_2009_03_mayor.normalized.csv"
        candidates, ballots = parse_ballots_csv_file(file_name)

        election_result = pyrankvote.instant_runoff_voting(
            candidates, ballots, pick_random_if_blank=False)
        last_round = election_result.rounds[-1]

        blank_votes = last_round.number_of_blank_votes
        correct_blank_votes = 607
        self.assertEqual(correct_blank_votes, blank_votes)

        number_of_votes = [
            candidate_result.number_of_votes
            for candidate_result in last_round.candidate_results
        ]
        correct_number_of_votes = [4313, 4060, 0, 0, 0, 0]
        assert_list_almost_equal(self, correct_number_of_votes,
                                 number_of_votes)
コード例 #5
0
async def close_vote(ctx, *args):
    if len(args) != 1:
        await ctx.send('Usage: -vote close {name}')
        return

    name = args[0]
    try:
        vote = data.open_votes[(ctx.guild, name)]
    except KeyError:
        await ctx.send(f'No vote named {name}')
        return

    if not vote.has_started:
        await ctx.send(f'{name} has not opened yet.')
        return

    if vote.has_ended:
        await ctx.send(f'{name} has already been closed.')
        return

    vote.has_ended = True
    del data.open_votes[(ctx.guild, name)]

    await ctx.send(
        f'Voting for {name} has been closed. Results will be posted when available.'
    )

    result = pyrankvote.instant_runoff_voting(vote.choices, vote.ballots)
    await ctx.send(str(result))
コード例 #6
0
    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 run_election(list_of_cand_objs, election_df):
    """
    :goal: simulate Instant Runoff Voting election via PyRankVote
    :param list_of_cand_objs:
    :param election_df:
    :return:
    """
    return pyrankvote.instant_runoff_voting(list_of_cand_objs,
                                            election_df['ballots'],
                                            pick_random_if_blank=True)
コード例 #8
0
ファイル: election.py プロジェクト: tngzng/ranked-choice
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
コード例 #9
0
    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")
コード例 #10
0
    def __init__(self, movie_night, candidates, vetoes=[]):
        from standrew.models import MovieRankedVote

        self.result = pyrankvote.instant_runoff_voting(
            candidates,
            [
                movie_ballot.get_ballot(vetoes)
                for movie_ballot in movie_night.movieballot_set.prefetch_related(
                    Prefetch(
                        "movierankedvote_set", queryset=MovieRankedVote.objects.select_related("candidate__imdb_id")
                    )
                )
                .select_related("voter")
                .all()
            ],
        )
コード例 #11
0
    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")
コード例 #12
0
    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")
コード例 #13
0
def getCandidates(candidatelist):
    returndict = []
    for candidate in candidatelist:
        returndict.append(dictCandidate[candidate])
    return returndict


ballots = []


def addvote(num):
    ballots.append(
        Ballot(ranked_candidates=getCandidates(sheet.row_values(num))))


j = 2
while j <= numRows + 1:  #loops through all the rows and adds it to be tabulated
    time.sleep(0.75)
    addvote(j)
    j = j + 1

electIRV = pyrankvote.instant_runoff_voting(candidates, ballots)
winIRV = electIRV.get_winners()
print(electIRV)
#IRV used for one seat
#STV used for multiple, change the 2  below to the amount of seats
#comment/uncomment whichever one you need to use
#electSTV = pyrankvote.single_transferable_vote(candidates,ballots, 2)
#winSTV = electSTV.get_winners()
#print(electSTV)
コード例 #14
0
# 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)')>]

print(election_result)
# Prints:
"""
ROUND 1
Candidate                      Votes  Status
---------------------------  -------  --------
George W. Bush (Republican)        4  Hopeful
Al Gore (Democratic)               3  Hopeful
Ralph Nader (Green)                2  Rejected

FINAL RESULT