Converters API

Converters between vote and result formats.

These objects have a convert() method that converts between different formats of votes or election results.

Vote aggregators

class votelib.convert.ApprovalToSimpleVotes(split=False)

Aggregate approval votes to simple votes.

Aggregate votes for candidate sets (approval votes) to separate votes for individual candidates. Useful for example in approval voting.

Parameters

split (bool) – Whether to split the vote power among all the candidates in the set (as in satisfaction approval voting) 1 or give full vote to each (as in ordinary approval voting) 2.

1

“Satisfaction approval voting”, Wikipedia. https://en.wikipedia.org/wiki/Satisfaction_approval_voting

2

“Approval voting”, Wikipedia. https://en.wikipedia.org/wiki/Approval_voting

convert(votes)

Convert approval votes to simple votes.

Return type

Dict[Union[str, CandidateObject], Number]

class votelib.convert.ScoreToSimpleVotes(function='mean', unscored_value=None, min_count=0, truncation=0, bottom_value=0)

Aggregate scores (cardinal votes) to simple votes.

Useful for score voting (range voting) systems. Note that, if the usual central value functions such as mean or median are used, this does not give scores that could be passed to ordinary magnitude-based evaluators since mean/median scores do not scale with the number of voters.

This can be used directly in combination with a simple-vote plurality evaluator but is also a component in several cardinal vote evaluators.

The scores can be arbitrary values as long as the aggregation function can cope with them, but numeric scores are the most common.

Parameters
  • function (Union[Callable[[List[Any]], Any], str]) – A function to aggregate all scores given to a candidate to a single score. It can also be specified by name (string); this looks into the exact aggregator register in the utility module (which reimplements some common aggregation functions to use exact arithmetic, such as the mean, which is the default here) and then searches builtin functions and the statistics stdlib module namespaces.

  • unscored_value (Union[Callable[[List[Any]], Any], Any, None]) – Score to give to a candidate that was not assigned a score by the voter. None means such ballots will not be considered for the candidate. A function can be specified to determine the value from all assigned scores (such as assigning the minimum). Builtin functions and functions from the statistics stdlib module can be specified by their names.

  • min_count (int) – Minimum count of voter scores for the candidate to be considered. Candidates below this threshold will be assigned bottom_value. This is used in some systems to prevent an unknown upset candidate to win by high score mean although they were scored only by a handful of highly dedicated voters.

  • truncation (Number) – Fraction (if lower than 1) or count (if at least 1) of lowest and highest scores to disregard before aggregating, to stabilize the result. (Both ends are trimmed using this, so the number/fraction of scores disregarded is twice the count/fraction.)

  • bottom_value (Any) – Value to assign to candidates with less voter scores than min_count. This would usually be the lowest possible aggregate score.

aggregate(scores)

Aggregate corrected score votes to scores per candidate.

Parameters

scores (Dict[Union[str, CandidateObject], Dict[Any, int]]) – Corrected scores in an intermediate format of a nested dict (candidates are mapped to dictionaries mapping score values to numbers of their occurrences).

Return type

Dict[Union[str, CandidateObject], Any]

Returns

A mapping from candidates to their aggregate scores.

aggregate_one(cscores)

Aggregate corrected scores for a candidate to a single score.

Return type

Any

convert(votes)

Convert score votes to simple votes.

Parameters

votes (Dict[FrozenSet[Tuple[Union[str, CandidateObject], Any]], int]) – Uncorrected score votes.

Return type

Dict[Union[str, CandidateObject], Any]

Returns

A mapping from candidates to their aggregate scores.

corrected_scores(votes)

Correct score votes to an intermediate format.

This forms the first part of the conversion (the second is aggregate()) and is exposed independently to allow for repeated aggregation which is used by some score voting evaluators.

The correction adds values for unscored candidates, assigns a fixed value to candidates with too few votes, and potentially truncates the scores to enable truncated central values.

Parameters

votes (Dict[FrozenSet[Tuple[Union[str, CandidateObject], Any]], int]) – Uncorrected score votes.

Return type

Dict[Union[str, CandidateObject], Dict[Any, int]]

Returns

Corrected scores in a nested dictionary (candidates are mapped to dictionaries mapping score values to numbers of their occurrences).

class votelib.convert.RankedToPositionalVotes(rank_scorer, unranked_scoring='zero')

Aggregate ranked votes to simple votes.

Useful for Borda count systems. Assigns a score to each rank and then sums the scores. The complete Borda count system is obtained by coupling this converter with the Plurality evaluator.

