Election module

Contents

Election module#

Alternatives#

class Alternative(name)[source]#

Bases: object

Represents an alternative, i.e., one of the potential outcomes of the election.

An alternative is represented by its name. Equality, hash, and other tests are based on the name.

Parameters:

name (str) – The identifier or label for the alternative.

name#

The identifier or label for the alternative.

Type:

str

Trichotomous Ballots#

class AbstractTrichotomousBallot[source]#

Bases: ABC

Abstract base class for a trichotomous ballot.

A trichotomous ballot partitions alternatives into approved and disapproved sets, with the implicit third category being neutral or unknown.

Subclasses must implement the approved and disapproved properties.

class TrichotomousBallot(*, approved: Iterable[Alternative] = None, disapproved: Iterable[Alternative] = None)[source]#

Bases: AbstractTrichotomousBallot

Represents a mutable trichotomous ballot, where alternatives are categorized into approved, disapproved, or implicitly neutral.

Parameters:
  • approved (Iterable[Alternative], optional) – Approved alternatives.

  • disapproved (Iterable[Alternative], optional) – Disapproved alternatives.

approved#

The alternatives the voter approves of.

Type:

set[Alternative]

disapproved#

The alternatives the voter disapproves of.

Type:

set[Alternative]

add_approved(alt: Alternative) None[source]#

Add an alternative to the approved set.

Parameters:

alt (Alternative) – The alternative to approve.

add_disapproved(alt: Alternative) None[source]#

Add an alternative to the disapproved set.

Parameters:

alt (Alternative) – The alternative to disapprove.

freeze() FrozenTrichotomousBallot[source]#

Return an immutable version of this ballot.

Returns:

A frozen (immutable) copy of this ballot.

Return type:

FrozenTrichotomousBallot

property approved: set[Alternative]#

Set of approved alternatives.

property disapproved: set[Alternative]#

Set of disapproved alternatives.

class FrozenTrichotomousBallot(*, approved: Iterable[Alternative] = None, disapproved: Iterable[Alternative] = None)[source]#

Bases: AbstractTrichotomousBallot

Represents an immutable trichotomous ballot using tuples for storage.

This version is suitable for hashing and storing in sets or as keys in dictionaries.

Parameters:
  • approved (Iterable[Alternative], optional) – Approved alternatives.

  • disapproved (Iterable[Alternative], optional) – Disapproved alternatives.

approved#

The alternatives the voter approves of.

Type:

tuple[Alternative, …]

disapproved#

The alternatives the voter disapproves of.

Type:

tuple[Alternative, …]

property approved: tuple[Alternative, ...]#

Tuple of approved alternatives.

property disapproved: tuple[Alternative, ...]#

Tuple of disapproved alternatives.

Trichotomous Profiles#

class AbstractTrichotomousProfile(alternatives: Iterable[Alternative] = None, max_size_selection: int = None)[source]#

Abstract class representing a profile, i.e., a collection of ballots. This class is only meant to be inherited and provides a common interface for trichotomous profiles.

alternatives#

The set of all alternatives in the profile.

Type:

set[Alternative]

max_size_selection#

The maximum number of alternatives that can be selected in a feasible selection (optional).

Type:

int or None

class TrichotomousProfile(init: Iterable[TrichotomousBallot] = (), *, alternatives: Iterable[Alternative] = None, max_size_selection: int = None)[source]#

Bases: AbstractTrichotomousProfile, MutableSequence[TrichotomousBallot]

Represents a trichotomous profile, i.e., a collection of trichotomous ballots, one per voter.

Parameters:
  • init (Iterable[TrichotomousBallot], optional) – An iterable of trichotomous ballots used to initialize the profile. Defaults to empty.

  • alternatives (Iterable[Alternative], optional) – An iterable of alternatives representing all alternatives of the instance.

  • max_size_selection (int, optional) – The maximum number of alternatives to be selected when computing the outcome of a rule on the profile. Used notably when reading files from preference libraries.

