Algorithmadvanced
Recognizing single-peaked profiles
Also called Bartholdi-Trick algorithm, Escoffier-Lang-Ozturk algorithm, single-peaked consistency.
Decides whether a profile is single-peaked on some ordering of the candidates, and finds such an axis, in O(mn) time by placing candidates from the two ends inward.
- Time
- O(m n) worst
- Space
- O(m n) extra
- Where
- m = the number of candidates; n = the number of voters
- Model
- Word RAM
- Properties
- not comparison baseddeterministiciterative
- Evidence
- Proof sketchCode in 1 languages
- Origin
- John J. Bartholdi III, Michael A. Trick, Jean Paul Doignon, Jean Claude Falmagne, Bruno Escoffier, Jérôme Lang, Meltem Öztürk, 1986
Recognizing single-peaked profiles is the problem of deciding whether a preference profile is single-peaked on some order of the candidates, and of finding such an order, the axis. The axis is not part of the input, and there are candidate orders, so a search over all of them is hopeless beyond tiny cases. The algorithm on this page fills the axis from both ends toward the middle: the candidates that voters rank last must go at the ends. It runs in time for voters and candidates, which is linear in the size of the profile.
In plain words
In a single-peaked profile, the worst candidate of every voter is at one of the two ends of the line, because every voter likes candidates less as they move away from the favourite. So look at the bottom of every ballot. If three or more different candidates appear there, no line works. If one or two appear, put them at the free ends of the line, delete them from all ballots, and repeat with the rest. The only care needed is to choose the correct end for each candidate. A voter who likes the new candidate more than the candidate at one end and less than the candidate at the other end tells you which end is correct.
The problem
The input is a profile of strict rankings of the candidates , each ranking stored as a list, best first. The output is an axis , a linear order of , such that each is single-peaked on , or NONE if no such axis exists. If an axis exists, its reverse also works, and there may be many more.
The key facts are from the definition. On a single-peaked profile, each voter's last candidate is an end of the axis, so at most two candidates are last for some voter. Removing candidates keeps the profile single-peaked on the restricted axis. Together they suggest the outside-in method, but they do not tell which end a candidate should go to. The test in lines L10 and L11 answers this.
The algorithm
SP-AXIS(P, m) ▷ P = (≻_1, ..., ≻_n), candidates 0, ..., m - 1- 1
pos_i[a] ← position of a in ≻_i, for each voter i and candidate a - 2
left ← (); right ← (); R ← all candidates ▷ R: the unplaced candidates - 3
while |R| ≥ 2 do - 4
B ← {the candidate that voter i ranks last in R : i = 1, ..., n} - 5
if |B| ≥ 3 then return NONE - 6
if right is empty then ▷ first stage: fill both ends - 7
append min B to left; if |B| = 2 then append max B to right - 8
else ▷ second stage - 9
ℓ ← innermost candidate of left; r ← innermost candidate of right - 10
L ← {x in B : some voter i who does not rank x first in R has r ≻_i x ≻_i ℓ} - 11
R' ← {x in B : some voter i who does not rank x first in R has ℓ ≻_i x ≻_i r} - 12
if |L| ≥ 2 or |R'| ≥ 2 or L ∩ R' ≠ ∅ then return NONE - 13
put each x in B that is in neither set into L if L is empty, else into R' - 14
append L to left; append R' to right - 15
R ← R \ B; move each voter's first and last pointers past placed candidates - 16
return left, then R, then right from the outer end inward
Line L1 makes every comparison a comparison of two stored integers. Lines L4 and L5 find the candidates ranked last in the remaining set. In the first stage, line L7 fills the left end, and the right end as soon as two candidates are ranked last. In the second stage a candidate goes next to if a voter ranks between above and below while preferring some other remaining candidate to : putting next to would make a valley at for that voter. Line L11 is the mirror test. The free choices in lines L7 and L13 put the smaller candidate on the left.
Example
Take five candidates , numbered to , and three voters (Elkind, Lackner and Peters, Example 26):
| round | last candidates | , | decision | partial axis | |
|---|---|---|---|---|---|
| 1 | none | first stage: left, right | |||
| 2 | , | voter 1 has and prefers to , so | |||
| 3 | , | no voter constrains or , so goes left and right |
The loop stops with empty, and line L16 returns . All three rankings are single-peaked on it: voter 3, for example, has peak and goes down to , on the left and to , on the right. If round 2 had put next to , then voter 1 would have a valley at between and . The axes for this profile are , and their reverses.
Correctness
The proof is in proofs/correctness.md, after Elkind, Lackner and Peters (Theorem 4.2). It has two parts.
If the algorithm returns an axis, suppose some voter had a valley on it. Then there is a valley on three adjacent candidates . The first of them to be placed is an end one, say , and it was placed in a round with two last candidates. The middle one is placed no later than . When is placed, the voter ranks it below and, by a lemma on the earlier rounds, above . The voter also prefers to . So line L11 forces next to , not next to , which is a contradiction.
If the algorithm returns NONE, the proof finds one of two small patterns that no single-peaked profile can contain: three candidates that are each ranked below the other two by some voter, or four candidates with two voters whose top two sets cannot both be intervals of any axis.
Proof: The outside-in algorithm returns an axis exactly when the profile is single-peakedfull
The proof follows the structure of Elkind, Lackner and Peters (survey, Theorem 4.2), with the free choices of the code fixed and with the case analysis of the second claim done in full. Let be a profile of strict rankings of , , . We use the no-valley form of single-peakedness: a ranking is single-peaked on an axis if and only if there are no with and . Such a triple is a valley at .
Notation. In a round, is the set of unplaced candidates, is the set of candidates that some voter ranks last in (line L4), and is the set of voters who do not rank first in . In the second stage, when the right list is not empty, is the innermost candidate on the left and the innermost on the right (line L9), and lines L10 and L11 compute
Elements of go next to and elements of next to . Line L13 puts each free element of on a side that is still free, the left first.
Facts about rounds.
- Each round puts at most one candidate at the inner end of each list, so the placed candidates are a prefix and a suffix of the final axis and is the gap between them. Line L16 joins left, gap and right.
- If , its element is a unanimous bottom: every voter ranks it last in .
- If , its two elements go to opposite sides: by line L7 in the first stage, and in the second stage because line L12 rejects , and .
- Every candidate placed in a round is ranked last in that round's by some voter.
Lemma 1. In a round of the second stage, let . Every voter ranks above or above .
Proof. If and were placed in the same round, then was in that round and every voter ranked one of them last in a set that contains . If was placed in a later round than , nothing was put on the left in that later round, because is still the innermost left candidate. So that round had , a unanimous bottom, and every voter ranks above . The case where was placed later is the mirror image.
Claim 1: if the code returns an axis, every ranking is single-peaked on it
Suppose voter has a valley on the output axis. Then it has one on three adjacent candidates: if with a valley at , then either and is a narrower valley, or and is one. So let be adjacent on the axis, in this order, with and . Look at the first round that places one of them.
- Two of them on the same side in one round is impossible by fact 1. Exactly and is impossible: would be in , voter ranks it below both, so the voter's bottom in is a third element of . Exactly is impossible, because lies strictly inside the gap.
- So the round places exactly one of and ; by the mirror image we may assume it is . If in that round, is a unanimous bottom of a set that contains , which contradicts . So and all later rounds are in the second stage.
- Suppose is placed strictly before . At that round is placed and are not, the gap is an interval, and is at its end, so the gap is . Voter ranks last in it, so and is placed in the same round as , a contradiction.
- So is placed while is still in , and it is put next to , so in that round. By Lemma 1, voter ranks above or above ; the first is false, so . Voter ranks above , so and . Since line L12 did not stop, , and line L14 puts next to , not next to . This is a contradiction.
Claim 2: if the code returns NONE, the profile is not single-peaked
Lemma 2. (a) If each of three candidates is ranked below the other two by some voter, is not single-peaked. (b) If there are candidates and voters with and , then is not single-peaked.
Proof. (a) On any axis one of the three lies between the other two, and the voter who ranks it last has a valley there. (b) Restrict to ; this keeps single-peakedness. The top two candidates of a single-peaked ranking form an interval, so and are intervals, and the last candidates of and of are the two ends. So the axis is with and in the middle. If is next to , then is not an interval; if is next to , then is not one.
The code returns NONE only at line L5 or at line L12.
Line L5. Three elements of are each last in for some voter, which is Lemma 2(a).
at line L12. Let with voters , , and , . The candidate was placed in an earlier round, so by fact 4 some voter ranks below every candidate of , in particular below and . By Lemma 2(a) on it suffices to find a voter who ranks last in this triple and one who ranks last in it.
Voter ranks below . If , voter ranks last in the triple; if , it ranks last. Voter in the same way ranks last if and last if . If the two voters give different answers, we are done. Otherwise, by the symmetry between and , assume both rank last, so . Since , the top of voter in is not , and it is not , so . Since , some voter ranks last in , so . If , voter ranks last in the triple and we are done. If , then and , which is Lemma 2(b) with the candidates in the roles of .
The case is the mirror image.
at line L12. Let , with voters , and . We find that both voters rank above . If , is a unanimous bottom, and any other works ( in the loop). If and, say, , then and , and by Lemma 1 also , so and ; that case is done above. The same holds for with . So and , and
which is Lemma 2(b) with in the roles of .
Running time
Line L1 builds the table of positions in time. Each round places one or two candidates, so there are at most rounds. In a round, line L4 reads one bottom pointer per voter, lines L10 and L11 make at most constant-time comparisons, and line L15 moves the pointers past placed candidates. Each pointer moves at most times in the whole run. The total is time and space.
The tests in impl/python/test_single_peaked_recognition.py compare the answer with a search over all axes on every profile of up to 3 voters on 3 candidates and of 2 voters on 4 candidates, and on random profiles with up to 6 candidates, and they check every returned axis.
Complexity
Line L1 takes time. There are at most rounds, because each round places one or two candidates. Each voter keeps a pointer to its first and its last remaining candidate, so line L4 costs , lines L10 and L11 make at most comparisons of positions, and line L15 moves each pointer at most times in the whole run. The total is time in the word RAM model, linear in the input, and extra space for the position table. If rankings were searched by scanning, each comparison would cost and the bound would be .
Properties
- Exact. It returns an axis exactly when one exists, and every returned axis works.
- One axis, not all. The output is one axis. The set of all axes has a compact form; a PQ-tree built by the consecutive ones method describes all of them, and Elkind, Lackner and Peters (Section 4.1) give a direct description of the set.
- Deterministic. With the fixed choices in lines L7 and L13 the output depends only on the input.
- Not neutral in its output. Renaming the candidates can give a different axis among the valid ones, because free choices go by index.
- The answer is a certificate. A returned axis can be checked in time with the interval test of the definition; a NONE answer comes with one of the two forbidden patterns in the proof.
Variants and improvements
- Consecutive ones. Bartholdi and Trick (1986) wrote one 0-1 row for each top- set of each voter, rows over columns, and asked for a column order with the ones of every row consecutive, the consecutive ones property. The matrix has entries, so this route takes time, and its PQ-tree gives all axes at once.
- Direct algorithms. Doignon and Falmagne (1994) gave a direct algorithm in time, and Escoffier, Lang and Ozturk (2008) one in time. The form on this page follows the survey of Elkind, Lackner and Peters.
- Other domains. Single-crossing profiles can be recognized in time and one-dimensional Euclidean profiles in polynomial time, while for -dimensional Euclidean preferences with a fixed recognition is NP-hard (survey, Theorems 4.8, 4.11 and 4.12).
- Nearly single-peaked profiles. Deleting the fewest candidates to make a profile single-peaked takes polynomial time, , while deleting the fewest voters is NP-complete (survey, Section 4.8, Table 2).
When to use it
Use it before you rely on any result that needs single-peakedness: the median voter theorem, the strategyproof generalized median voter rules, or the polynomial algorithm for the Chamberlin-Courant rule on single-peaked profiles, which needs the axis as input. If the axis is known from the problem, such as a numerical scale, check the profile against it directly with the interval test instead.
Pitfalls
- Checking each voter alone. Every single ranking is single-peaked on some axis. The question is whether one axis works for all voters.
- Choosing the side without the test. In round 2 of the example, can go next to or next to as far as the end positions go, but only the first choice works. A rule such as "always the left side" works in the first stage and fails in the second, where lines L10 and L11 decide.
- Slow comparisons. Lines L10 and L11 compare positions. Looking a candidate up in a list costs and raises the time to .
- Ties and missing candidates. The algorithm needs strict and complete rankings. Weak orders and partial rankings need other algorithms.
Implementations
Each implementation follows the pseudocode above. A comment @line links a line of code to a line of the pseudocode. Point at a line of the pseudocode to see the matching code. The build runs the native tests of each language.
# SPDX-License-Identifier: MIT
# Shared helper of the algorithmic game theory pages of https://algorithm.tamnd.com/. The authors are listed in prov/.
"""Preference profiles, majority relations and brute force axiom checkers.
The candidates are 0, ..., m - 1. A ranking is a tuple of all m candidates, best first:
(2, 0, 1) means that 2 is preferred to 0 and 0 to 1. A profile is a tuple of n rankings,
one per voter. An approval ballot is a frozenset of candidates, and an approval profile is
a tuple of n ballots.
A rule is a function rule(profile, m). A resolute rule returns one candidate (an int); a
correspondence returns a nonempty frozenset of candidates. The checkers accept both: they
turn an int w into frozenset({w}).
Each checker takes the rule, m and n, and by default tries every profile of all_profiles(m,
n). Pass profiles= to check a given list of profiles instead (for example approval profiles,
or a random sample when the full domain is too large). Each checker returns None when the
property holds on every profile it tried, and else a counterexample tuple.
There is no voting rule in this module. Every count is an exact integer.
"""
from itertools import permutations, product
# ---------------------------------------------------------------- rankings and profiles
def all_rankings(m):
"""Return the list of the m! rankings of 0, ..., m - 1, in lexicographic order."""
return list(permutations(range(m)))
def all_profiles(m, n):
"""Yield every profile of n rankings of m candidates: (m!)^n profiles, voters ordered."""
return product(all_rankings(m), repeat=n)
def random_profile(rng, m, n):
"""Return a profile of n rankings drawn uniformly and independently (impartial culture)."""
return tuple(tuple(rng.sample(range(m), m)) for _ in range(n))
def position(r, a):
"""Return the position of candidate a in ranking r: 0 for the top."""
return r.index(a)
def prefers(r, a, b):
"""Return True if ranking r puts a above b."""
return r.index(a) < r.index(b)
def pairwise(profile, m):
"""Return the m by m matrix N with N[a][b] the number of voters who rank a above b."""
N = [[0] * m for _ in range(m)]
for r in profile:
for i, a in enumerate(r):
for b in r[i + 1:]:
N[a][b] += 1
return N
def margins(profile, m):
"""Return the m by m matrix of margins N[a][b] - N[b][a]."""
N = pairwise(profile, m)
return [[N[a][b] - N[b][a] for b in range(m)] for a in range(m)]
def condorcet_winner(profile, m):
"""Return the candidate with a positive margin over every other candidate, or None."""
M = margins(profile, m)
for a in range(m):
if all(M[a][b] > 0 for b in range(m) if b != a):
return a
return None
def weak_condorcet_winners(profile, m):
"""Return the frozenset of candidates whose margin over every other candidate is >= 0."""
M = margins(profile, m)
return frozenset(a for a in range(m) if all(M[a][b] >= 0 for b in range(m) if b != a))
def kendall_tau(r1, r2):
"""Return the number of pairs of candidates that r1 and r2 order differently."""
pos = {a: i for i, a in enumerate(r2)}
seq = [pos[a] for a in r1]
return sum(1 for i in range(len(seq)) for j in range(i + 1, len(seq)) if seq[i] > seq[j])
def is_single_peaked_on(profile, axis):
"""Return True if every ranking of the profile is single-peaked on the axis.
axis is a tuple of all candidates, left to right. A ranking is single-peaked on the axis
exactly when, for each k, its k best candidates form a contiguous block of the axis.
"""
where = {a: i for i, a in enumerate(axis)}
for r in profile:
lo = hi = where[r[0]]
for a in r[1:]:
p = where[a]
if p == lo - 1:
lo = p
elif p == hi + 1:
hi = p
else:
return False
return True
def lex_tiebreak(candidates):
"""Return the candidate with the smallest index: the default tie-breaking rule."""
return min(candidates)
def random_approval_profile(rng, m, n, p):
"""Return n approval ballots; each voter approves each candidate with probability p."""
return tuple(frozenset(a for a in range(m) if rng.random() < p) for _ in range(n))
def permute_profile(profile, pi):
"""Rename the candidates: candidate a becomes pi[a]. Works for rankings and approval ballots."""
out = []
for ballot in profile:
if isinstance(ballot, (set, frozenset)):
out.append(frozenset(pi[a] for a in ballot))
else:
out.append(tuple(pi[a] for a in ballot))
return tuple(out)
# ---------------------------------------------------------------- axiom checkers
def _as_set(result):
if isinstance(result, (set, frozenset)):
return frozenset(result)
return frozenset([result])
def _domain(m, n, profiles):
return all_profiles(m, n) if profiles is None else profiles
def _candidate_generators(m):
"""A transposition and an m-cycle: together they generate every permutation of the candidates."""
gens = []
if m >= 2:
swap = list(range(m))
swap[0], swap[1] = 1, 0
gens.append(tuple(swap))
if m >= 3:
gens.append(tuple((a + 1) % m for a in range(m)))
return gens
def check_anonymity(rule, m, n, profiles=None):
"""Check that permuting the voters does not change the result.
It tries the swap of voters 0 and 1 and the cyclic shift of the voters. These generate all
permutations, so on the full domain this is a complete test. Returns None or
(profile, permuted_profile).
"""
for P in _domain(m, n, profiles):
P = tuple(P)
if len(P) < 2:
continue
base = _as_set(rule(P, m))
others = [(P[1], P[0]) + P[2:], P[1:] + P[:1]]
for Q in others:
if _as_set(rule(Q, m)) != base:
return (P, Q)
return None
def check_neutrality(rule, m, n, profiles=None):
"""Check that renaming the candidates by pi renames the result by pi.
It tries a transposition and an m-cycle of the candidates, which generate all permutations.
A resolute rule with a fixed tie-breaking order usually fails this test; test its
correspondence instead. Returns None or (profile, pi).
"""
gens = _candidate_generators(m)
for P in _domain(m, n, profiles):
P = tuple(P)
base = _as_set(rule(P, m))
for pi in gens:
if _as_set(rule(permute_profile(P, pi), m)) != frozenset(pi[a] for a in base):
return (P, pi)
return None
def check_pareto(rule, m, n, profiles=None):
"""Check that no candidate b wins when every voter ranks some a above b.
Returns None or (profile, a, b).
"""
for P in _domain(m, n, profiles):
P = tuple(P)
W = _as_set(rule(P, m))
N = pairwise(P, m)
for b in W:
for a in range(m):
if a != b and N[a][b] == len(P):
return (P, a, b)
return None
def check_condorcet_consistency(rule, m, n, profiles=None):
"""Check that a Condorcet winner, when one exists, is the unique winner.
Returns None or (profile, condorcet_winner).
"""
for P in _domain(m, n, profiles):
P = tuple(P)
c = condorcet_winner(P, m)
if c is not None and _as_set(rule(P, m)) != frozenset([c]):
return (P, c)
return None
def _raise_once(r, w):
"""Return r with w moved up one place, or None if w is already on top."""
i = r.index(w)
if i == 0:
return None
s = list(r)
s[i - 1], s[i] = s[i], s[i - 1]
return tuple(s)
def check_monotonicity(rule, m, n, profiles=None):
"""Check that a winner stays a winner when one voter moves it up one place.
Every raise of w, with no other change in the relative order of the others, is a chain of
such one-place moves, so on the full domain this is a complete test. For a correspondence
the test is that w stays in the winning set. Returns None or (profile, raised_profile, w).
"""
for P in _domain(m, n, profiles):
P = tuple(P)
for w in _as_set(rule(P, m)):
for i, r in enumerate(P):
s = _raise_once(r, w)
if s is None:
continue
Q = P[:i] + (s,) + P[i + 1:]
if w not in _as_set(rule(Q, m)):
return (P, Q, w)
return None
def find_manipulation(rule, m, n, profiles=None):
"""Search for a voter who gets a strictly better winner by a false ranking.
The rule must be resolute (a correspondence must return one winner on every profile it
is called on). Returns None or (profile, voter, false_ranking): with the false ranking in
place of the voter's true one, the winner is one that the true ranking strictly prefers.
"""
rankings = all_rankings(m)
for P in _domain(m, n, profiles):
P = tuple(P)
w = _single(rule(P, m))
for i, r in enumerate(P):
if r[0] == w:
continue
for s in rankings:
if s == r:
continue
Q = P[:i] + (s,) + P[i + 1:]
if prefers(r, _single(rule(Q, m)), w):
return (P, i, s)
return None
def _single(result):
W = _as_set(result)
if len(W) != 1:
raise ValueError("find_manipulation needs a resolute rule")
return next(iter(W))
single_peaked_recognition.py 84 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/single-peaked-recognition/. The authors are listed in prov/HW79QR.jsonl.
"""Recognize single-peaked profiles and find an axis, in O(m n) time.
The candidates are 0, ..., m - 1 and a profile is a sequence of n rankings, each a tuple of all
m candidates, best first. The algorithm builds the axis from the two ends inward: at each
step the candidates that some voter ranks last among the unplaced ones must go to the free
ends. This is the algorithm of Doignon and Falmagne (1994) and Escoffier, Lang and Ozturk
(2008) in the form of Elkind, Lackner and Peters (survey, Algorithm 1).
Free choices are made in a fixed way: the smaller candidate goes to the left.
"""
from typing import Optional, Sequence
Ranking = Sequence[int]
def single_peaked_axis(profile: Sequence[Ranking], m: int) -> Optional[tuple]:
"""Return an axis (a tuple of all m candidates, left to right) on which every ranking of
the profile is single-peaked, or None if there is no such axis."""
n = len(profile)
if n == 0:
return tuple(range(m))
pos = []
for r in profile: # @line L1
p = [0] * m
for k, a in enumerate(r):
p[a] = k
pos.append(p)
top = [0] * n
bot = [m - 1] * n
placed = [False] * m
left, right = [], [] # @line L2
rest = m
while rest >= 2: # @line L3
B = {profile[i][bot[i]] for i in range(n)} # @line L4
if len(B) >= 3: # @line L5
return None
B = sorted(B)
if not right: # @line L6
left.append(B[0]) # @line L7
if len(B) == 2:
right.append(B[1])
else: # @line L8
l, r = left[-1], right[-1] # @line L9
to_left, to_right = set(), set()
for x in B:
for i in range(n):
if profile[i][top[i]] == x:
continue
p = pos[i]
if p[r] < p[x] < p[l]:
to_left.add(x) # @line L10
if p[l] < p[x] < p[r]:
to_right.add(x) # @line L11
if len(to_left) >= 2 or len(to_right) >= 2 or to_left & to_right: # @line L12
return None
free = [x for x in B if x not in to_left and x not in to_right] # @line L13
for x in free:
if not to_left:
to_left.add(x)
else:
to_right.add(x)
left.extend(to_left) # @line L14
right.extend(to_right)
for x in B: # @line L15
placed[x] = True
rest -= len(B)
if rest == 0:
break
for i in range(n):
r = profile[i]
while placed[r[bot[i]]]:
bot[i] -= 1
while placed[r[top[i]]]:
top[i] += 1
middle = [a for a in range(m) if not placed[a]]
return tuple(left + middle + right[::-1]) # @line L16
def is_single_peaked(profile: Sequence[Ranking], m: int) -> bool:
"""Return True if the profile is single-peaked on some axis."""
return single_peaked_axis(profile, m) is not None
test_single_peaked_recognition.py 112 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/single-peaked-recognition/. The authors are listed in prov/HW79QR.jsonl.
import itertools
import random
from agtprefs import all_profiles, all_rankings, is_single_peaked_on, random_profile
from single_peaked_recognition import is_single_peaked, single_peaked_axis
def brute_axes(profile, m):
return [ax for ax in itertools.permutations(range(m)) if is_single_peaked_on(profile, ax)]
def random_sp_ranking(rng, axis):
"""Build a ranking single-peaked on axis from the bottom: take one end of the rest each time."""
lo, hi = 0, len(axis) - 1
worst_first = []
while lo < hi:
if rng.random() < 0.5:
worst_first.append(axis[lo])
lo += 1
else:
worst_first.append(axis[hi])
hi -= 1
worst_first.append(axis[lo])
return tuple(reversed(worst_first))
def check(profile, m):
axis = single_peaked_axis(profile, m)
exists = bool(brute_axes(profile, m))
assert (axis is not None) == exists, (profile, axis)
if axis is not None:
assert sorted(axis) == list(range(m))
assert is_single_peaked_on(profile, axis)
def test_every_profile_with_three_candidates():
for n in range(1, 4):
for P in all_profiles(3, n):
check(P, 3)
def test_every_profile_of_two_voters_with_four_candidates():
for P in all_profiles(4, 2):
check(P, 4)
def test_random_single_peaked_profiles_are_recognized():
rng = random.Random(1)
for _ in range(300):
m = rng.randint(2, 6)
axis = tuple(rng.sample(range(m), m))
P = tuple(random_sp_ranking(rng, axis) for _ in range(rng.randint(1, 6)))
check(P, m)
assert is_single_peaked(P, m)
def test_random_profiles_agree_with_brute_force():
rng = random.Random(2)
for _ in range(300):
m = rng.randint(3, 6)
n = rng.randint(1, 4)
if rng.random() < 0.5:
P = random_profile(rng, m, n)
else:
axis = tuple(rng.sample(range(m), m))
P = [random_sp_ranking(rng, axis) for _ in range(n)]
i = rng.randrange(n)
r = list(P[i])
a, b = rng.sample(range(m), 2)
r[a], r[b] = r[b], r[a]
P[i] = tuple(r)
P = tuple(P)
check(P, m)
def test_count_of_single_peaked_rankings_on_one_axis():
for m in range(1, 7):
axis = tuple(range(m))
assert sum(1 for r in all_rankings(m) if is_single_peaked_on((r,), axis)) == 2 ** (m - 1)
def test_condorcet_cycle_is_not_single_peaked():
assert single_peaked_axis(((0, 1, 2), (1, 2, 0), (2, 0, 1)), 3) is None
def test_worked_example():
# a, b, c, d, e = 0, 1, 2, 3, 4
P = ((4, 3, 1, 2, 0), (4, 3, 2, 1, 0), (3, 4, 2, 0, 1))
assert single_peaked_axis(P, 5) == (0, 2, 3, 4, 1)
assert brute_axes(P, 5) == [(0, 2, 3, 4, 1), (0, 2, 4, 3, 1), (1, 3, 4, 2, 0), (1, 4, 3, 2, 0)]
def test_edge_cases():
assert single_peaked_axis((), 3) == (0, 1, 2)
assert single_peaked_axis(((0,),), 1) == (0,)
assert single_peaked_axis(((1, 0),), 2) in ((0, 1), (1, 0))
def test_larger_profile():
rng = random.Random(3)
m = 40
axis = tuple(rng.sample(range(m), m))
P = tuple(random_sp_ranking(rng, axis) for _ in range(300))
found = single_peaked_axis(P, m)
assert found is not None and is_single_peaked_on(P, found)
Q = P[:-1] + (tuple(rng.sample(range(m), m)),)
found = single_peaked_axis(Q, m)
if found is not None:
assert is_single_peaked_on(Q, found)
History
Black (1948) defined single-peaked preferences, but the question of finding the axis came much later. Bartholdi and Trick (1986) met it while studying stable roommates with preferences from a one-dimensional model, and solved it by the consecutive ones property and PQ-trees. Doignon and Falmagne (1994) gave a direct algorithm in the language of unidimensional unfolding in psychology, and Escoffier, Lang and Ozturk (2008) found a direct linear algorithm independently, in computational social choice.
References
- John J. Bartholdi III and Michael A. Trick, Stable matching with preferences derived from a psychological model, Operations Research Letters 5(4) (1986), 165-169, the recognition of single-peaked preferences
- Jean-Paul Doignon and Jean-Claude Falmagne, A polynomial time algorithm for unidimensional unfolding representations, Journal of Algorithms 16(2) (1994), 218-233, the direct algorithm that builds the axis
- Bruno Escoffier, Jérôme Lang and Meltem Öztürk, Single-peaked consistency and its complexity, Proceedings of ECAI 2008, 366-370, the direct algorithm for single-peaked consistency
- Edith Elkind, Martin Lackner and Dominik Peters, Preference restrictions in computational social choice: a survey, arXiv 2205.09092, version 2, March 2025, Section 4.1 (the consecutive ones reduction, Algorithm 1 and Theorem 4.2) and Section 4.8 (nearly single-peaked profiles, Table 2)
About this page
The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.
| Ladder | Level | What the next level needs |
|---|---|---|
| Human proof | H1 sketch |
|
| Lean | L0 no Lean part |
|
| Code (python) | I0 not checked yet |
|
| Visual | V0 none |
|
| Writing | W2 basic |
|
Tag HW79QR Edit this page History Report an error Markdown