Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Cumulative voting #106

Closed
wants to merge 10 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
200 changes: 200 additions & 0 deletions notebooks/cumulative_voting.ipynb
Original file line number Diff line number Diff line change
@@ -0,0 +1,200 @@
{
"cells": [
{
"cell_type": "markdown",
"metadata": {},
"source": [
"# `PointBallot`\n",
"While some elections rely on candidate rankings, others rely on candidate scorings, such as Borda, Cumulative, or approval voting. The `PointBallot` class stores such scoring information as a dictionary, where each key is a candidate and each value is the number of points given to that candidate by the voter.\n",
"\n",
"The `points` attribute can be either a list with multiplicity, or a dictionary."
]
},
{
"cell_type": "code",
"execution_count": 1,
"metadata": {},
"outputs": [],
"source": [
"import votekit.ballot_generator as bg\n",
"from votekit.ballot import PointBallot\n",
"\n",
"from votekit.elections import HighestScore\n",
"from votekit.pref_profile import PreferenceProfile\n",
"from fractions import Fraction"
]
},
{
"cell_type": "code",
"execution_count": 2,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"{'A': 2, 'B': 1} with weight 1\n",
"{'A': 2, 'B': 1} with weight 3\n"
]
}
],
"source": [
"print(PointBallot(points=[\"A\", \"B\", \"A\"]))\n",
"print(PointBallot(points={\"A\":2, \"B\":1}, weight = Fraction(3,1)))"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"# Cumulative Voting\n",
"\n",
"In a cumulative election, voters have $m$ votes to fill $m$ seats. They are allowed to cast these votes on any candidate, including multiple votes for one candidate. Then, the candidates with the $m$ highest vote totals win. We still model this using a preference interval, except now we just sample with replacement (instead of without replacement as in the PL model)."
]
},
{
"cell_type": "code",
"execution_count": 3,
"metadata": {},
"outputs": [],
"source": [
"candidates = [\"A\", \"B\", \"C\"]\n",
"pref_interval_by_bloc = {\"R\": {\"A\": .3, \"B\":.6, \"C\":.1}}\n",
"bloc_voter_prop = {\"R\":1}\n",
"num_seats = 2\n",
"\n",
"cumulative = bg.Cumulative( num_votes=num_seats, candidates = candidates, pref_interval_by_bloc = pref_interval_by_bloc,\n",
" bloc_voter_prop=bloc_voter_prop)\n",
"\n"
]
},
{
"cell_type": "code",
"execution_count": 4,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
" Ballots Weight\n",
" (B: 2,) 4\n",
"(A: 1, B: 1) 3\n",
" (A: 2,) 2\n",
"(B: 1, C: 1) 1\n"
]
}
],
"source": [
"cumulative_profile = cumulative.generate_profile(number_of_ballots=10)\n",
"cumulative_election = HighestScore(profile = cumulative_profile,\n",
" seats = num_seats)\n",
"\n",
"print(cumulative_profile)"
]
},
{
"cell_type": "code",
"execution_count": 5,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"Candidate Status Round\n",
" B Elected 1\n",
" A Elected 1\n",
" C Eliminated 1"
]
},
"execution_count": 5,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"cumulative_election.run_election()"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Double check the computation above!\n",
"\n",
"\n",
"Now what happens in the case of ties? As currently coded, `votekit` takes all the tied candidates and randomly permutes them."
]
},
{
"cell_type": "code",
"execution_count": 6,
"metadata": {},
"outputs": [],
"source": [
"tied_cumulative_profile = PreferenceProfile(ballots = [PointBallot(points=[\"A\", \"B\", \"C\"])],\n",
" candidates = [\"A\", \"B\", \"C\"])"
]
},
{
"cell_type": "code",
"execution_count": 8,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"A tie was broken.\n"
]
},
{
"data": {
"text/plain": [
"Candidate Status Round\n",
" B Elected 1\n",
" C Elected 1\n",
" A Eliminated 1"
]
},
"execution_count": 8,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"cumulative_election = HighestScore(profile = tied_cumulative_profile,\n",
" seats = num_seats)\n",
"cumulative_election.run_election()"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": []
}
],
"metadata": {
"kernelspec": {
"display_name": "votekit",
"language": "python",
"name": "votekit"
},
"language_info": {
"codemirror_mode": {
"name": "ipython",
"version": 3
},
"file_extension": ".py",
"mimetype": "text/x-python",
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.11.5"
}
},
"nbformat": 4,
"nbformat_minor": 2
}
2 changes: 2 additions & 0 deletions pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,8 @@ networkx = "^3.1"
jinja2 = "^3.1.2"
matplotlib = "^3.7.2"
pandas = "^1.5.3"
apportionment = "^1"