alternatives#

A set of alternatives representing all the alternatives of the instance.

Type:

set[Alternative]

max_size_selection#

The maximum number of alternatives to be selected when computing the outcome of a rule on the profile.

Type:

int or None

add_ballot(ballot: TrichotomousBallot)[source]#

Adds a ballot to the profile.

Parameters:

ballot (AbstractTrichotomousBallot) – The ballot to add.

all_sub_profiles() Iterator[TrichotomousProfile][source]#

Returns an iterator over all possible sub-profiles of the current profile.

A sub-profile is any subset of the ballots from the current profile.

Returns:

An iterator that yields all possible sub-profiles.

Return type:

Iterator[TrichotomousProfile]

append(value)[source]#

S.append(value) – append value to the end of the sequence

approval_disapproval_score(alternative: Alternative) tuple[int, int][source]#

Returns the approval and disapproval score of an alternative together at the same time.

Parameters:

alternative (Alternative) – The alternative to consider.

Returns:

The approval and the disapproval score of the alternative.

Return type:

tuple[int, int]

approval_disapproval_score_dict() tuple[defaultdict[Alternative, int], defaultdict[Alternative, int]][source]#

Returns the dictionaries of the approval score and of the disapproval score.

Returns:

The approval score and the disapproval score dictionaries. Alternatives never appearing (approved or disapproved) in any ballot will be absent, but accessing them returns 0.

Return type:

tuple[collections.defaultdict[Alternative, int], collections.defaultdict[Alternative, int]]

approval_score(alternative: Alternative) int[source]#

Returns the approval score of an alternative, i.e., the number of voters approving of it.

Parameters:

alternative (Alternative) – The alternative to consider.

Returns:

The approval score of the alternative.

Return type:

int

approval_score_dict() defaultdict[Alternative, int][source]#

Returns the approval scores of the alternatives of the profile as a dictionary.

Returns:

The approval score of each alternative appearing in at least one ballot. Alternatives never approved in any ballot will be absent, but accessing them returns 0.

Return type:

collections.defaultdict[Alternative, int]

as_multiprofile() TrichotomousMultiProfile[source]#

Returns the multiprofile corresponding to this profile. Ballots are converted to immutable frozen ballots.

Returns:

The multiprofile representation of this profile with frozen ballots.

Return type:

TrichotomousMultiProfile

clear() None -- remove all items from S[source]#
count(value) integer -- return number of occurrences of value[source]#
disapproval_score(alternative: Alternative) int[source]#

Returns the disapproval score of an alternative, i.e., the number of voters disapproving of it.

Parameters:

alternative (Alternative) – The alternative to consider.

Returns:

The disapproval score of the alternative.

Return type:

int

disapproval_score_dict() defaultdict[Alternative, int][source]#

Returns the disapproval scores of the alternatives of the profile as a dictionary.

Returns:

The disapproval score of each alternative appearing in at least one ballot. Alternatives never disapproved in any ballot will be absent, but accessing them returns 0.

Return type:

collections.defaultdict[Alternative, int]

extend(iterable)[source]#

S.extend(iterable) – extend sequence by appending elements from the iterable

index(value[, start[, stop]]) integer -- return first index of value.[source]#

Raises ValueError if the value is not present.

Supporting start and stop arguments is optional, but recommended.

insert(index, value)[source]#

S.insert(index, value) – insert value before index

multiplicity(ballot: TrichotomousBallot) int[source]#

Returns the multiplicity of a ballot in the profile.

Note: This implementation returns 1 for any ballot regardless of its presence in the profile, to save computation time.

Parameters:

ballot (TrichotomousBallot) – The ballot whose multiplicity is inquired.

Returns:

The multiplicity of the ballot, always 1.

Return type:

int

num_ballots() int[source]#

Returns the number of ballots in the profile.

Returns:

The multiplicity of the ballots.

Return type:

int

pop([index]) item -- remove and return item at index (default last).[source]#

Raise IndexError if list is empty or index is out of range.

remove(value)[source]#

S.remove(value) – remove first occurrence of value. Raise ValueError if the value is not present.

reverse()[source]#

S.reverse() – reverse IN PLACE

support(alternative: Alternative) int[source]#

Returns the support of an alternative, i.e., the net number of voters supporting it (the number of approvers minus the number of disapprovers).

Parameters:

alternative (Alternative) – The alternative to consider.

Returns:

The support of the alternative.

Return type:

int

support_dict() defaultdict[Alternative, int][source]#

Returns the support of the alternatives of the instance as a dictionary.

Returns:

The support of each alternative appearing in at least one ballot. Alternatives never appearing (approved or disapproved) in any ballot will be absent, but accessing them returns 0.

Return type:

collections.defaultdict[Alternative, int]

class TrichotomousMultiProfile(init: Iterable[FrozenTrichotomousBallot] = (), *, alternatives: Iterable[Alternative] = None, max_size_selection: int = None)[source]#

Bases: AbstractTrichotomousProfile, MutableMapping[FrozenTrichotomousBallot, int]

Represents a trichotomous multi-profile, i.e., a collection of trichotomous ballots where identical ballots are stored together with their multiplicities.

This class models a multi-set of ballots, where each unique frozen ballot is associated with an integer count indicating how many times it appears in the profile.

Parameters:
  • init (Iterable[FrozenTrichotomousBallot], optional) – An iterable of frozen trichotomous ballots used to initialize the multi-profile. Defaults to an empty iterable.

  • alternatives (Iterable[Alternative], optional) – An iterable of all alternatives present in the profile. If not provided and init is an AbstractTrichotomousProfile, its alternatives are used.

  • max_size_selection (int, optional) – The maximum number of alternatives to be selected when computing the outcome of a rule on the profile. Used notably when reading files from preference libraries. If not provided and init is an AbstractTrichotomousProfile, its max_size_selection is used.

_ballots_counter#

Internal counter mapping each frozen trichotomous ballot to its multiplicity.

Type:

collections.Counter

alternatives#

The set of all alternatives in the profile.

Type:

set[Alternative]

max_size_selection#

Maximum number of alternatives to select in an outcome (optional).

Type:

int

add_ballot(ballot: FrozenTrichotomousBallot)[source]#

Adds a ballot to the multi-profile, increasing its multiplicity by one.

Parameters:

ballot (FrozenTrichotomousBallot) – The frozen ballot to add.

all_sub_profiles() Iterator[TrichotomousMultiProfile][source]#

Generates all possible sub-profiles of the current multi-profile.

A sub-profile is any profile obtained by choosing any number (including zero) of occurrences of each ballot up to their multiplicity in the current profile.

Yields:

TrichotomousMultiProfile – Each possible sub-profile.

approval_disapproval_score(alternative: Alternative) tuple[int, int][source]#

Returns the approval and disapproval score of an alternative together at the same time.

Parameters:

alternative (Alternative) – The alternative to consider.

Returns:

The approval and the disapproval score of the alternative.

Return type:

tuple[int, int]

approval_disapproval_score_dict() tuple[defaultdict[Alternative, int], defaultdict[Alternative, int]][source]#

Returns the dictionaries of the approval score and of the disapproval score.

Returns:

The approval score and the disapproval score dictionaries. Alternatives never appearing (approved or disapproved) in any ballot will be absent, but accessing them returns 0.

Return type:

tuple[collections.defaultdict[Alternative, int], collections.defaultdict[Alternative, int]]

approval_score(alternative: Alternative) int[source]#

Returns the approval score of an alternative, i.e., the number of voters approving of it.

Parameters:

alternative (Alternative) – The alternative to consider.

Returns:

The approval score of the alternative.

