Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions .github/workflows/tests.yml
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
12 changes: 12 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -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`,
Expand Down
2 changes: 1 addition & 1 deletion Cargo.toml
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
[package]
name = "vote"
version = "0.2.0"
version = "0.3.0"
authors = ["Chris McComb <ccmcc2012@gmail.com>"]
description = "Common voting methods"
edition = "2021"
Expand Down
107 changes: 101 additions & 6 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -4,17 +4,18 @@

# 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

Requires **Rust 1.85 or newer**. Add `vote` to your project's `Cargo.toml`:

```toml
[dependencies]
vote = "0.2"
vote = "0.3"
```

# Usage
Expand Down Expand Up @@ -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

Expand Down Expand Up @@ -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
Expand Down
43 changes: 43 additions & 0 deletions examples/compare_methods.rs
Original file line number Diff line number Diff line change
@@ -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(())
}
4 changes: 4 additions & 0 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down
122 changes: 122 additions & 0 deletions src/pairwise.rs
Original file line number Diff line number Diff line change
@@ -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<T> {
candidates: Vec<T>,
counts: Vec<Vec<usize>>,
}

impl<T> PairwiseResults<T> {
/// 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<usize>] {
&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<T: Eq> PairwiseResults<T> {
/// 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<usize> {
let row = self
.candidates
.iter()
.position(|candidate| candidate == preferred)?;
let column = self
.candidates
.iter()
.position(|candidate| candidate == other)?;
Some(self.counts[row][column])
}
}

impl<T: Clone> PairwiseResults<T> {
/// 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<T> {
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<T: Eq + Hash + Clone>(pref: &Preference<T>) -> PairwiseResults<T> {
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<T: Eq + Hash + Clone>(pref: &Preference<T>) -> Results<T> {
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<T: Eq + Hash + Clone>(pref: &Preference<T>) -> Option<T> {
pairwise(pref).condorcet_winner().cloned()
}
6 changes: 4 additions & 2 deletions src/results.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9,9 +9,11 @@ pub struct ScoreGroup<T> {
pub candidates: Vec<T>,
}

/// 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)]
Expand Down
Loading
Loading