Parameters
  • rank_scorer (RankScorer) – A rank scorer that determines which score to assign to which rank through its scores() method. You can use any object that honors the interface of rankscore.RankScorer, such as any of its subclasses.

  • unranked_scoring (str) – What score to assign to candidates not ranked by the given voter. So far only the ‘zero’ option, which assigns a score of zero, is supported.

convert(votes)

Convert ranked votes to simple votes by scoring their positions.

Return type

Dict[Union[str, CandidateObject], Number]

class votelib.convert.RankedToCondorcetVotes(unranked_at_bottom=True)

Aggregate ranked votes to counts of pairwise wins.

Basic component for Condorcet methods. For each ballot that ranks a pair of candidates in a given order, adds one to the count of the first candidate over the second.

Parameters

unranked_at_bottom (bool) – Whether to consider candidates not ranked on a ballot as being ranked last. If False, these candidates are not considered (the voter is assumed not to have any preferences there).

convert(votes)

Convert ranked votes to counts of pairwise wins.

Return type

Dict[Tuple[Union[str, CandidateObject], Union[str, CandidateObject]], int]

class votelib.convert.ScoreToRankedVotes(unscored_value=None)

Convert score votes to ranked votes.

This is useful to employ ranked voting methods for run-off in some score voting systems to reduce their susceptibility to tactical voting (e.g. STAR voting).

Parameters

unscored_value (Union[str, Number, None]) – Score to give to a candidate that was not assigned a score by the voter. None means such ballots will not be considered for the candidate. A callable is not accepted.

convert(votes)

Convert score votes to ranked votes.

Parameters

votes (Dict[FrozenSet[Tuple[Union[str, CandidateObject], Any]], int]) – Score votes.

Return type

Dict[Tuple[Union[str, CandidateObject, FrozenSet[Union[str, CandidateObject]]], …], int]

Vote inverters to negative votes

class votelib.convert.InvertedSimpleVotes

Vote inverter to represent negative simple votes.

In some voting systems, voters vote against rather than for candidates.

convert(votes)

Invert the count signs of single votes.

Return type

Dict[Union[str, CandidateObject], Number]

Individual candidate/party conversion

class votelib.convert.IndividualToPartyVotes(mapper=<votelib.candidate.IndividualToPartyMapper object>)

Aggregate votes for individual candidates to votes for their parties.

Useful for cases where votes are received by candidates but also considered by party, e.g. in panachage systems.

Parameters

mapper (IndividualToPartyMapper) – A mapper object specifying the mapping from individuals to parties.

convert(votes)

Convert individual simple votes to party-based simple votes.

Return type

Dict[ElectionParty, int]

class votelib.convert.IndividualToPartyResult(mapper=<votelib.candidate.IndividualToPartyMapper object>)

Aggregate individual elected candidates to results for their parties.

Useful to determine party results in systems (or parts thereof) where party affiliation is not taken into account during evaluation, e.g. in STV systems (Ireland) or in mixed-member proportional systems (Germany) to determine the number of directly elected candidates before party-based seats are allocated.

Parameters

mapper (IndividualToPartyMapper) – A mapper object specifying the mapping from individuals to parties.

convert(results)

Convert individual selection results to party-based counts.

Return type

Dict[ElectionParty, int]

Result conversion and merging

class votelib.convert.SelectionToDistribution(amount=1)

Adapt selection results to distribution (seat count) format.

This can be used e.g. for majority bonus systems where the largest party gets a predetermined amount of additional reserved seats, or in mixed-member proportional systems to determine party-wise results of the constituency round.

Parameters

amount (Number) – How many votes to attribute to each winner of the selection.

convert(elected)

Convert selection results to distribution results.

Return type

Dict[Union[str, CandidateObject], int]

class votelib.convert.MergedSelections

Compile candidates elected in constituencies to a single result list.

The candidates are ordered by their positions in the district-wide result lists.

Useful e.g. in mixed-member proportional systems to list all candidates elected in constituencies.

convert(elected)

Compile constituency election results to a single result list.

Parameters

elected (Union[Dict[Constituency, List[Union[str, CandidateObject]]], List[List[Union[str, CandidateObject]]]]) – Partial selection results in a list or dictionary; if a dictionary, its keys are ignored and values treated as a list.

Return type

List[Union[str, CandidateObject]]

class votelib.convert.MergedDistributions

Merge many distribution election results into one.

Aggregates distribution election results from a list or dictionary of partial results (e.g. by constituency) into a single candidate-wise dictionary. Neither reconciles ties nor preserves result ordering.