Return type:

int

approval_score_dict() defaultdict[Alternative, int][source]#

Returns the approval scores of the alternatives of the profile as a dictionary.

Returns:

The approval score of each alternative appearing in at least one ballot. Alternatives never approved in any ballot will be absent, but accessing them returns 0.

Return type:

collections.defaultdict[Alternative, int]

clear() None.  Remove all items from D.[source]#
disapproval_score(alternative: Alternative) int[source]#

Returns the disapproval score of an alternative, i.e., the number of voters disapproving of it.

Parameters:

alternative (Alternative) – The alternative to consider.

Returns:

The disapproval score of the alternative.

Return type:

int

disapproval_score_dict() defaultdict[Alternative, int][source]#

Returns the disapproval scores of the alternatives of the profile as a dictionary.

Returns:

The disapproval score of each alternative appearing in at least one ballot. Alternatives never disapproved in any ballot will be absent, but accessing them returns 0.

Return type:

collections.defaultdict[Alternative, int]

multiplicity(ballot: FrozenTrichotomousBallot) int[source]#

Returns the multiplicity of a given ballot in the profile.

Parameters:

ballot (FrozenTrichotomousBallot) – The ballot whose multiplicity is requested.

Returns:

The number of times the ballot appears in the profile.

Return type:

int

num_ballots() int[source]#

Returns the number of ballots in the profile.

Returns:

The multiplicity of the ballots.

Return type:

int

support(alternative: Alternative) int[source]#

Returns the support of an alternative, i.e., the net number of voters supporting it (the number of approvers minus the number of disapprovers).

Parameters:

alternative (Alternative) – The alternative to consider.

Returns:

The support of the alternative.

Return type:

int

support_dict() defaultdict[Alternative, int][source]#

Returns the support of the alternatives of the instance as a dictionary.

Returns:

The support of each alternative appearing in at least one ballot. Alternatives never appearing (approved or disapproved) in any ballot will be absent, but accessing them returns 0.

Return type:

collections.defaultdict[Alternative, int]

total()[source]#

Computes the total number of ballots in the profile, counting multiplicities.

Returns:

Total number of ballots.

Return type:

int

update([E, ]**F) None.  Update D from mapping/iterable E and F.[source]#

If E present and has a .keys() method, does: for k in E: D[k] = E[k] If E present and lacks .keys() method, does: for (k, v) in E: D[k] = v In either case, this is followed by: for k, v in F.items(): D[k] = v

Link to abcvoting#

Module to bridge this package and the abcvoting package.

This module defines functions to convert profiles from this package to the abcvoting package, allowing to parse preference files generated by the abcvoting package.

abcvoting_to_trichotomous_profile(abc_profile: Profile) TrichotomousProfile[source]#

Converts a profile from the abcvoting library into a trichotomous profile.

Parameters:

abc_profile (Profile) – The input profile using abcvoting’s approval-based format.

Returns:

A trichotomous profile where each ballot has only approved alternatives and the rest are left unspecified.

Return type:

TrichotomousProfile

parse_abcvoting_yaml(file_path: str) TrichotomousProfile[source]#

Parses a YAML file formatted for the abcvoting library and returns the corresponding trichotomous profile.

Parameters:

file_path (str) – Path to the YAML file containing the approval-based voting profile.

Returns:

The parsed trichotomous profile including its maximum selection size.

Return type:

TrichotomousProfile

Link with Pabulib and pabutools#

parse_pabulib(file_path: str) TrichotomousProfile[source]#

Parses a PaBuLib file and returns the corresponding trichotomous profile.

Parameters:

file_path (str) – Path to the PaBuLib file to be parsed.

Returns:

The profile corresponding to the file.

Return type:

TrichotomousProfile

pb_approval_profile_to_trichotomous_profile(instance: Instance, app_profile: AbstractApprovalProfile) TrichotomousProfile[source]#

