-
Notifications
You must be signed in to change notification settings - Fork 29
Feat/allow int candidates #370
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
Open
graceg571
wants to merge
10
commits into
mggg:3.4.1
Choose a base branch
from
graceg571:feat/allow-int-candidates
base: 3.4.1
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
10 commits
Select commit
Hold shift + click to select a range
ac74d1d
initial pass, translate cand to ids
graceg571 da89464
remove cached property of cand attributes
graceg571 dbfc017
accept int or str candidates
graceg571 610f73c
fix pyright errors
graceg571 43a0e5f
add mixed cand fuzz test, update std ballot generators to accept mixe…
graceg571 f8976dd
add internal df tests, mixed cands ballots, warning 1, 1 cands
graceg571 e2d4cec
add df with mixed cands tests
graceg571 c9308ca
update docstring to candidate, cand=int|str
graceg571 9622fea
update docstring for _convert_dict_to_matrix
graceg571 0be9799
fix candidate docstrings, add lexico sort for mixed candidates, add s…
graceg571 File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
Large diffs are not rendered by default.
Oops, something went wrong.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -1,35 +1,45 @@ | ||
| from __future__ import annotations | ||
|
|
||
| import warnings | ||
| from numbers import Real | ||
| from typing import Iterable, Optional, Sequence, TypeAlias, Union, overload | ||
| from typing import Iterable, Mapping, Optional, Sequence, TypeAlias, Union, overload | ||
|
|
||
| Ranking: TypeAlias = Optional[tuple[frozenset[str], ...]] | ||
| RankingLike: TypeAlias = Optional[Sequence[str | Iterable[str]]] | ||
| from votekit.types import Candidate | ||
|
|
||
| Ranking: TypeAlias = Optional[tuple[frozenset[Candidate], ...]] | ||
| RankingLike: TypeAlias = Optional[Sequence[Candidate | Iterable[Candidate]]] | ||
| ScoresLike: TypeAlias = Optional[ | ||
| Mapping[Candidate, float | int] | Mapping[str, float | int] | Mapping[int, float | int] | ||
| ] | ||
|
|
||
|
|
||
| class Ballot: | ||
| """ | ||
| Ballot parent class, contains voter set and assigned weight. | ||
|
|
||
| Args: | ||
| ranking (Optional[Sequence[str | Iterable[str]]]): Candidate ranking. | ||
| ranking (Optional[Sequence[Candidate | Iterable[Candidate]]]): Candidate ranking. | ||
| Entry i of the sequence is a candidate or iterable of candidates ranked in position i. | ||
| Defaults to None. Will be coerced to tuple[frozenset[str], ...]. | ||
| Candidates can be strings, integers, or mix of both. | ||
| Defaults to None. Will be coerced to tuple[frozenset[str | int], ...]. | ||
| weight (Union[float, int]): Weight assigned to a given ballot. Defaults to 1.0 | ||
| Can be input as int or float, and will be coerced to float. | ||
| voter_set (Union[set[str], frozenset[str]]): Set of voters who cast the ballot. | ||
| Defaults to frozenset(). Will be coerced to frozenset. | ||
| scores (Optional[dict[str, Union[int, float]]): Scores for individual candidates. | ||
| Defaults to None. Values can be input as int or float but will be coerced to float. | ||
| scores (Optional[Mapping[Candidate, float | int] | Mapping[str, float | int] | ||
| | Mapping[int, float | int]]): Scores for individual candidates. Defaults to None. | ||
| Values can be input as int or float but will be coerced to float. | ||
| Candidates can be strings, integers, or mix of both. | ||
| Stored internally as a dict[str | int, float]. | ||
| Only retains non-zero scores. | ||
|
|
||
| Attributes: | ||
| ranking (Optional[tuple[frozenset[str], ...]]): Tuple of candidate ranking. | ||
| Entry i of the tuple is a | ||
| frozenset of candidates ranked in position i. | ||
| ranking (Optional[tuple[frozenset[Candidate], ...]]): Tuple of candidate ranking. | ||
| Entry i of the tuple is a frozenset of candidates ranked in position i. | ||
| Candidates can be strings, integers, or mix of both. | ||
| weight (float): Weight assigned to a given ballot. | ||
| voter_set (frozenset[str]): Set of voters who cast the ballot. | ||
| scores (Optional[dict[str, float]]): Scores for individual candidates. | ||
| scores (Optional[Mapping[Candidate, float | int]): Scores for individual candidates. | ||
|
|
||
| Raises: | ||
| TypeError: Only one of ranking or scores can be provided. | ||
|
|
@@ -49,7 +59,7 @@ class Ballot: | |
| def __new__( | ||
| cls, | ||
| *, | ||
| ranking: Sequence[str | Iterable[str]], | ||
| ranking: RankingLike, | ||
| scores: None = None, | ||
| weight: Union[float, int] = 1.0, | ||
| voter_set: Union[set[str], frozenset[str]] = frozenset(), | ||
|
|
@@ -60,7 +70,7 @@ def __new__( | |
| cls, | ||
| *, | ||
| ranking: None = None, | ||
| scores: dict[str, Union[int, float]], | ||
| scores: ScoresLike, | ||
| weight: Union[float, int] = 1.0, | ||
| voter_set: Union[set[str], frozenset[str]] = frozenset(), | ||
| ) -> ScoreBallot: ... | ||
|
|
@@ -69,17 +79,17 @@ def __new__( | |
| def __new__( | ||
| cls, | ||
| *, | ||
| ranking: Optional[Sequence[str | Iterable[str]]] = None, | ||
| scores: Optional[dict[str, Union[int, float]]] = None, | ||
| ranking: RankingLike = None, | ||
| scores: ScoresLike = None, | ||
| weight: Union[float, int] = 1.0, | ||
| voter_set: Union[set[str], frozenset[str]] = frozenset(), | ||
| ) -> Ballot: ... | ||
|
|
||
| def __new__( | ||
| cls, | ||
| *, | ||
| ranking: Optional[Sequence[str | Iterable[str]]] = None, | ||
| scores: Optional[dict[str, Union[int, float]]] = None, | ||
| ranking: RankingLike = None, | ||
| scores: ScoresLike = None, | ||
| weight: Union[float, int] = 1.0, | ||
| voter_set: Union[set[str], frozenset[str]] = frozenset(), | ||
| ): | ||
|
|
@@ -95,8 +105,8 @@ def __new__( | |
| def __init__( | ||
| self, | ||
| *, | ||
| ranking: Optional[Sequence[str | Iterable[str]]] = None, | ||
| scores: Optional[dict[str, Union[int, float]]] = None, | ||
| ranking: RankingLike = None, | ||
| scores: ScoresLike = None, | ||
| weight: Union[float, int] = 1.0, | ||
| voter_set: Union[set[str], frozenset[str]] = frozenset(), | ||
| ): | ||
|
|
@@ -152,25 +162,29 @@ class RankBallot(Ballot): | |
|
|
||
| Args: | ||
| ranking (RankingLike): Ranking of candidates, defaults to None. | ||
| RankingLike = Sequence[Candidate | Iterable[Candidate]] | None | ||
| Canidates can be strings, integers, or mix of both. | ||
| weight (Union[int, float]): Weight of the ballot, defaults to 1.0. | ||
| voter_set (Union[set[str], frozenset[str]]): Voter set of the ballot, | ||
| defaults to frozenset(). | ||
|
|
||
| Attributes: | ||
| ranking (RankingLike): Ranking of candidates. | ||
| ranking (Ranking): Ranking of candidates. | ||
| Ranking = tuple[frozenset[Candidate], ...] | None | ||
| weight (float): Weight of the ballot. | ||
| voter_set (frozenset[str]): Voter set of the ballot. | ||
|
|
||
| Raises: | ||
| ValueError: Candidate '~' found in ballot ranking. | ||
| ValueError: Ballot weight cannot be negative. | ||
| UserWarning: '1' and 1 candidates are treated as separate candidates. | ||
| """ | ||
|
|
||
| def __init__( | ||
| self, | ||
| *, | ||
| ranking: RankingLike = None, | ||
| scores: Optional[dict[str, Union[int, float]]] = None, | ||
| scores: ScoresLike = None, | ||
| weight: Union[int, float] = 1.0, | ||
| voter_set: Union[set[str], frozenset[str]] = frozenset(), | ||
| ): | ||
|
|
@@ -194,22 +208,40 @@ def _convert_ranking_candidates_to_frozenset_strip_whitespace( | |
|
|
||
| normalized_ranking = [] | ||
| for cand_set in ranking: | ||
| if isinstance(cand_set, str): | ||
| normalized_ranking.append(frozenset({cand_set.strip()})) | ||
| if isinstance(cand_set, Candidate): | ||
| normalized_ranking.append( | ||
| frozenset({cand_set.strip() if isinstance(cand_set, str) else cand_set}) | ||
| ) | ||
| else: | ||
| normalized_ranking.append(frozenset(c.strip() for c in cand_set)) | ||
| normalized_ranking.append( | ||
| frozenset(c.strip() if isinstance(c, str) else c for c in cand_set) | ||
| ) | ||
| return tuple(normalized_ranking) | ||
|
|
||
| def _validate_ranking_candidates(self, ranking: Ranking): | ||
| if ranking is None: | ||
| return | ||
| if any(c == "~" for cand_set in ranking for c in cand_set): | ||
| if any(cand == "~" for cand_set in ranking for cand in cand_set): | ||
| raise ValueError( | ||
| f"Candidate '~' found in ballot ranking {ranking}." | ||
| " '~' is a reserved character and cannot be used for" | ||
| " candidate names." | ||
| ) | ||
|
|
||
| str_cands = {cand for cand_set in ranking for cand in cand_set if isinstance(cand, str)} | ||
| int_cands = {cand for cand_set in ranking for cand in cand_set if isinstance(cand, int)} | ||
| collisions = { | ||
| str_cand | ||
| for str_cand in str_cands | ||
| if str_cand.lstrip("-").isdigit() and int(str_cand) in int_cands | ||
| } | ||
| if collisions: | ||
| warnings.warn( | ||
| f"Candidates {collisions} appear as both str and int (e.g. '1' and 1)." | ||
| " These will be treated as separate candidates.", | ||
| UserWarning, | ||
| ) | ||
|
|
||
|
Comment on lines
+231
to
+244
Collaborator
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Let's take the convention that integer candidates are non-negative so we don't need to worry about '-1' or '--1' or '---1' |
||
| def __eq__(self, other): | ||
| if not isinstance(other, RankBallot): | ||
| return False | ||
|
|
@@ -246,56 +278,76 @@ class ScoreBallot(Ballot): | |
| Class to handle ballots with scores. Strips whitespace from candidate names. | ||
|
|
||
| Args: | ||
| scores (Optional[dict[str, Union[int, float]]]): Scores of candidates, defaults to None. | ||
| scores (ScoresLike): Scores of candidates, defaults to None. | ||
| ScoresLike = Mapping[Candidate, int | float] | Mapping[str, int | float] | ||
| | Mapping[int, int | float] | None | ||
| Candidates can be strings, integers, or mix of both. | ||
| weight (Union[int, float]): Weight of the ballot, defaults to 1.0. | ||
| voter_set (Union[set[str], frozenset[str]]): Voter set of the ballot, | ||
| defaults to frozenset(). | ||
|
|
||
| Attributes: | ||
| scores (Optional[dict[str, float]]): Scores of candidates. | ||
| scores (Optional[dict[Candidate, float]]): Scores of candidates. | ||
| weight (float): Weight of the ballot. | ||
| voter_set (frozenset[str]): Voter set of the ballot. | ||
|
|
||
| Raises: | ||
| ValueError: Candidate '~' found in ballot scores. | ||
| ValueError: Ballot weight cannot be negative. | ||
| TypeError: Score values must be numeric. | ||
| UserWarning: '1' and 1 candidates are treated as separate candidates. | ||
| """ | ||
|
|
||
| def __init__( | ||
| self, | ||
| *, | ||
| ranking: RankingLike = None, | ||
| scores: Optional[dict[str, Union[int, float]]] = None, | ||
| scores: ScoresLike = None, | ||
| weight: Union[int, float] = 1.0, | ||
| voter_set: Union[set[str], frozenset[str]] = frozenset(), | ||
| ): | ||
| if ranking is not None: | ||
| raise TypeError("Only one of ranking or scores can be provided.") | ||
| scores = self._convert_scores_to_float_strip_whitespace(scores) | ||
| self._validate_scores_candidates(scores) | ||
| self.scores = self._convert_scores_to_float_strip_whitespace(scores) | ||
| self.scores = scores | ||
|
|
||
| super().__init__(weight=weight, voter_set=voter_set) | ||
|
|
||
| def _validate_scores_candidates(self, scores: Optional[dict[str, Union[int, float]]]): | ||
| if scores is not None: | ||
| if "~" in scores: | ||
| raise ValueError( | ||
| f"Candidate '~' found in ballot scores {list(scores.keys())}." | ||
| " '~' is a reserved character and cannot be used for" | ||
| " candidate names." | ||
| ) | ||
|
|
||
| def _convert_scores_to_float_strip_whitespace( | ||
| self, scores: Optional[dict[str, float]] | ||
| ) -> Optional[dict[str, float]]: | ||
| self, scores: ScoresLike | ||
| ) -> Optional[dict[Candidate, float]]: | ||
| if scores is None: | ||
| return None | ||
|
|
||
| if any(not isinstance(s, Real) for s in scores.values()): | ||
| raise TypeError("Score values must be numeric.") | ||
|
|
||
| return {c.strip(): float(s) for c, s in scores.items() if s != 0} | ||
| return { | ||
| c.strip() if isinstance(c, str) else c: float(s) for c, s in scores.items() if s != 0 | ||
| } | ||
|
|
||
| def _validate_scores_candidates(self, scores: ScoresLike): | ||
| if scores is not None: | ||
| if "~" in scores: | ||
| raise ValueError( | ||
| f"Candidate '~' found in ballot scores {list(scores.keys())}." | ||
| " '~' is a reserved character and cannot be used for" | ||
| " candidate names." | ||
| ) | ||
| str_cands = {cand for cand in scores.keys() if isinstance(cand, str)} | ||
| int_cands = {cand for cand in scores.keys() if isinstance(cand, int)} | ||
| collisions = { | ||
| str_cand | ||
| for str_cand in str_cands | ||
| if str_cand.lstrip("-").isdigit() and int(str_cand) in int_cands | ||
| } | ||
| if collisions: | ||
| warnings.warn( | ||
| f"Candidates {collisions} appear as both str and int (e.g. '1' and 1)." | ||
| " These will be treated as separate candidates.", | ||
| UserWarning, | ||
| ) | ||
|
|
||
| def __eq__(self, other): | ||
| if not isinstance(other, ScoreBallot): | ||
|
|
@@ -306,11 +358,7 @@ def __eq__(self, other): | |
|
|
||
| def __hash__(self): | ||
| return ( | ||
| hash( | ||
| tuple(sorted((c, s) for c, s in self.scores.items())) | ||
| if self.scores is not None | ||
| else self.scores | ||
| ) | ||
| hash(frozenset(self.scores.items()) if self.scores is not None else self.scores) | ||
| + super().__hash__() | ||
| ) | ||
|
|
||
|
|
||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Types.py?