OpenTally/src/election.rs

480 lines
16 KiB
Rust
Raw Normal View History

2021-05-28 11:58:40 +02:00
/* OpenTally: Open-source election vote counting
* Copyright © 2021 Lee Yingtong Li (RunasSudo)
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
use crate::constraints::{Constraints, ConstraintMatrix};
use crate::logger::Logger;
2021-05-28 11:58:40 +02:00
use crate::numbers::Number;
2021-06-12 19:15:15 +02:00
use crate::sharandom::SHARandom;
use crate::stv::{QuotaMode, STVOptions};
2021-05-28 11:58:40 +02:00
2021-09-02 09:17:45 +02:00
#[cfg(not(target_arch = "wasm32"))]
use rkyv::{Archive, Archived, Deserialize, Fallible, Resolver, Serialize, with::{ArchiveWith, DeserializeWith, SerializeWith}};
use std::cmp::max;
2021-05-28 11:58:40 +02:00
use std::collections::HashMap;
2021-07-31 07:24:23 +02:00
2021-06-14 12:43:36 +02:00
/// An election to be counted
#[derive(Clone)]
2021-09-02 09:17:45 +02:00
#[cfg_attr(not(target_arch = "wasm32"), derive(Archive, Deserialize, Serialize))]
2021-05-28 11:58:40 +02:00
pub struct Election<N> {
2021-06-16 09:20:29 +02:00
/// Name of the election
pub name: String,
2021-06-16 09:20:29 +02:00
/// Number of candidates to be elected
2021-05-28 11:58:40 +02:00
pub seats: usize,
2021-06-16 09:20:29 +02:00
/// [Vec] of [Candidate]s in the election
2021-05-28 11:58:40 +02:00
pub candidates: Vec<Candidate>,
2021-06-16 09:20:29 +02:00
/// Indexes of withdrawn candidates
2021-06-11 16:50:01 +02:00
pub withdrawn_candidates: Vec<usize>,
2021-06-16 09:20:29 +02:00
/// [Vec] of [Ballot]s cast in the election
2021-05-28 11:58:40 +02:00
pub ballots: Vec<Ballot<N>>,
/// Constraints on candidates
pub constraints: Option<Constraints>,
2021-05-28 11:58:40 +02:00
}
impl<N: Number> Election<N> {
2021-06-14 12:43:36 +02:00
/// Convert ballots with weight >1 to multiple ballots of weight 1
2021-09-03 15:53:15 +02:00
///
/// Assumes ballots have integer weight.
pub fn normalise_ballots(&mut self) {
let mut normalised_ballots = Vec::new();
for ballot in self.ballots.iter() {
let mut n = N::new();
let one = N::one();
while n < ballot.orig_value {
let new_ballot = Ballot {
orig_value: N::one(),
preferences: ballot.preferences.clone(),
};
normalised_ballots.push(new_ballot);
n += &one;
}
}
self.ballots = normalised_ballots;
}
2021-09-03 15:53:15 +02:00
/// Convert ballots with equal rankings to strict-preference "minivoters"
pub fn realise_equal_rankings(&mut self) {
let mut realised_ballots = Vec::new();
for ballot in self.ballots.iter() {
let mut b = ballot.realise_equal_rankings();
realised_ballots.append(&mut b);
}
self.ballots = realised_ballots;
}
2021-05-28 11:58:40 +02:00
}
2021-06-14 12:43:36 +02:00
/// A candidate in an [Election]
#[derive(Clone, Eq, Hash, PartialEq)]
2021-09-02 09:17:45 +02:00
#[cfg_attr(not(target_arch = "wasm32"), derive(Archive, Deserialize, Serialize))]
2021-05-28 11:58:40 +02:00
pub struct Candidate {
2021-06-16 09:20:29 +02:00
/// Name of the candidate
2021-05-28 11:58:40 +02:00
pub name: String,
}
2021-06-14 12:43:36 +02:00
/// The current state of counting an [Election]
2021-06-16 05:00:54 +02:00
pub struct CountState<'a, N: Number> {
2021-06-16 09:20:29 +02:00
/// Pointer to the [Election] being counted
2021-05-28 11:58:40 +02:00
pub election: &'a Election<N>,
2021-06-16 09:20:29 +02:00
/// [HashMap] of [CountCard]s for each [Candidate] in the election
2021-05-28 11:58:40 +02:00
pub candidates: HashMap<&'a Candidate, CountCard<'a, N>>,
2021-06-16 09:20:29 +02:00
/// [CountCard] representing the exhausted pile
2021-05-28 11:58:40 +02:00
pub exhausted: CountCard<'a, N>,
2021-06-16 09:20:29 +02:00
/// [CountCard] representing loss by fraction
pub loss_fraction: CountCard<'a, N>,
2021-05-28 11:58:40 +02:00
2021-06-16 09:20:29 +02:00
/// [crate::stv::meek::BallotTree] for Meek STV
2021-06-16 05:00:54 +02:00
pub ballot_tree: Option<crate::stv::meek::BallotTree<'a, N>>,
2021-06-16 09:20:29 +02:00
/// Values used to break ties, based on forwards tie-breaking
pub forwards_tiebreak: Option<HashMap<&'a Candidate, usize>>,
2021-06-16 09:20:29 +02:00
/// Values used to break ties, based on backwards tie-breaking
pub backwards_tiebreak: Option<HashMap<&'a Candidate, usize>>,
2021-06-16 09:20:29 +02:00
/// [SHARandom] for random tie-breaking
2021-06-12 19:15:15 +02:00
pub random: Option<SHARandom<'a>>,
2021-06-16 09:20:29 +02:00
/// Quota for election
2021-06-07 12:52:18 +02:00
pub quota: Option<N>,
2021-06-16 09:20:29 +02:00
/// Vote required for election
///
/// Only used in ERS97/ERS76.
2021-06-07 12:52:18 +02:00
pub vote_required_election: Option<N>,
2021-05-28 11:58:40 +02:00
2021-06-16 09:20:29 +02:00
/// Number of candidates who have been declared elected
2021-05-28 11:58:40 +02:00
pub num_elected: usize,
2021-06-16 09:20:29 +02:00
/// Number of candidates who have been declared excluded
2021-05-28 11:58:40 +02:00
pub num_excluded: usize,
2021-05-28 17:22:46 +02:00
/// [ConstraintMatrix] for constrained elections
pub constraint_matrix: Option<ConstraintMatrix>,
2021-06-16 09:20:29 +02:00
/// The type of stage being counted
///
/// For example, "Surplus of", "Exclusion of"
2021-05-28 17:22:46 +02:00
pub kind: Option<&'a str>,
2021-06-16 09:20:29 +02:00
/// The description of the stage being counted, excluding [CountState::kind]
2021-05-28 17:22:46 +02:00
pub title: String,
2021-06-16 09:20:29 +02:00
/// [Logger] for this stage of the count
pub logger: Logger<'a>,
2021-05-28 11:58:40 +02:00
}
impl<'a, N: Number> CountState<'a, N> {
2021-06-14 12:43:36 +02:00
/// Construct a new blank [CountState] for the given [Election]
2021-05-28 11:58:40 +02:00
pub fn new(election: &'a Election<N>) -> Self {
let mut state = CountState {
election: &election,
candidates: HashMap::new(),
exhausted: CountCard::new(),
loss_fraction: CountCard::new(),
2021-06-16 05:00:54 +02:00
ballot_tree: None,
forwards_tiebreak: None,
backwards_tiebreak: None,
2021-06-12 19:15:15 +02:00
random: None,
2021-06-07 12:52:18 +02:00
quota: None,
vote_required_election: None,
2021-05-28 11:58:40 +02:00
num_elected: 0,
num_excluded: 0,
constraint_matrix: None,
2021-05-28 17:22:46 +02:00
kind: None,
title: String::new(),
logger: Logger { entries: Vec::new() },
2021-05-28 11:58:40 +02:00
};
for candidate in election.candidates.iter() {
state.candidates.insert(candidate, CountCard::new());
}
2021-06-11 16:50:01 +02:00
for withdrawn_idx in election.withdrawn_candidates.iter() {
state.candidates.get_mut(&election.candidates[*withdrawn_idx]).unwrap().state = CandidateState::Withdrawn;
}
if let Some(constraints) = &election.constraints {
let mut num_groups: Vec<usize> = constraints.0.iter().map(|c| c.groups.len()).collect();
let mut cm = ConstraintMatrix::new(&mut num_groups[..]);
// Init constraint matrix total cells min/max
for (i, constraint) in constraints.0.iter().enumerate() {
for (j, group) in constraint.groups.iter().enumerate() {
let mut idx = vec![0; constraints.0.len()];
idx[i] = j + 1;
let mut cell = &mut cm[&idx];
cell.min = group.min;
cell.max = group.max;
}
}
// Fill in grand total, etc.
cm.update_from_state(&state.election, &state.candidates);
cm.init();
//println!("{}", cm);
// Require correct number of candidates to be elected
let idx = vec![0; constraints.0.len()];
cm[&idx].min = election.seats;
cm[&idx].max = election.seats;
state.constraint_matrix = Some(cm);
}
2021-05-28 11:58:40 +02:00
return state;
}
2021-06-14 12:43:36 +02:00
/// [Step](CountCard::step) every [CountCard] to prepare for the next stage
2021-05-28 11:58:40 +02:00
pub fn step_all(&mut self) {
for (_, count_card) in self.candidates.iter_mut() {
count_card.step();
}
self.exhausted.step();
self.loss_fraction.step();
2021-05-28 11:58:40 +02:00
}
/// List the candidates, and their current state, votes and transfers
pub fn describe_candidates(&self, opts: &STVOptions) -> String {
let mut candidates: Vec<(&Candidate, &CountCard<N>)>;
if opts.sort_votes {
// Sort by votes if requested
candidates = self.candidates.iter()
.map(|(c, cc)| (*c, cc)).collect();
// First sort by order of election (as a tie-breaker, if votes are equal)
candidates.sort_unstable_by(|a, b| b.1.order_elected.cmp(&a.1.order_elected));
// Then sort by votes
candidates.sort_by(|a, b| a.1.votes.cmp(&b.1.votes));
candidates.reverse();
} else {
candidates = self.election.candidates.iter()
.map(|c| (c, &self.candidates[c]))
.collect();
}
let mut result = String::new();
for (candidate, count_card) in candidates {
match count_card.state {
CandidateState::Hopeful => {
result.push_str(&format!("- {}: {:.dps$} ({:.dps$})\n", candidate.name, count_card.votes, count_card.transfers, dps=opts.pp_decimals));
}
CandidateState::Guarded => {
result.push_str(&format!("- {}: {:.dps$} ({:.dps$}) - Guarded\n", candidate.name, count_card.votes, count_card.transfers, dps=opts.pp_decimals));
}
CandidateState::Elected => {
if let Some(kv) = &count_card.keep_value {
result.push_str(&format!("- {}: {:.dps$} ({:.dps$}) - ELECTED {} (kv = {:.dps2$})\n", candidate.name, count_card.votes, count_card.transfers, count_card.order_elected, kv, dps=opts.pp_decimals, dps2=max(opts.pp_decimals, 2)));
} else {
result.push_str(&format!("- {}: {:.dps$} ({:.dps$}) - ELECTED {}\n", candidate.name, count_card.votes, count_card.transfers, count_card.order_elected, dps=opts.pp_decimals));
}
}
CandidateState::Doomed => {
result.push_str(&format!("- {}: {:.dps$} ({:.dps$}) - Doomed\n", candidate.name, count_card.votes, count_card.transfers, dps=opts.pp_decimals));
}
CandidateState::Withdrawn => {
if !opts.hide_excluded || !count_card.votes.is_zero() || !count_card.transfers.is_zero() {
result.push_str(&format!("- {}: {:.dps$} ({:.dps$}) - Withdrawn\n", candidate.name, count_card.votes, count_card.transfers, dps=opts.pp_decimals));
}
}
CandidateState::Excluded => {
// If --hide-excluded, hide unless nonzero votes or nonzero transfers
if !opts.hide_excluded || !count_card.votes.is_zero() || !count_card.transfers.is_zero() {
result.push_str(&format!("- {}: {:.dps$} ({:.dps$}) - Excluded {}\n", candidate.name, count_card.votes, count_card.transfers, -count_card.order_elected, dps=opts.pp_decimals));
}
}
}
}
return result;
}
/// Produce summary rows for the current stage
pub fn describe_summary(&self, opts: &STVOptions) -> String {
let mut result = String::new();
result.push_str(&format!("Exhausted: {:.dps$} ({:.dps$})\n", self.exhausted.votes, self.exhausted.transfers, dps=opts.pp_decimals));
result.push_str(&format!("Loss by fraction: {:.dps$} ({:.dps$})\n", self.loss_fraction.votes, self.loss_fraction.transfers, dps=opts.pp_decimals));
let mut total_vote = self.candidates.values().fold(N::zero(), |acc, cc| { acc + &cc.votes });
total_vote += &self.exhausted.votes;
total_vote += &self.loss_fraction.votes;
result.push_str(&format!("Total votes: {:.dps$}\n", total_vote, dps=opts.pp_decimals));
result.push_str(&format!("Quota: {:.dps$}\n", self.quota.as_ref().unwrap(), dps=opts.pp_decimals));
if opts.quota_mode == QuotaMode::ERS97 || opts.quota_mode == QuotaMode::ERS76 {
result.push_str(&format!("Vote required for election: {:.dps$}\n", self.vote_required_election.as_ref().unwrap(), dps=opts.pp_decimals));
}
return result;
}
2021-05-28 11:58:40 +02:00
}
2021-06-14 12:43:36 +02:00
/// Current state of a [Candidate] during an election count
2021-05-28 11:58:40 +02:00
#[derive(Clone)]
pub struct CountCard<'a, N> {
2021-06-16 09:20:29 +02:00
/// State of the candidate
2021-05-28 11:58:40 +02:00
pub state: CandidateState,
2021-06-16 09:20:29 +02:00
/// Order of election or exclusion
///
/// Positive integers represent order of election; negative integers represent order of exclusion.
2021-05-28 11:58:40 +02:00
pub order_elected: isize,
/// Whether distribution of this candidate's surpluses/transfer of excluded candidate's votes is complete
pub finalised: bool,
2021-05-28 11:58:40 +02:00
2021-06-16 09:20:29 +02:00
/// Net votes transferred to this candidate in this stage
2021-05-28 11:58:40 +02:00
pub transfers: N,
2021-06-16 09:20:29 +02:00
/// Votes of the candidate at the end of this stage
2021-05-28 11:58:40 +02:00
pub votes: N,
2021-08-16 10:48:49 +02:00
/// Net ballots transferred to this candidate in this stage
pub ballot_transfers: N,
2021-06-16 09:20:29 +02:00
/// Parcels of ballots assigned to this candidate
2021-05-28 11:58:40 +02:00
pub parcels: Vec<Parcel<'a, N>>,
2021-06-16 05:00:54 +02:00
/// Candidate's keep value (Meek STV)
pub keep_value: Option<N>,
2021-05-28 11:58:40 +02:00
}
impl<'a, N: Number> CountCard<'a, N> {
2021-06-14 12:43:36 +02:00
/// Returns a new blank [CountCard]
2021-05-28 11:58:40 +02:00
pub fn new() -> Self {
return CountCard {
2021-06-11 16:50:01 +02:00
state: CandidateState::Hopeful,
2021-05-28 11:58:40 +02:00
order_elected: 0,
finalised: false,
2021-05-28 11:58:40 +02:00
transfers: N::new(),
votes: N::new(),
2021-08-16 10:48:49 +02:00
ballot_transfers: N::new(),
2021-05-28 11:58:40 +02:00
parcels: Vec::new(),
2021-06-16 05:00:54 +02:00
keep_value: None,
2021-05-28 11:58:40 +02:00
};
}
2021-06-14 12:43:36 +02:00
/// Transfer the given number of votes to this [CountCard], incrementing [transfers](CountCard::transfers) and [votes](CountCard::votes)
2021-05-28 11:58:40 +02:00
pub fn transfer(&mut self, transfer: &'_ N) {
self.transfers += transfer;
self.votes += transfer;
}
2021-06-16 05:00:54 +02:00
/// Set [transfers](CountCard::transfers) to 0
2021-05-28 11:58:40 +02:00
pub fn step(&mut self) {
self.transfers = N::new();
2021-08-16 10:48:49 +02:00
self.ballot_transfers = N::new();
2021-05-28 11:58:40 +02:00
}
2021-07-19 15:15:17 +02:00
/// Concatenate all parcels into a single parcel, leaving [parcels](CountCard::parcels) empty
pub fn concat_parcels(&mut self) -> Vec<Vote<'a, N>> {
let mut result = Vec::new();
for parcel in self.parcels.iter_mut() {
result.append(&mut parcel.votes);
}
return result;
}
2021-08-16 10:48:49 +02:00
/// Return the number of ballots across all parcels
pub fn num_ballots(&self) -> N {
return self.parcels.iter().fold(N::new(), |acc, p| acc + p.num_ballots());
}
2021-05-28 11:58:40 +02:00
}
2021-06-14 12:43:36 +02:00
/// Parcel of [Vote]s during a count
2021-07-19 15:15:17 +02:00
#[derive(Clone)]
pub struct Parcel<'a, N> {
/// [Vote]s in this parcel
pub votes: Vec<Vote<'a, N>>,
/// Accumulated relative value of each [Vote] in this parcel
pub value_fraction: N,
/// Order for sorting with [crate::stv::ExclusionMethod::BySource]
2021-07-19 15:15:17 +02:00
pub source_order: usize,
}
2021-05-28 11:58:40 +02:00
impl<'a, N: Number> Parcel<'a, N> {
/// Return the number of ballots in this parcel
pub fn num_ballots(&self) -> N {
return self.votes.iter().fold(N::new(), |acc, v| acc + &v.ballot.orig_value);
}
/// Return the value of the votes in this parcel
pub fn num_votes(&self) -> N {
return self.num_ballots() * &self.value_fraction;
}
}
2021-06-14 12:43:36 +02:00
/// Represents a [Ballot] with an associated value
2021-05-28 11:58:40 +02:00
#[derive(Clone)]
pub struct Vote<'a, N> {
2021-06-16 09:20:29 +02:00
/// Ballot from which the vote is derived
2021-05-28 11:58:40 +02:00
pub ballot: &'a Ballot<N>,
2021-06-16 05:00:54 +02:00
/// Index of the next preference to examine
2021-05-28 11:58:40 +02:00
pub up_to_pref: usize,
}
2021-09-03 15:53:15 +02:00
impl<'a, N> Vote<'a, N> {
/// Get the next preference and increment `up_to_pref`
///
/// Assumes that each preference level contains only one preference.
pub fn next_preference(&mut self) -> Option<usize> {
if self.up_to_pref >= self.ballot.preferences.len() {
return None;
}
let preference = &self.ballot.preferences[self.up_to_pref];
self.up_to_pref += 1;
return Some(*preference.first().unwrap());
}
}
2021-06-14 12:43:36 +02:00
/// A record of a voter's preferences
#[derive(Clone)]
2021-09-02 09:17:45 +02:00
#[cfg_attr(not(target_arch = "wasm32"), derive(Archive, Deserialize, Serialize))]
2021-05-28 11:58:40 +02:00
pub struct Ballot<N> {
2021-06-16 09:20:29 +02:00
/// Original value/weight of the ballot
2021-09-02 09:17:45 +02:00
#[cfg_attr(not(target_arch = "wasm32"), with(SerializedNum))]
2021-05-28 11:58:40 +02:00
pub orig_value: N,
2021-09-03 15:53:15 +02:00
/// Indexes of candidates preferenced at each level on the ballot
pub preferences: Vec<Vec<usize>>,
}
impl<N: Number> Ballot<N> {
/// Convert ballot with equal rankings to strict-preference "minivoters"
pub fn realise_equal_rankings(&self) -> Vec<Ballot<N>> {
// Preferences for each minivoter
let mut minivoters = vec![Vec::new()];
for preference in self.preferences.iter() {
if preference.len() == 1 {
for minivoter in minivoters.iter_mut() {
minivoter.push(preference.clone());
}
} else {
todo!();
}
}
let weight_each = self.orig_value.clone() / N::from(minivoters.len());
let ballots = minivoters.into_iter()
.map(|p| Ballot { orig_value: weight_each.clone(), preferences: p })
.collect();
return ballots;
}
2021-05-28 11:58:40 +02:00
}
2021-09-02 09:17:45 +02:00
/// rkyv-serialized representation of [Number]
#[cfg(not(target_arch = "wasm32"))]
pub struct SerializedNum;
#[cfg(not(target_arch = "wasm32"))]
impl<N: Number> ArchiveWith<N> for SerializedNum {
type Archived = Archived<String>;
type Resolver = Resolver<String>;
unsafe fn resolve_with(field: &N, pos: usize, resolver: Self::Resolver, out: *mut Self::Archived) {
field.to_string().resolve(pos, resolver, out);
}
}
#[cfg(not(target_arch = "wasm32"))]
impl<N: Number, S: Fallible + ?Sized> SerializeWith<N, S> for SerializedNum where String: Serialize<S> {
fn serialize_with(field: &N, serializer: &mut S) -> Result<Self::Resolver, S::Error> {
return field.to_string().serialize(serializer);
}
}
#[cfg(not(target_arch = "wasm32"))]
impl<N: Number, D: Fallible + ?Sized> DeserializeWith<Archived<String>, N, D> for SerializedNum where Archived<String>: Deserialize<String, D> {
fn deserialize_with(field: &Archived<String>, deserializer: &mut D) -> Result<N, D::Error> {
return Ok(N::parse(&field.deserialize(deserializer)?));
}
}
2021-06-14 12:43:36 +02:00
/// State of a [Candidate] during a count
2021-05-28 11:58:40 +02:00
#[allow(dead_code)]
#[derive(PartialEq)]
#[derive(Clone)]
#[derive(Debug)]
2021-05-28 11:58:40 +02:00
pub enum CandidateState {
2021-06-16 09:20:29 +02:00
/// Hopeful (continuing candidate)
2021-06-11 16:50:01 +02:00
Hopeful,
2021-06-16 09:20:29 +02:00
/// Required by constraints to be guarded from exclusion
2021-06-11 16:50:01 +02:00
Guarded,
2021-06-16 09:20:29 +02:00
/// Declared elected
2021-06-11 16:50:01 +02:00
Elected,
2021-06-16 09:20:29 +02:00
/// Required by constraints to be doomed to be excluded
2021-06-11 16:50:01 +02:00
Doomed,
2021-06-16 09:20:29 +02:00
/// Withdrawn candidate
2021-06-11 16:50:01 +02:00
Withdrawn,
2021-06-16 09:20:29 +02:00
/// Declared excluded
2021-06-11 16:50:01 +02:00
Excluded,
2021-05-28 11:58:40 +02:00
}