Converts a PaBuLib approval profile into a trichotomous profile.

Parameters:
  • instance (Instance) – The project instance from PaBuLib.

  • app_profile (AbstractApprovalProfile) – The approval profile from PaBuLib.

Returns:

A trichotomous profile with approved alternatives from the approval profile.

Return type:

TrichotomousProfile

pb_approval_ballot_to_trichotomous_ballot(app_ballot: AbstractApprovalBallot, alt_map: dict[Project, Alternative]) TrichotomousBallot[source]#

Converts an approval ballot from a PaBuLib profile into a trichotomous ballot.

Parameters:
  • app_ballot (AbstractApprovalBallot) – A ballot where projects are approved in a PaBuLib approval profile.

  • alt_map (dict[Project, Alternative]) – A mapping from PaBuLib projects to Trivoting alternatives.

Returns:

A trichotomous ballot with approved alternatives (no disapprovals).

Return type:

TrichotomousBallot

Link with PrefLib#

parse_preflib(file_path: str) TrichotomousProfile[source]#

Parses a PrefLib file and returns the corresponding trichotomous profile.

The file is parsed using preflibtools.get_parsed_instance, and only categorical instances with 1–3 categories are supported.

Parameters:

file_path (str) – The file path to a PrefLib categorical instance.

Returns:

A trichotomous profile built from the given file.

Return type:

TrichotomousProfile

cat_instance_to_trichotomous_profile(cat_instance: CategoricalInstance) TrichotomousProfile[source]#

Converts a PrefLib CategoricalInstance into a trichotomous profile. The PrefLib instance should have 1, 2 or 3 categories. If there is a single categories, it is assumed to represent the approved alternatives. If there are 2 categories, it is assumed that they represent the approved and neutral alternatives. In case of 3 categories, the categories are assumed to represent approved, neutral and disapproved alternatives, in that order.

Each ballot in the categorical instance is converted using cat_preferences_to_trichotomous_ballot.

Parameters:

cat_instance (CategoricalInstance) – A parsed categorical instance from PrefLib.

Returns:

A profile composed of trichotomous ballots.

Return type:

TrichotomousProfile

cat_preferences_to_trichotomous_ballot(pref: tuple[tuple[int]], alt_map: dict[int, Alternative]) TrichotomousBallot[source]#

Converts a categorical preference from PrefLib into a trichotomous ballot.

The first category in the preference is treated as the set of approved alternatives. If a second category is present, it is treated as neutral and ignored in the ballot. If a third category is present, it is treated as the set of disapproved alternatives.

Parameters:
  • pref (tuple[tuple[int]]) – The categorical preferences, typically a tuple of up to 3 ranked groups of alternative IDs.

  • alt_map (dict[int, Alternative]) – A mapping from PrefLib integer IDs to Alternative objects.

Returns:

The corresponding trichotomous ballot.

Return type:

TrichotomousBallot

Raises:

ValueError – If the number of categories is not between 1 and 3.

Generate Random Profile#

generate_random_ballot(alternatives: list[Alternative], approved_disapproved_sampler: Callable, approved_sampler: Callable, disapproved_sampler: Callable) TrichotomousBallot[source]#

Generates a random trichotomous ballot based on the given sampling functions. Sampling functions are expected to behave as the ones from the prefsampling package.

First samples a set of potentially approved alternatives. The set of the potentially disapproved alternatives is the complement of the former. For both of these sets, an extra sampling function is applied to determine the definitively approved and disapproved alternatives.

Parameters:
  • alternatives (list of Alternative) – List of alternatives available in the election.

  • approved_disapproved_sampler (Callable) – Function that samples a split between potentially approved and disapproved alternatives. It should take num_voters and num_candidates as keyword arguments and return a list of index sets.

  • approved_sampler (Callable) – Function that samples which of the potentially approved alternatives are definitively approved. Same interface as approve_disapproved_sampler.

  • disapproved_sampler (Callable) – Function that samples which of the potentially disapproved alternatives are definitively disapproved. Same interface as approve_disapproved_sampler.