Use VoteTotals to aggregate votes.

convert(elected)

Aggregate many distribution election results into one.

Parameters

elected (Union[Dict[Constituency, Dict[Union[str, CandidateObject], int]], List[Dict[Union[str, CandidateObject], int]]]) – Partial distribution election results in a list or dictionary; if a dictionary, its keys are ignored and values treated as a list.

Return type

Dict[Union[str, CandidateObject], int]

Constituency-based vote handling and aggregation

class votelib.convert.VoteTotals

Count total votes/results for each candidate in all constituencies.

If votes of other type than simple are given, counts the totals of votes. Use MergedDistributions to aggregate distribution election results.

convert(votes)

Count total votes for each candidate in all constituencies.

Parameters

votes (Dict[Constituency, Dict[Any, int]]) – Votes of any type.

Return type

Dict[Any, int]

class votelib.convert.ConstituencyTotals

Count total votes (or results) for all candidates in each constituency.

Accepts any type of votes or distribution election results.

Useful for apportionment of seats to districts.

convert(votes)

Return total votes for all candidates in each constituency.

Parameters

votes (Dict[Constituency, Dict[Any, int]]) – Votes of any type, or distribution election results.

Return type

Dict[Constituency, int]

class votelib.convert.PartyTotals

Count total votes for parties from grouped votes for its candidates.

Accepts any type of votes or distribution election results.

Useful for evaluating party-based results in systems where votes can be received by individual candidates (panachage) if the results are already grouped by party in a nested dictionary, e.g. after applying GroupVotesByParty.

convert(votes)

Return total votes for all candidates of each party.

Parameters

votes (Dict[ElectionParty, Dict[Any, int]]) – Votes of any type, or distribution election results.

Return type

Dict[ElectionParty, int]

class votelib.convert.ByConstituency(converter)

Perform conversion for each constituency votes/results separately.

Parameters

converter (Converter) – A converter to wrap. Will be called to convert votes (or results) for each constituency separately.

convert(values)

Convert the votes/results for each constituency.

Parameters

values (Dict[Constituency, Dict[Any, Any]]) – Mapping of constituencies to votes or results. The keys of this dictionary will be transferred unchanged to the result, with their values converted by the wrapped converter.

Return type

Dict[Constituency, Dict[Any, Any]]

Vote corrections and subsetting

class votelib.convert.RoundedVotes(decimals, round_method='ROUND_HALF_UP')

Round vote counts to the given number of decimal digits.

In some systems, rounding of fractional values to a given number of digits is specified (e.g. Scottish STV). This rounds vote counts of any vote type to this number of decimals.

Parameters
  • decimals (int) – Number of digits to round to. Negative values are not accepted.

  • round_method – A rounding method accepted by Python’s decimal module.

Raises

ValueError – If an invalid number of decimal digits is given.

convert(votes)

Round all vote counts to the specified number of votes.

The vote counts must be convertible to Decimal (Fraction and any types accepted by the decimal constructor are supported).

Parameters

votes (Dict[Any, Number]) – Votes whose counts should be rounded.

Return type

Dict[Any, Decimal]

class votelib.convert.SubsettedVotes(vote_subsetter=<votelib.vote.SimpleSubsetter object>, depth=0)

Subset the votes to only concern a subset of candidates.

A wrapper over VoteSubsetter that takes the entire vote count dictionary, not just a single vote object (key). Useful when some candidates should be excluded because they do not pass an electoral threshold, or when evaluating ties.

Parameters

vote_subsetter (VoteSubsetter) – A vote subsetter that turns a single vote object (key) into a vote object that only concerns the specified candidates, with other candidates removed.

convert(votes, subset)

Subset the votes to only concern a subset of candidates.

Parameters
  • votes (Dict[Any, Number]) – Votes to be subsetted. Their type should be in accordance with the wrapped vote subsetter.

  • subset (Collection[Union[str, CandidateObject]]) – The only candidates that should be contained in the output.

Return type

Dict[Any, Number]

class votelib.convert.InvalidVoteEliminator(validator)

Only allow through votes that are declared valid by a given validator.

Calls the validate() method of the validator for each of the keys of the input dictionary; if an vote.VoteError is raised, does not include the vote in the output.

Parameters

validator (VoteValidator) – The vote validator to use. Look for some in the vote module.

convert(votes)

Copy the votes dictionary, removing invalid votes.

If no invalid votes are detected, does not make a copy.

Return type

Dict[Any, int]