From 2ed45725a48b6b793a89766264097cab8e21dae2 Mon Sep 17 00:00:00 2001 From: Chris McComb Date: Sat, 19 Sep 2026 14:18:23 -0400 Subject: [PATCH] Release vote 0.3.0 with pairwise and instant-runoff methods --- .github/workflows/tests.yml | 1 + CHANGELOG.md | 12 ++ Cargo.toml | 2 +- README.md | 107 +++++++++- examples/compare_methods.rs | 43 ++++ src/lib.rs | 4 + src/pairwise.rs | 122 +++++++++++ src/results.rs | 6 +- src/runoff.rs | 172 ++++++++++++++++ tests/methods.rs | 400 ++++++++++++++++++++++++++++++++++++ 10 files changed, 860 insertions(+), 9 deletions(-) create mode 100644 examples/compare_methods.rs create mode 100644 src/pairwise.rs create mode 100644 src/runoff.rs create mode 100644 tests/methods.rs diff --git a/.github/workflows/tests.yml b/.github/workflows/tests.yml index 03a399c..1a95dcd 100644 --- a/.github/workflows/tests.yml +++ b/.github/workflows/tests.yml @@ -29,6 +29,7 @@ jobs: run: | cargo +stable run --example simple cargo +stable run --example seeded + cargo +stable run --example compare_methods quality: runs-on: ubuntu-latest diff --git a/CHANGELOG.md b/CHANGELOG.md index 22679b0..ae05096 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,17 @@ # Changelog +## 0.3.0 - 2026-09-19 + +- Add Copeland(0.5) with integer scores scaled by two and explicit tied groups. +- Expose pairwise comparison counts and strict Condorcet winner detection, + including reusable matrix methods to avoid recounting ballots. +- Add instant-runoff voting with per-round tallies, single-candidate + eliminations, and explicit unresolved elimination ties. A caller-supplied + comparator can resolve ties without changing candidates' unequal vote counts. +- Preserve the existing 0.2 API and its complete, strict ballot requirements. +- Add a methods-comparison example, README guidance, a published counting + fixture, and exhaustive pairwise/runoff checks over 1,554 small profiles. + ## 0.2.0 - 2026-09-19 - Validate profiles at construction with `Preference::new` and `TryFrom`, diff --git a/Cargo.toml b/Cargo.toml index 2da32dd..f3d657b 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "vote" -version = "0.2.0" +version = "0.3.0" authors = ["Chris McComb "] description = "Common voting methods" edition = "2021" diff --git a/README.md b/README.md index 69640d4..9e72f5e 100644 --- a/README.md +++ b/README.md @@ -4,9 +4,10 @@ # About -`vote` aggregates ranked preferences with plurality, Borda, and random dictatorship. -It validates complete ballots, reports scores and ties explicitly, and accepts a -caller-supplied random number generator for repeatable voting experiments. +`vote` aggregates ranked preferences with plurality, Borda, Copeland, +instant-runoff voting, and random dictatorship. It also provides pairwise +comparisons and strict Condorcet winner detection. It validates complete ballots, +reports scores and ties explicitly, and supports repeatable experiments. # Install @@ -14,7 +15,7 @@ Requires **Rust 1.85 or newer**. Add `vote` to your project's `Cargo.toml`: ```toml [dependencies] -vote = "0.2" +vote = "0.3" ``` # Usage @@ -58,10 +59,101 @@ Output: | `borda` | With `m` candidates, award `m - 1, ..., 0` points | Score groups, highest first | | `random_dictator` | Select a voter uniformly | A copy of that voter's ranked ballot | | `random_dictator_with_rng` | Same rule, using the caller's RNG | A copy of that voter's ranked ballot | +| `copeland` | Two points per pairwise win, one per tie, zero per loss | Score groups, highest first | +| `condorcet_winner` | Find a candidate who strictly defeats every opponent head-to-head | `Some(candidate)` or `None` | +| `pairwise` | Count voters preferring each candidate to each opponent | Labeled comparison matrix | +| `instant_runoff` | Transfer votes from one lowest candidate at a time until a strict majority | Winner or unresolved elimination tie, plus round trace | +| `instant_runoff_by` | Same count with a caller-supplied elimination tie-break rule | Winner or unresolved elimination tie, plus round trace | Each ballot represents one voter. Repeated identical ballots retain their multiplicity. Scores use `u128`, and candidates with zero points remain in the -results. Instant-runoff voting and Condorcet methods are not yet implemented. +results. All methods use the same validated complete ballots. Version 0.3 +preserves the existing 0.2 API. See `cargo run --example compare_methods` for a +full comparison. + +## Pairwise voting and Copeland + +`pairwise(&preferences)` returns candidates in first-ballot order and a square +matrix: entry `[i][j]` counts voters who prefer candidate `i` to candidate `j`. +Opposite off-diagonal counts sum to the voter count; diagonal entries are zero. +`preference_count(&candidate, &opponent)` provides lookup by candidate identity, +returning `None` for an unknown candidate. + +Copeland uses the common half-point tie convention, scaled by two to preserve +integer scores: win = 2, tie = 1, loss = 0. Equal final scores remain tied in +`Results`. A strict Condorcet winner always uniquely wins Copeland, but Copeland +can also return a unique winner when there is no strict Condorcet winner. +`condorcet_winner` returns `None` for cycles or other profiles without a candidate +who strictly beats every opponent. A sole candidate wins vacuously. + +```rust +use vote::{copeland, pairwise, Preference}; + +fn main() -> Result<(), vote::PreferenceError> { + // A three-way cycle: each candidate defeats one opponent and loses to another. + let preferences = Preference::new(vec![ + vec!["A", "B", "C"], + vec!["B", "C", "A"], + vec!["C", "A", "B"], + ])?; + let comparisons = pairwise(&preferences); + assert_eq!(comparisons.preference_count(&"A", &"B"), Some(2)); + assert_eq!(comparisons.condorcet_winner(), None); + assert_eq!(comparisons.copeland(), copeland(&preferences)); + assert_eq!(comparisons.copeland().winners(), &["A", "B", "C"]); + Ok(()) +} +``` + +Computing the matrix takes expected `O(voters * candidates²)` time and +`O(candidates²)` auxiliary space. Reuse its `copeland()` and `condorcet_winner()` +methods to compare outcomes without recounting ballots. + +## Instant-runoff voting + +Each round counts every voter's highest-ranked active candidate. A strict +majority, more than half of all ballots, elects the winner immediately. +Otherwise, one candidate with the fewest votes is eliminated and their ballots +transfer to the next active preference. Complete ballots do not become exhausted. + +The default `instant_runoff` stops at any elimination tie, including zero-vote +ties. `RunoffOutcome::EliminationTie` identifies candidates tied for elimination; +it does **not** declare them winners. The round tally's `winners()` are only that +round's leaders. Use the runoff result's `winner()` for the elected candidate. +`rounds()` exposes all tallies and eliminations, including the terminal round; +it does not assign an overall ranking to the unelected candidates. + +With `instant_runoff_by`, `Ordering::Less` favors the first candidate, matching +`Results::ranking_by`. Of candidates tied for the lowest count, the greatest +(least preferred) is eliminated. The comparator never overrides different vote +counts. If it leaves several candidates equally least preferred, the count still +stops with an explicit elimination tie. Only one candidate is removed per round. + +```rust +use vote::{instant_runoff, instant_runoff_by, Preference, RunoffOutcome}; + +fn main() -> Result<(), vote::PreferenceError> { + let preferences = Preference::new(vec![vec!["B", "A"], vec!["A", "B"]])?; + let unresolved = instant_runoff(&preferences); + assert_eq!(unresolved.winner(), None); + assert_eq!( + unresolved.outcome(), + &RunoffOutcome::EliminationTie(vec!["B", "A"]), + ); + + // Favor alphabetically earlier names; eliminate B in the tied first round. + let resolved = instant_runoff_by(&preferences, Ord::cmp); + assert_eq!(resolved.rounds()[0].eliminated, Some("B")); + assert_eq!(resolved.winner(), Some(&"A")); + Ok(()) +} +``` + +The counting rule follows the standard preferential transfer procedure described +by the [Australian Electoral Commission](https://www.aec.gov.au/voting/counting/hor_count.htm). +Tie resolution is explicitly caller-controlled; historical-count or +jurisdiction-specific tie rules are not applied automatically. The Copeland +scoring convention is [Copeland(0.5)](https://arxiv.org/abs/0711.4759). ## Ballot requirements @@ -171,12 +263,15 @@ cargo clippy --all-targets --all-features -- -D warnings RUSTDOCFLAGS="-D warnings" cargo doc --no-deps --all-features cargo run --example simple cargo run --example seeded +cargo run --example compare_methods ``` The README is also the crate-level documentation, so its Rust examples run as documentation tests. CI checks stable Rust on Linux, macOS, and Windows, plus Rust 1.85 on Linux. Tests include the malformed-ballot regressions and all 1,554 -complete profiles with three candidates and one to four voters. +complete profiles with three candidates and one to four voters. Pairwise and +runoff tests check that same exhaustive set, including independent reference +counts and full runoff traces, plus a published AEC transfer example. See the [published API documentation](https://docs.rs/vote), [examples](https://github.com/cmccomb/vote/tree/master/examples), and diff --git a/examples/compare_methods.rs b/examples/compare_methods.rs new file mode 100644 index 0000000..af5ed6a --- /dev/null +++ b/examples/compare_methods.rs @@ -0,0 +1,43 @@ +use vote::{borda, copeland, instant_runoff, instant_runoff_by, pairwise, plurality, Preference}; + +fn main() -> Result<(), vote::PreferenceError> { + let mut ballots = vec![vec!["A", "B", "C"]; 4]; + ballots.extend(vec![vec!["B", "C", "A"]; 3]); + ballots.extend(vec![vec!["C", "B", "A"]; 2]); + let preferences = Preference::new(ballots)?; + + println!("Plurality winners: {:?}", plurality(&preferences).winners()); + println!("Borda winners: {:?}", borda(&preferences).winners()); + println!("Copeland winners: {:?}", copeland(&preferences).winners()); + let comparisons = pairwise(&preferences); + println!("Pairwise row/column order: {:?}", comparisons.candidates()); + for row in comparisons.counts() { + println!("{row:?}"); + } + println!( + "Strict Condorcet winner: {:?}", + comparisons.condorcet_winner() + ); + + let runoff = instant_runoff(&preferences); + for (index, round) in runoff.rounds().iter().enumerate() { + println!( + "Round {}: {:?}; eliminate {:?}", + index + 1, + round.tallies.groups(), + round.eliminated + ); + } + println!("Runoff outcome: {:?}", runoff.outcome()); + assert_eq!(runoff.winner(), Some(&"B")); + + let tied = Preference::new(vec![vec!["B", "A"], vec!["A", "B"]])?; + println!("Unresolved runoff: {:?}", instant_runoff(&tied).outcome()); + let resolved = instant_runoff_by(&tied, Ord::cmp); + println!( + "Favoring alphabetically earlier names: {:?}", + resolved.outcome() + ); + assert_eq!(resolved.winner(), Some(&"A")); + Ok(()) +} diff --git a/src/lib.rs b/src/lib.rs index 8c898ac..6ae5a75 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -2,11 +2,15 @@ #![warn(missing_docs)] #![forbid(unsafe_code)] +mod pairwise; mod preference; mod results; +mod runoff; +pub use pairwise::{condorcet_winner, copeland, pairwise, PairwiseResults}; pub use preference::{Preference, PreferenceError}; pub use results::{Results, ScoreGroup}; +pub use runoff::{instant_runoff, instant_runoff_by, RunoffOutcome, RunoffResults, RunoffRound}; use rand::{Rng, RngExt}; use std::collections::HashMap; diff --git a/src/pairwise.rs b/src/pairwise.rs new file mode 100644 index 0000000..eb81f02 --- /dev/null +++ b/src/pairwise.rs @@ -0,0 +1,122 @@ +use crate::{candidate_indices, Preference, Results}; +use std::cmp::Ordering; +use std::hash::Hash; + +/// Head-to-head preference counts, with candidates in first-ballot order. +/// +/// Entry `[i][j]` counts voters who rank candidate `i` ahead of candidate `j`. +/// The diagonal is zero; opposite off-diagonal entries sum to the voter count. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct PairwiseResults { + candidates: Vec, + counts: Vec>, +} + +impl PairwiseResults { + /// Candidates indexing both the rows and columns of [`Self::counts`]. + pub fn candidates(&self) -> &[T] { + &self.candidates + } + + /// Borrow the square matrix of head-to-head voter counts. + pub fn counts(&self) -> &[Vec] { + &self.counts + } + + /// Return the candidate who strictly defeats every other candidate, if any. + /// + /// Pairwise ties do not count as victories. Cycles or tied contests may + /// leave no strict Condorcet winner. A single candidate wins vacuously. + pub fn condorcet_winner(&self) -> Option<&T> { + (0..self.candidates.len()) + .find(|&candidate| { + (0..self.candidates.len()).all(|opponent| { + candidate == opponent + || self.counts[candidate][opponent] > self.counts[opponent][candidate] + }) + }) + .map(|index| &self.candidates[index]) + } +} + +impl PairwiseResults { + /// Count voters preferring `preferred` to `other`. + /// + /// Returns `None` if either candidate is unknown and `Some(0)` for a known + /// candidate compared with itself. Lookup takes linear time in the number + /// of candidates; use [`Self::counts`] for repeated indexed comparisons. + pub fn preference_count(&self, preferred: &T, other: &T) -> Option { + let row = self + .candidates + .iter() + .position(|candidate| candidate == preferred)?; + let column = self + .candidates + .iter() + .position(|candidate| candidate == other)?; + Some(self.counts[row][column]) + } +} + +impl PairwiseResults { + /// Score Copeland's method from these counts without recounting ballots. + /// + /// Uses Copeland(0.5), scaled by two to keep scores integral: two points + /// per pairwise win, one per pairwise tie, zero per loss. Equal final scores + /// remain grouped. A strict Condorcet winner, when present, uniquely wins. + pub fn copeland(&self) -> Results { + let mut scores = vec![0; self.candidates.len()]; + for first in 0..self.candidates.len() { + for second in first + 1..self.candidates.len() { + match self.counts[first][second].cmp(&self.counts[second][first]) { + Ordering::Greater => scores[first] += 2, + Ordering::Less => scores[second] += 2, + Ordering::Equal => { + scores[first] += 1; + scores[second] += 1; + } + } + } + } + Results::from_scores(&self.candidates, scores) + } +} + +/// Count every pairwise preference in a validated profile. +/// +/// Takes expected `O(voters * candidates^2)` time and `O(candidates^2)` auxiliary +/// space. Ballots are complete and strict, so every voter contributes to exactly +/// one side of each contest. Repeated ballots keep their multiplicity. +pub fn pairwise(pref: &Preference) -> PairwiseResults { + let indices = candidate_indices(pref); + let mut counts = vec![vec![0; pref.candidate_count()]; pref.candidate_count()]; + for ballot in pref.ballots() { + for (rank, candidate) in ballot.iter().enumerate() { + let row = indices[candidate]; + for other in &ballot[rank + 1..] { + counts[row][indices[other]] += 1; + } + } + } + PairwiseResults { + candidates: pref.candidates().to_vec(), + counts, + } +} + +/// Score Copeland(0.5): two points per pairwise win, one per tie, zero per loss. +/// +/// This doubles the usual one-point/half-point scoring convention without +/// changing winners or ties. Use [`pairwise`] to inspect or reuse the counts. +pub fn copeland(pref: &Preference) -> Results { + pairwise(pref).copeland() +} + +/// Copy the strict Condorcet winner, if one candidate beats every other head-to-head. +/// +/// Returns `None` when no candidate strictly defeats all opponents. Use +/// [`copeland`] for a scored outcome even when there is no Condorcet winner, +/// or [`pairwise`] to inspect the individual contests. +pub fn condorcet_winner(pref: &Preference) -> Option { + pairwise(pref).condorcet_winner().cloned() +} diff --git a/src/results.rs b/src/results.rs index 76e2a96..7d1d58b 100644 --- a/src/results.rs +++ b/src/results.rs @@ -9,9 +9,11 @@ pub struct ScoreGroup { pub candidates: Vec, } -/// Positional voting results, grouped by score from highest to lowest. +/// Voting scores, grouped from highest to lowest. /// -/// Every candidate occurs exactly once, including candidates with zero points. +/// Every candidate in the count occurs exactly once, including those with zero +/// points. The scoring unit is defined by the method: positional points, +/// doubled Copeland points, or a runoff round's vote counts. /// Equal scores remain tied. Use [`Self::ranking_by`] only when a downstream /// application requires a ranking with a caller-chosen tie-break rule. #[derive(Debug, Clone, PartialEq, Eq)] diff --git a/src/runoff.rs b/src/runoff.rs new file mode 100644 index 0000000..91bd655 --- /dev/null +++ b/src/runoff.rs @@ -0,0 +1,172 @@ +use crate::{candidate_indices, Preference, Results}; +use std::cmp::Ordering; +use std::hash::Hash; + +/// The outcome of an instant-runoff count. +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum RunoffOutcome { + /// A candidate has a strict majority of all ballots. + Winner(T), + /// The count stopped because one candidate could not be selected for elimination. + /// + /// These are the candidates tied for elimination after applying any supplied + /// comparator. They are not a set of winners; other candidates may still + /// be active. Display order follows the first ballot. + EliminationTie(Vec), +} + +/// A tally before an elimination, or the terminal tally of a runoff count. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct RunoffRound { + /// Active candidates and their current first-remaining-preference vote counts. + /// Previously eliminated candidates are omitted; zero-vote active candidates remain. + pub tallies: Results, + /// The single candidate removed after this tally, or `None` in the final round. + pub eliminated: Option, +} + +/// An instant-runoff outcome and the full trace of rounds leading to it. +/// +/// Counting stops at a strict majority or an unresolved elimination tie. The +/// trace does not assign an overall ranking to the unelected candidates. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct RunoffResults { + outcome: RunoffOutcome, + rounds: Vec>, +} + +impl RunoffResults { + /// Borrow the elected candidate or unresolved elimination tie. + pub fn outcome(&self) -> &RunoffOutcome { + &self.outcome + } + + /// Borrow the elected candidate, or return `None` if the count stopped at a tie. + pub fn winner(&self) -> Option<&T> { + match &self.outcome { + RunoffOutcome::Winner(candidate) => Some(candidate), + RunoffOutcome::EliminationTie(_) => None, + } + } + + /// Borrow all rounds in counting order, including the terminal tally. + pub fn rounds(&self) -> &[RunoffRound] { + &self.rounds + } +} + +/// Run instant-runoff voting, stopping if the lowest vote count is tied. +/// +/// Each voter supports their highest-ranked active candidate. A strict majority +/// (more than half of all ballots) elects a winner immediately. Otherwise, the +/// unique lowest candidate is eliminated and their votes transfer. A tie for +/// lowest stops the count with [`RunoffOutcome::EliminationTie`], even if the +/// tied candidates have zero votes. Use [`instant_runoff_by`] to choose a policy. +/// +/// Only complete, strict ballots are accepted by [`Preference`], so no ballots +/// are exhausted. This is a generic single-winner count, with no automatic +/// historical-count or jurisdiction-specific tie rules. +pub fn instant_runoff(pref: &Preference) -> RunoffResults { + instant_runoff_by(pref, |_, _| Ordering::Equal) +} + +/// Run instant-runoff voting with an explicit preference order for elimination ties. +/// +/// `Ordering::Less` favors the first candidate: among candidates tied for the +/// lowest vote count, the greatest (least preferred) is eliminated. For example, +/// `Ord::cmp` favors alphabetically earlier names and eliminates the latest name +/// in a tied group. The comparator is never used across different vote counts. +/// +/// Supply a consistent total order to resolve every tie. If the comparator leaves +/// multiple candidates equally least preferred, the count stops and reports them +/// in [`RunoffOutcome::EliminationTie`]. It never silently uses ballot order or +/// eliminates an entire tied group. A majority winner is elected before considering +/// elimination ties. The profile is borrowed and remains unchanged. +pub fn instant_runoff_by(pref: &Preference, mut compare: F) -> RunoffResults +where + T: Eq + Hash + Clone, + F: FnMut(&T, &T) -> Ordering, +{ + let candidates = pref.candidates(); + let indices = candidate_indices(pref); + let ballots: Vec> = pref + .ballots() + .iter() + .map(|ballot| ballot.iter().map(|candidate| indices[candidate]).collect()) + .collect(); + let mut positions = vec![0; pref.voter_count()]; + let mut active = vec![true; pref.candidate_count()]; + let mut rounds = Vec::new(); + + loop { + let mut scores = vec![0_u128; pref.candidate_count()]; + for (ballot, position) in ballots.iter().zip(&mut positions) { + // At least one candidate remains, and every ballot contains them. + // Cursors only advance, skipping already-eliminated preferences. + while !active[ballot[*position]] { + *position += 1; + } + scores[ballot[*position]] += 1; + } + let remaining: Vec = (0..candidates.len()) + .filter(|&index| active[index]) + .collect(); + let round_candidates: Vec = remaining + .iter() + .map(|&index| candidates[index].clone()) + .collect(); + let round_scores = remaining.iter().map(|&index| scores[index]).collect(); + let tallies = Results::from_scores(&round_candidates, round_scores); + + if let Some(&winner) = remaining + .iter() + .find(|&&index| scores[index] > pref.voter_count() as u128 / 2) + { + rounds.push(RunoffRound { + tallies, + eliminated: None, + }); + return RunoffResults { + outcome: RunoffOutcome::Winner(candidates[winner].clone()), + rounds, + }; + } + + // A validated nonempty profile always has at least one active candidate. + let lowest_score = remaining.iter().map(|&index| scores[index]).min().unwrap(); + let mut lowest: Vec = Vec::new(); + for index in remaining + .into_iter() + .filter(|&index| scores[index] == lowest_score) + { + if let Some(&other) = lowest.first() { + match compare(&candidates[index], &candidates[other]) { + Ordering::Less => continue, + Ordering::Greater => lowest.clear(), + Ordering::Equal => {} + } + } + lowest.push(index); + } + if lowest.len() > 1 { + let tied = lowest + .into_iter() + .map(|index| candidates[index].clone()) + .collect(); + rounds.push(RunoffRound { + tallies, + eliminated: None, + }); + return RunoffResults { + outcome: RunoffOutcome::EliminationTie(tied), + rounds, + }; + } + let eliminated = lowest[0]; + active[eliminated] = false; + rounds.push(RunoffRound { + tallies, + eliminated: Some(candidates[eliminated].clone()), + }); + } +} diff --git a/tests/methods.rs b/tests/methods.rs new file mode 100644 index 0000000..f2a55fd --- /dev/null +++ b/tests/methods.rs @@ -0,0 +1,400 @@ +use std::cmp::Reverse; +use std::collections::BTreeMap; +use vote::{ + condorcet_winner, copeland, instant_runoff, instant_runoff_by, pairwise, plurality, Preference, + Results, RunoffOutcome, RunoffResults, +}; + +fn profile(rows: &[(usize, &[u8])]) -> Preference { + Preference::new( + rows.iter() + .flat_map(|(count, ballot)| vec![ballot.to_vec(); *count]) + .collect(), + ) + .unwrap() +} + +fn scores(results: &Results) -> BTreeMap { + results + .groups() + .iter() + .flat_map(|group| { + group + .candidates + .iter() + .map(move |&candidate| (candidate, group.score)) + }) + .collect() +} + +#[test] +fn pairwise_counts_have_explicit_orientation_and_preserve_voter_multiplicity() { + // Candidate 1 is the first matrix row, not candidate 0. + let pref = profile(&[(2, &[1, 0, 2]), (1, &[0, 2, 1])]); + let result = pairwise(&pref); + assert_eq!(result.candidates(), &[1, 0, 2]); + assert_eq!( + result.counts(), + &[vec![0, 2, 2], vec![1, 0, 3], vec![1, 0, 0]] + ); + assert_eq!(result.preference_count(&0, &1), Some(1)); + assert_eq!(result.preference_count(&1, &0), Some(2)); + assert_eq!(result.preference_count(&1, &1), Some(0)); + assert_eq!(result.preference_count(&9, &1), None); + assert_eq!(result.preference_count(&1, &9), None); + assert_eq!(result.condorcet_winner(), Some(&1)); + assert_eq!(result.copeland(), copeland(&pref)); +} + +#[test] +fn condorcet_and_runoff_can_disagree_with_plurality() { + let pref = profile(&[(4, &[0, 1, 2]), (3, &[1, 2, 0]), (2, &[2, 1, 0])]); + assert_eq!(plurality(&pref).winners(), &[0]); + assert_eq!(condorcet_winner(&pref), Some(1)); + assert_eq!( + scores(&copeland(&pref)), + BTreeMap::from([(0, 0), (1, 4), (2, 2)]) + ); + let result = instant_runoff(&pref); + assert_eq!(result.winner(), Some(&1)); + assert_eq!(result.rounds().len(), 2); + assert_eq!(result.rounds()[0].eliminated, Some(2)); + assert_eq!( + scores(&result.rounds()[1].tallies), + BTreeMap::from([(0, 4), (1, 5)]) + ); +} + +#[test] +fn a_condorcet_cycle_has_no_strict_winner_and_keeps_copeland_ties() { + let pref = profile(&[(1, &[0, 1, 2]), (1, &[1, 2, 0]), (1, &[2, 0, 1])]); + let comparisons = pairwise(&pref); + assert_eq!( + comparisons.counts(), + &[vec![0, 2, 1], vec![1, 0, 2], vec![2, 1, 0]] + ); + assert_eq!(comparisons.condorcet_winner(), None); + assert_eq!(condorcet_winner(&pref), None); + assert_eq!(copeland(&pref).winners(), &[0, 1, 2]); + assert_eq!( + scores(&copeland(&pref)), + BTreeMap::from([(0, 2), (1, 2), (2, 2)]) + ); +} + +#[test] +fn even_electorates_score_pairwise_ties_without_claiming_condorcet_winners() { + let pref = profile(&[(1, &[0, 1, 2]), (1, &[2, 1, 0])]); + assert_eq!(condorcet_winner(&pref), None); + assert_eq!( + scores(&copeland(&pref)), + BTreeMap::from([(0, 2), (1, 2), (2, 2)]) + ); +} + +#[test] +fn all_methods_handle_a_single_candidate() { + let pref = profile(&[(3, &[9])]); + assert_eq!(pairwise(&pref).counts(), &[vec![0]]); + assert_eq!(condorcet_winner(&pref), Some(9)); + assert_eq!(scores(&copeland(&pref)), BTreeMap::from([(9, 0)])); + let result = instant_runoff(&pref); + assert_eq!(result.winner(), Some(&9)); + assert_eq!(result.rounds().len(), 1); + assert_eq!(result.rounds()[0].eliminated, None); + assert_eq!( + scores(&result.rounds()[0].tallies), + BTreeMap::from([(9, 3)]) + ); +} + +#[test] +fn a_unique_copeland_winner_need_not_be_a_strict_condorcet_winner() { + let pref = profile(&[(2, &[0, 1, 2]), (1, &[2, 0, 1]), (1, &[2, 1, 0])]); + assert_eq!(condorcet_winner(&pref), None); + assert_eq!(copeland(&pref).winners(), &[0]); + assert_eq!( + scores(&copeland(&pref)), + BTreeMap::from([(0, 3), (1, 1), (2, 2)]) + ); +} + +#[test] +fn majority_wins_before_considering_a_loser_tie() { + let pref = profile(&[(3, &[0, 1, 2]), (1, &[1, 2, 0]), (1, &[2, 0, 1])]); + let result = instant_runoff_by(&pref, |_, _| panic!("no tie-break needed")); + assert_eq!(result.winner(), Some(&0)); + assert_eq!(result.rounds().len(), 1); + assert_eq!(result.rounds()[0].eliminated, None); +} + +#[test] +fn exactly_half_is_not_a_majority() { + let pref = profile(&[(2, &[0, 1, 2]), (1, &[1, 0, 2]), (1, &[2, 0, 1])]); + let result = instant_runoff(&pref); + assert_eq!(result.winner(), None); + assert_eq!(result.outcome(), &RunoffOutcome::EliminationTie(vec![1, 2])); +} + +#[test] +fn unresolved_elimination_candidates_are_not_reported_as_winners() { + let pref = profile(&[(3, &[0, 1, 2]), (2, &[1, 2, 0]), (2, &[2, 1, 0])]); + let result = instant_runoff(&pref); + assert_eq!(result.outcome(), &RunoffOutcome::EliminationTie(vec![1, 2])); + assert_eq!(result.winner(), None); + assert_eq!(result.rounds()[0].tallies.winners(), &[0]); // This round's leader only. + assert_eq!(result.rounds()[0].eliminated, None); + assert_eq!(instant_runoff_by(&pref, Ord::cmp).winner(), Some(&1)); + assert_eq!(instant_runoff_by(&pref, |a, b| b.cmp(a)).winner(), Some(&2)); +} + +#[test] +fn final_two_candidate_tie_requires_an_explicit_policy() { + let pref = profile(&[(1, &[1, 0]), (1, &[0, 1])]); + assert_eq!( + instant_runoff(&pref).outcome(), + &RunoffOutcome::EliminationTie(vec![1, 0]) + ); + let resolved = instant_runoff_by(&pref, Ord::cmp); + assert_eq!(resolved.winner(), Some(&0)); + assert_eq!(resolved.rounds()[0].eliminated, Some(1)); + assert_eq!( + scores(&resolved.rounds()[1].tallies), + BTreeMap::from([(0, 2)]) + ); +} + +#[test] +fn zero_vote_ties_are_explicit_and_only_one_candidate_is_removed_per_round() { + let pref = profile(&[(2, &[0, 1, 2, 3]), (2, &[1, 0, 2, 3])]); + assert_eq!( + instant_runoff(&pref).outcome(), + &RunoffOutcome::EliminationTie(vec![2, 3]) + ); + let result = instant_runoff_by(&pref, Ord::cmp); + assert_eq!(result.winner(), Some(&0)); + assert_eq!( + result + .rounds() + .iter() + .map(|r| r.eliminated) + .collect::>(), + vec![Some(3), Some(2), Some(1), None] + ); + for (index, round) in result.rounds().iter().enumerate() { + assert_eq!(scores(&round.tallies).len(), 4 - index); + assert_eq!(scores(&round.tallies).values().sum::(), 4); + } +} + +#[test] +fn an_incomplete_tie_policy_reports_only_the_remaining_lowest_priority_group() { + let pref = profile(&[ + (1, &[0, 1, 2, 3]), + (1, &[1, 2, 3, 0]), + (1, &[2, 3, 0, 1]), + (1, &[3, 0, 1, 2]), + ]); + let result = instant_runoff_by(&pref, |a, b| u8::from(*a != 0).cmp(&u8::from(*b != 0))); + assert_eq!(result.winner(), None); + assert_eq!( + result.outcome(), + &RunoffOutcome::EliminationTie(vec![1, 2, 3]) + ); + assert_eq!(result.rounds()[0].eliminated, None); +} + +#[test] +fn transfers_skip_preferences_that_were_eliminated_in_earlier_rounds() { + let pref = profile(&[ + (4, &[0, 1, 2, 3]), + (3, &[1, 0, 2, 3]), + (2, &[2, 3, 1, 0]), + (1, &[3, 1, 2, 0]), + ]); + let before = pref.ballots().to_vec(); + let result = instant_runoff(&pref); + assert_eq!(result.winner(), Some(&1)); + assert_eq!( + result + .rounds() + .iter() + .map(|r| r.eliminated) + .collect::>(), + vec![Some(3), Some(2), None] + ); + assert_eq!( + scores(&result.rounds()[2].tallies), + BTreeMap::from([(0, 4), (1, 6)]) + ); + assert_eq!(pref.ballots(), before); +} + +#[test] +fn reproduces_aec_preference_transfer_example() { + // AEC's Nick/Michael/Jenny example, scaled from 60,000 voters to 600. + // https://results.aec.gov.au/12246/voting.htm + let pref = profile(&[ + (63, &[0, 1, 2]), + (87, &[0, 2, 1]), + (230, &[1, 0, 2]), + (220, &[2, 0, 1]), + ]); + let result = instant_runoff(&pref); + assert_eq!( + scores(&result.rounds()[0].tallies), + BTreeMap::from([(0, 150), (1, 230), (2, 220)]) + ); + assert_eq!(result.rounds()[0].eliminated, Some(0)); + assert_eq!( + scores(&result.rounds()[1].tallies), + BTreeMap::from([(1, 293), (2, 307)]) + ); + assert_eq!(result.winner(), Some(&2)); +} + +#[test] +fn candidates_do_not_need_ord_or_debug() { + #[derive(Clone, PartialEq, Eq, Hash)] + enum Candidate { + A, + B, + } + let pref = Preference::new(vec![vec![Candidate::B, Candidate::A]; 3]).unwrap(); + assert!(condorcet_winner(&pref) == Some(Candidate::B)); + assert!(pairwise(&pref).condorcet_winner() == Some(&Candidate::B)); + assert!(copeland(&pref).winners() == [Candidate::B]); + assert!(instant_runoff(&pref).winner() == Some(&Candidate::B)); +} + +type Trace = Vec<(BTreeMap, Option)>; + +// An independent reference physically removes eliminated candidates from ballots. +fn reference_runoff(mut ballots: Vec>, break_ties: bool) -> (Option, Vec, Trace) { + let voters = ballots.len(); + let mut trace = Vec::new(); + loop { + let mut counts: BTreeMap = + ballots[0].iter().map(|&candidate| (candidate, 0)).collect(); + for ballot in &ballots { + *counts.get_mut(&ballot[0]).unwrap() += 1; + } + if let Some((&winner, _)) = counts + .iter() + .find(|&(_, &count)| count > voters as u128 / 2) + { + trace.push((counts, None)); + return (Some(winner), vec![], trace); + } + let minimum = *counts.values().min().unwrap(); + let tied: Vec = counts + .iter() + .filter(|&(_, &count)| count == minimum) + .map(|(&c, _)| c) + .collect(); + if tied.len() > 1 && !break_ties { + trace.push((counts, None)); + return (None, tied, trace); + } + let loser = *counts + .keys() + .min_by_key(|&&candidate| (counts[&candidate], Reverse(candidate))) + .unwrap(); + trace.push((counts, Some(loser))); + for ballot in &mut ballots { + ballot.retain(|&candidate| candidate != loser); + } + } +} + +fn check_runoff(result: &RunoffResults, expected: &(Option, Vec, Trace)) { + assert_eq!(result.winner().copied(), expected.0); + if let RunoffOutcome::EliminationTie(tied) = result.outcome() { + let mut tied = tied.clone(); + tied.sort(); + assert_eq!(tied, expected.1); + } + let trace: Trace = result + .rounds() + .iter() + .map(|round| (scores(&round.tallies), round.eliminated)) + .collect(); + assert_eq!(trace, expected.2); +} + +#[test] +fn exhaustively_checks_pairwise_and_runoff_for_small_elections() { + let permutations = [ + vec![0, 1, 2], + vec![0, 2, 1], + vec![1, 0, 2], + vec![1, 2, 0], + vec![2, 0, 1], + vec![2, 1, 0], + ]; + for voters in 1..=4 { + for mut code in 0..6_usize.pow(voters) { + let ballots: Vec<_> = (0..voters) + .map(|_| { + let ballot = permutations[code % 6].clone(); + code /= 6; + ballot + }) + .collect(); + let pref = Preference::new(ballots.clone()).unwrap(); + let comparisons = pairwise(&pref); + let mut expected_scores = BTreeMap::new(); + let mut strict_winner = None; + for first in 0..3 { + let mut score = 0; + let mut wins = 0; + for second in 0..3 { + if first == second { + continue; + } + let count = ballots + .iter() + .filter(|ballot| { + ballot.iter().position(|&c| c == first) + < ballot.iter().position(|&c| c == second) + }) + .count(); + assert_eq!(comparisons.preference_count(&first, &second), Some(count)); + assert_eq!( + comparisons.preference_count(&second, &first), + Some(voters as usize - count) + ); + if 2 * count > voters as usize { + score += 2; + wins += 1; + } else if 2 * count == voters as usize { + score += 1; + } + } + expected_scores.insert(first, score); + if wins == 2 { + strict_winner = Some(first); + } + } + assert_eq!(scores(&comparisons.copeland()), expected_scores); + assert_eq!(expected_scores.values().sum::(), 6); + assert_eq!(comparisons.condorcet_winner().copied(), strict_winner); + if let Some(winner) = strict_winner { + assert_eq!(comparisons.copeland().winners(), &[winner]); + } + + let unresolved = reference_runoff(ballots.clone(), false); + let resolved = reference_runoff(ballots.clone(), true); + check_runoff(&instant_runoff(&pref), &unresolved); + check_runoff(&instant_runoff_by(&pref, Ord::cmp), &resolved); + + let mut reversed = ballots; + reversed.reverse(); + let reversed = Preference::new(reversed).unwrap(); + assert_eq!(scores(&copeland(&reversed)), expected_scores); + assert_eq!(condorcet_winner(&reversed), strict_winner); + check_runoff(&instant_runoff(&reversed), &unresolved); + check_runoff(&instant_runoff_by(&reversed, Ord::cmp), &resolved); + } + } +}