Returns:

A randomly generated trichotomous ballot.

Return type:

TrichotomousBallot

generate_random_profile(num_alternatives: int, num_voters: int, approved_disapproved_sampler: Callable, approved_sampler: Callable, disapproved_sampler: Callable) TrichotomousProfile[source]#

Generates a random trichotomous profile composed of several ballots. Uses the function generate_random_ballot to generate the ballots.

Parameters:
  • num_alternatives (int) – The number of alternatives in the profile.

  • num_voters (int) – The number of voters (ballots) in the profile.

  • approved_disapproved_sampler (Callable) – Function that samples a split between potentially approved and disapproved alternatives. It should take num_voters and num_candidates as keyword arguments and return a list of index sets.

  • approved_sampler (Callable) – Function that samples which of the potentially approved alternatives are definitively approved. Same interface as approve_disapproved_sampler.

  • disapproved_sampler (Callable) – Function that samples which of the potentially disapproved alternatives are definitively disapproved. Same interface as approve_disapproved_sampler.

Returns:

A profile containing randomly generated trichotomous ballots.

Return type:

TrichotomousProfile

Selection#

class Selection(selected: Iterable[Alternative] = None, rejected: Iterable[Alternative] = None, implicit_reject: bool = True)[source]#

Bases: object

A selection is the outcome of a rule. It contains both the alternatives that have been selected and the ones that have been rejected.

Parameters:
  • selected (Iterable[Alternative], optional) – A collection of alternatives that are selected. Defaults to an empty list.

  • rejected (Iterable[Alternative], optional) – A collection of alternatives that are explicitly rejected. Defaults to an empty list.

  • implicit_reject (bool, optional) – If True, all alternatives not in selected are considered rejected by default. If False, only alternatives in rejected are considered rejected. Defaults to True.

selected#

Alternatives that are selected.

Type:

list of Alternative

rejected#

Alternatives that are rejected.

Type:

list of Alternative

implicit_reject#

Whether rejection is implicit for alternatives not in the selection.

Type:

bool

add_rejected(alt: Alternative) None[source]#

Add a single alternative to the rejected list. Issues a warning if implicit_reject is set to True.

Parameters:

alt (Alternative) – The alternative to add to the rejection list.

add_selected(alt: Alternative) None[source]#

Add a single alternative to the selected list.

Parameters:

alt (Alternative) – The alternative to add to the selection.

copy() Selection[source]#

Create a copy of the current selection.

Returns:

A deep copy of the current selection object.

Return type:

Selection

extend_rejected(alts: Iterable[Alternative]) None[source]#

Extend the rejected list with multiple alternatives. Issues a warning if implicit_reject is set to True.

Parameters:

alts (Iterable[Alternative]) – An iterable of alternatives to add to the rejection list.

extend_selected(alts: Iterable[Alternative]) None[source]#

Extend the selected list with multiple alternatives.

Parameters:

alts (Iterable[Alternative]) – An iterable of alternatives to add to the selection.

is_rejected(a: Alternative) bool[source]#

Check whether an alternative is considered rejected. If implicit_reject is set to True, checks that the alternative is not selected. Otherwise, checks that the alternative is rejected.

Parameters:

a (Alternative) – The alternative to check.

Returns:

True if the alternative is selected; False otherwise.

Return type:

bool

is_selected(a: Alternative) bool[source]#

Check whether an alternative is considered selected. Same as a in selection.selected.

Parameters:

a (Alternative) – The alternative to check.

Returns:

True if the alternative is selected; False otherwise.

Return type:

bool

sort() None[source]#

Sort both selected and rejected alternatives in place.

total_len() int[source]#

Get the total number of alternatives (selected and rejected).

Returns:

Total count of selected and rejected alternatives.

Return type:

int