[tool.poetry.group.dev.dependencies]
Expand Down
82 changes: 80 additions & 2 deletions src/votekit/ballot.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@
from pydantic import BaseModel
from typing import Optional


class Ballot(BaseModel):
"""
Ballot class, contains ranking and assigned weight
Expand All @@ -19,7 +18,7 @@ class Ballot(BaseModel):
: weight assigned to a given a ballot

`voters`
: list of voters who cast a given a ballot
: set of voters who cast a given a ballot
"""

id: Optional[str] = None
Expand Down Expand Up @@ -57,3 +56,82 @@ def __eq__(self, other):

def __hash__(self):
return hash(str(self.ranking))


class PointBallot(BaseModel):
"""
Ballot class for voting methods that rely on point systems, like cumulative, Borda, approval.

**Attributes**

`id`
: optionally assigned ballot id

`points`
: list of candidates chosen with multiplicity or
dictionary whose keys are candidates and values are points given to candidates.

`weight`
: weight assigned to a given a ballot

`voters`
: set of voters who cast a given a ballot
"""

id: Optional[str] = None
weight: Fraction = Fraction(1,1)
voters: Optional[set[str]] = None
points: dict = {}

def __init__(self, id = None, weight = Fraction(1,1), voters = None, points = {}):

# convert list entry to dictionary
if isinstance(points, list):
di = {}
for candidate in points:
if candidate in di.keys():
di[candidate]+= 1
else:
di[candidate] = 1
points = di

super().__init__(id = id, weight = weight, voters = voters, points = points)




class Config:
arbitrary_types_allowed = True

def __eq__(self, other):
# Check type
if not isinstance(other, PointBallot):
return False

# Check id
if self.id is not None:
if self.id != other.id:
return False

# Check points
if self.points != other.points:
return False

# Check weight
if self.weight != other.weight:
return False

# Check voters
if self.voters is not None:
if self.voters != other.voters:
return False

return True

def __hash__(self):
return hash(str(self.points))

def __str__(self):
return f"{self.points} with weight {self.weight}"

__repr__ = __str__
69 changes: 67 additions & 2 deletions src/votekit/ballot_generator.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,9 +9,9 @@
import random
from typing import Optional

from .ballot import Ballot
from .ballot import Ballot, PointBallot
from .pref_profile import PreferenceProfile

import apportionment.methods as apportion # type: ignore
jamesturk marked this conversation as resolved.
Show resolved Hide resolved

class BallotGenerator:
"""
Expand Down Expand Up @@ -762,3 +762,68 @@ def generate_profile(self, number_of_ballots: int) -> PreferenceProfile:
ballot_pool=ballot_pool, candidates=self.candidates
)
return pp

class Cumulative(BallotGenerator):
"""
Class for generating cumulative voting ballots.

**Attributes**

`pref_interval_by_bloc`
: dictionary mapping of slate to preference interval
(ex. {race: {candidate : interval length}})

`bloc_voter_prop`
: dictionary mapping of slate to voter proportions (ex. {race: voter proportion})

`num_votes`
: the number of votes an individual voter has, usually the same as the number of seats up for
election.

**Methods**

See `BallotGenerator` base class
"""

def __init__(self, num_votes: int = 1, **data):

# Call the parent class's __init__ method to handle common parameters
super().__init__(**data)
self.num_votes = num_votes

def generate_profile(self, number_of_ballots) -> PreferenceProfile:
ballot_pool = []

# the number of ballots per bloc is determined by Huntington-Hill apportionment
blocs = list(self.bloc_voter_prop.keys())
bloc_props = list(self.bloc_voter_prop.values())
ballots_per_block = dict(zip(blocs, apportion.compute("huntington", bloc_props,
number_of_ballots)))

for bloc in self.bloc_voter_prop.keys():
# number of voters in this bloc
num_ballots = ballots_per_block[bloc]

pref_interval_dict = self.pref_interval_by_bloc[bloc]
# creates the interval of probabilities for candidates supported by this block
non_zero_cands = [cand for cand, prop in pref_interval_dict.items() if prop>0]
cand_support_vec = [pref_interval_dict[cand] for cand in non_zero_cands]

for _ in range(num_ballots):
# generates ranking based on probability distribution of candidate support
ballot = list(
np.random.choice(
non_zero_cands,
self.num_votes,
p=cand_support_vec,
replace=True,
)
)

ballot = PointBallot(points=ballot)
ballot_pool.append(ballot)


pp = PreferenceProfile(ballots = ballot_pool, candidates = self.candidates)
pp.condense_ballots()
return pp
Loading
Loading