Algorithmadvanced
KwikSort for rank aggregation
Also called Ailon-Charikar-Newman algorithm, pivot algorithm for Kemeny aggregation.
Quicksort with random pivots on pairwise majorities. It is an expected 2-approximation for Kemeny aggregation, and 11/7 when the better of it and an input ranking is kept.
- Time
- O(n m^2) worst
- Space
- O(m^2) extra
- Where
- m = the number of candidates; n = the number of voters
- Model
- Word RAM
- Properties
- comparison basedrandomizedrecursive
- Evidence
- Proof sketchCode in 1 languages
- Origin
- Nir Ailon, Moses Charikar, Alantha Newman, 2005
KwikSort is a fast approximation algorithm for Kemeny rank aggregation: given the rankings of many voters, find one ranking that disagrees with them as little as possible in total. Finding the best ranking is NP-hard. KwikSort runs quicksort with random pivots, but compares two candidates by the majority of the voters instead of by a key. Because the majority relation can have cycles, the result depends on the pivots, and the analysis bounds its expected cost. Ailon, Charikar and Newman proved that the expected cost is at most 2 times the optimum. Keeping the better of the KwikSort ranking and one of the input rankings lowers the ratio to . The same algorithm on any tournament has expected ratio 3 for the feedback arc set problem, which is the Slater rule for voting.
In plain words
You want one ranking that agrees with many voters as much as possible. Pick a candidate at random. Put every candidate that most voters prefer to it on its left, and every other candidate on its right. Then do the same, separately, inside the left group and inside the right group, until every group has one candidate. Because majorities can go in circles, some choices of the random candidate work better than others, but on average the result costs at most twice the best possible. As a safety net, compare the result with the best ballot that some voter cast, and keep the better one.
The problem
There are candidates and a profile of rankings. Let be the number of voters who rank above . The Kemeny cost of a ranking is the sum of its Kendall tau distances to the ballots,
and the problem is to find a ranking with the least cost, . The majority tournament has an arc when ; this page breaks ties toward the candidate with the smaller index, so has exactly one arc between each pair. An algorithm with expected ratio returns a ranking with on every profile.
The algorithm
KWIKSORT(V, T)- 1
if |V| ≤ 1 then return V - 2
p ← a uniformly random member of V - 3
L ← [u ∈ V \ {p} : u → p in T] - 4
R ← [u ∈ V \ {p} : p → u in T] - 5
return KWIKSORT(L, T), then p, then KWIKSORT(R, T) AGGREGATE(P, m)- 6
T ← majority tournament of P - 7
r1 ← KWIKSORT(A, T) - 8
r2 ← the ballot of P with the least Kemeny cost - 9
return r2 if K(r2) ≤ K(r1), else r1
Lines L1 to L5 are randomized quicksort with the arcs of as the comparisons. The code runs it with an explicit stack and a seeded random generator, so a run can be repeated. Line L8 is a deterministic form of Pick-A-Perm, which in the paper takes a ballot at random. The best ballot costs no more than a random one, so every bound for the better of KwikSort and Pick-A-Perm holds for line L9.
Example
Take the profile of the example on the Slater rule page, with four candidates and 13 voters:
| voters | ranking |
|---|---|
| 4 | |
| 6 | |
| 3 |
The majority tournament has the arcs , , , , and . Each of the four first pivots has probability :
| first pivot | left, right | output | |
|---|---|---|---|
| , | 33 | ||
| , | 30 | ||
| , | 30 | ||
| , | 33 |
Every group of two is sorted by its single arc. The expected Kemeny cost of KwikSort is . The optimum is , reached by , which is also the ballot of the 6 voters. So line L8 finds it and line L9 returns it. Here KwikSort alone has ratio , and the combined algorithm is exact.
Correctness
KwikSort always returns a ranking of all candidates, since each call places its pivot and passes every other candidate to exactly one side. If the majority relation is transitive, every split agrees with it, and the output is that order, which is then optimal. The ratio 3 for feedback arc set in tournaments has a short proof, given in full in proofs/correctness.md. A pair ends in the wrong order only when a pivot separates them with , so that form a directed triangle. So the cost equals the number of triangles whose three candidates are still together when one of them becomes the pivot. Each arc can be charged by at most one such triangle, and each of the three arcs of a triangle is equally likely to be the charged one. So the probabilities of the triangles, divided by 3, form a fractional packing of triangles into arcs, which is a lower bound on the optimum. For rank aggregation, Ailon, Charikar and Newman extend the argument with weights, and the tests check the ratios 2 and exactly on small profiles by computing the full output distribution.
Proof: Correctness of KwikSort and its ratio for feedback arc set in tournamentsfull
Let be a tournament on a finite set : for each pair , exactly one of and holds. For a ranking of , an arc is backward when puts above , and is the number of backward arcs. Let be the least . A triangle is a set whose three arcs form a directed cycle. A run of KWIKSORT is a tree of calls, and each call on a list with at least 2 members picks one pivot.
Claim 1 (output). KWIKSORT returns each member of exactly once. If the arcs of form a linear order, it returns that order.
Proof. By induction on . Lines L3 and L4 put each in exactly one of and , because exactly one of and holds, and . If is a linear order, the members of are above and those of below it, and by induction each side is returned in order.
Claim 2 (separation). For , there is exactly one call in which and are both in the list and either one of them is the pivot or they go to different sides. Their final order is decided in that call, and only there.
Proof. Both are in the first call. A call that keeps them together passes them to the same side, and the list gets shorter, so such calls end. The first call that does not keep them together decides the order: the pivot goes between the two sides, and the sides keep their order in the output.
Claim 3 (backward arcs and triangles). An arc is backward in the output exactly when, in the call of Claim 2 for and , the pivot is neither of them and . So of the output equals the number of triangles for which some call has all of in its list and a member of as its pivot. Call such a triangle hit.
Proof. If the pivot is , then goes right since , and the arc is forward. If the pivot is , goes left, and the arc is forward. If the pivot is neither and the two go to different sides, then goes left and goes right exactly when and , and then is a triangle. In that call all of are in the list and is the pivot. Conversely, if a triangle with is in a list whose pivot is , then goes left and goes right, so is backward. Before that call, no member of the triangle was a pivot and no pair of it was separated, so this is the separating call of Claim 2 for and , and each hit triangle gives one backward arc. Different hit triangles give different arcs, because the arc determines the separating call and so its pivot.
Claim 4 (ratio 3). .
Proof. For a triangle , let be the probability that is hit. Consider the first call whose pivot lies in , if any. Before it, has stayed in one list or has been split. If it is still in one list, the pivot of that call is uniform over the list, so given that it lies in , each of the three members of is the pivot with probability . So for each member of , the probability that is hit with pivot is . Fix an arc . By Claim 3, the event that is hit with the pivot opposite is the event that is made backward by that pivot in its separating call. There is only one separating call for , so these events are disjoint for the triangles that contain , and .
Let be the set of backward arcs of an optimal ranking. Every triangle has at least one arc in , since a ranking cannot follow all three arcs of a cycle. So
By Claim 3, .
Claim 5 (Smith set on top). Let be a nonempty set with for every and . Then KWIKSORT ranks every member of above every other candidate. For the majority tournament of a profile, this holds for the Smith set, and a Condorcet winner is ranked first.
Proof. Take and and their call from Claim 2. If the pivot is , goes right; if it is , goes left. If the pivot is neither, left and right would need and . If , then ; if , then . Both contradict this. So ends above . The members of the Smith set have positive margins over the outsiders, so the tie rule of line L6 does not affect these arcs.
Claim 6 (the best ballot). The ballot of line L8 has , so the output of line L9 does too.
Proof. Let be the Kendall tau distance, which is a metric, let be optimal, and let be the ballots. Then . The average of over is , so the average of is at most , and the least is not larger.
Claim 7 (time). AGGREGATE runs in time and space in the worst case.
Proof. The counts and the tournament take time and space. A call of KWIKSORT on a list of members compares the pivot with the others in lines L3 and L4. A pair is compared only when one of its members is the pivot, and then the two are separated for good, so each pair is compared at most once and there are at most comparisons. There are at most calls with a pivot, and the lists of one level of the call tree are disjoint, so the other work is too. Line L8 computes costs in each, and line L9 two more.
Complexity
Counting takes time, and line L8 also takes to compute the cost of every ballot. KwikSort itself compares each pair at most once, so it makes at most comparisons. When the majority relation is a linear order, it is exactly randomized quicksort and makes comparisons in expectation. The total is time in the worst case on the word RAM, with space for and . This is the same as the cost of reading the pairwise counts, while the exact problem is NP-hard.
Properties
- Expected ratios. On every profile, , and the better of KwikSort and Pick-A-Perm has expected cost at most . On any tournament, the expected number of backward arcs is at most 3 times the minimum.
- The best ballot is a 2-approximation. By the triangle inequality for the Kendall tau distance, some ballot has cost at most . Line L9 is never worse than this.
- Smith set on top. Every member of the Smith set beats every outsider, so no pivot sends an outsider to the left of a member. KwikSort always ranks the Smith set first, and a Condorcet winner first of all.
- Randomized. Different pivots can give rankings of different cost, as in the example. With a fixed seed, the code is deterministic.
Variants and improvements
- LP-based pivoting. In the same paper, Ailon, Charikar and Newman also round an LP relaxation with the pivot rule and get a smaller ratio for rank aggregation, at the cost of solving the LP.
- Deterministic pivots. Later work chooses the pivots by rules that follow the LP solution or the ranking by scores, and keeps a constant ratio without randomness.
- Better algorithms. The weighted feedback arc set problem in tournaments, and so Kemeny aggregation, has a polynomial time approximation scheme. See the Kemeny rank aggregation page for the details.
- Correlation clustering. The same pivot idea, with "similar" and "different" in place of "above" and "below", gives an expected 3-approximation for correlation clustering on complete graphs, also in the paper by Ailon, Charikar and Newman.
- Local search. A common practice is to improve the KwikSort output by swaps or moves of single candidates while the Kemeny cost goes down.
When to use it
Use KwikSort when you need a good consensus ranking of many candidates quickly, as in meta search, where many search engines rank the same pages, or in the fusion of ranked lists in recommendation systems. It needs only the majority relation, so it also works when the inputs are partial lists, if the pairwise counts can be formed. For a few dozen candidates, an exact integer program solver for Kemeny's rule is often fast enough and gives the optimum.
Pitfalls
- Expecting the optimum. KwikSort is an approximation. On profiles with cycles it can return a ranking that costs much more than the best ballot. Keep the comparison of line L9.
- Ties in the majority relation. With an even number of voters, some pairs are tied. Break the ties by a fixed rule so that every comparison has an answer. A tie sent to both sides, or to neither, loses candidates or repeats them.
- Running time of the counts. The sort is fast, but the counts take time. For very long lists, sample voters or count only the pairs that the sort compares.
- Recursion depth. With bad luck the recursion is levels deep. Use an explicit stack, as the code does.
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))
kwiksort_rank_aggregation.py 77 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/kwiksort-rank-aggregation/. The authors are listed in prov/BHYQT7.jsonl.
import random
from typing import Optional, Sequence
Ranking = Sequence[int]
def pairwise_counts(profile: Sequence[Ranking], m: int) -> list[list[int]]:
"""Return 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 majority_tournament(profile: Sequence[Ranking], m: int) -> list[list[bool]]:
"""Return T with T[u][v] True when a majority ranks u above v; a tie goes to the smaller index."""
N = pairwise_counts(profile, m)
return [[u != v and (N[u][v] > N[v][u] or (N[u][v] == N[v][u] and u < v))
for v in range(m)] for u in range(m)]
def partition(T: list[list[bool]], V: Sequence[int], p: int) -> tuple[list[int], list[int]]:
"""Split V without p into the candidates that beat p in T and those that p beats."""
left = [u for u in V if u != p and T[u][p]] # @line L3
right = [u for u in V if u != p and T[p][u]] # @line L4
return left, right
def kwiksort(T: list[list[bool]], V: Sequence[int], rng: random.Random) -> tuple[int, ...]:
"""Order V by quicksort on the tournament T with uniformly random pivots."""
out: list[int] = []
stack = [list(V)]
while stack:
W = stack.pop()
if len(W) <= 1: # @line L1
out.extend(W)
continue
p = W[rng.randrange(len(W))] # @line L2
left, right = partition(T, W, p)
stack.append(right) # @line L5
stack.append([p])
stack.append(left)
return tuple(out)
def kemeny_cost(N: list[list[int]], r: Ranking) -> int:
"""Return the sum over voters of the Kendall tau distance to r, from the counts N."""
return sum(N[r[j]][r[i]] for i in range(len(r)) for j in range(i + 1, len(r)))
def fas_cost(T: list[list[bool]], r: Ranking) -> int:
"""Return the number of arcs of T that point from a lower to a higher place of r."""
return sum(1 for i in range(len(r)) for j in range(i + 1, len(r)) if T[r[j]][r[i]])
def best_input_ranking(profile: Sequence[Ranking], N: list[list[int]]) -> tuple[int, ...]:
"""Return the ballot with the least Kemeny cost (the first one on ties)."""
return tuple(min(profile, key=lambda r: kemeny_cost(N, r)))
def kwiksort_aggregate(profile: Sequence[Ranking], m: int,
seed: Optional[int] = 0) -> tuple[int, ...]:
"""Return the better, in Kemeny cost, of KwikSort on the majority tournament and the best
ballot. The ballot wins ties. With no voters, return KwikSort on the empty tournament."""
rng = random.Random(seed)
N = pairwise_counts(profile, m)
T = majority_tournament(profile, m) # @line L6
r1 = kwiksort(T, range(m), rng) # @line L7
if not profile:
return r1
r2 = best_input_ranking(profile, N) # @line L8
return r2 if kemeny_cost(N, r2) <= kemeny_cost(N, r1) else r1 # @line L9
test_kwiksort_rank_aggregation.py 155 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/kwiksort-rank-aggregation/. The authors are listed in prov/BHYQT7.jsonl.
import random
from fractions import Fraction
from itertools import combinations, permutations
from agtprefs import condorcet_winner, kendall_tau, margins, pairwise, random_profile
from kwiksort_rank_aggregation import (best_input_ranking, fas_cost, kemeny_cost, kwiksort,
kwiksort_aggregate, majority_tournament, pairwise_counts,
partition)
A, B, C, D = 0, 1, 2, 3
# The worked example of the page (the same profile as on the Slater rule page).
EXAMPLE = ((D, B, C, A),) * 4 + ((B, A, D, C),) * 6 + ((C, A, D, B),) * 3
def output_distribution(T, V):
"""The exact distribution of the output of KwikSort on the list V."""
if len(V) <= 1:
return {tuple(V): Fraction(1)}
out = {}
for p in V:
left, right = partition(T, V, p)
for a, pa in output_distribution(T, left).items():
for b, pb in output_distribution(T, right).items():
k = a + (p,) + b
out[k] = out.get(k, 0) + pa * pb / len(V)
return out
def random_tournament(rng, m):
T = [[False] * m for _ in range(m)]
for u, v in combinations(range(m), 2):
if rng.random() < 0.5:
T[u][v] = True
else:
T[v][u] = True
return T
def test_example():
N = pairwise_counts(EXAMPLE, 4)
assert N == pairwise(EXAMPLE, 4)
T = majority_tournament(EXAMPLE, 4)
arcs = {(u, v) for u in range(4) for v in range(4) if T[u][v]}
assert arcs == {(B, A), (B, C), (D, C), (A, D), (C, A), (D, B)}
dist = output_distribution(T, [A, B, C, D])
assert dist == {(B, C, A, D): Fraction(1, 4), (D, B, C, A): Fraction(1, 2),
(A, D, B, C): Fraction(1, 4)}
assert [kemeny_cost(N, r) for r in ((B, C, A, D), (D, B, C, A), (A, D, B, C))] == [33, 30, 33]
assert sum(p * kemeny_cost(N, r) for r, p in dist.items()) == Fraction(63, 2)
assert min(kemeny_cost(N, r) for r in permutations(range(4))) == 27
assert best_input_ranking(EXAMPLE, N) == (B, A, D, C)
assert kwiksort_aggregate(EXAMPLE, 4, seed=1) == (B, A, D, C)
assert sum(kendall_tau((B, A, D, C), v) for v in EXAMPLE) == 27
def test_edge_cases():
rng = random.Random(0)
T = majority_tournament((), 3)
assert kwiksort(T, [], rng) == ()
assert kwiksort(T, [2], rng) == (2,)
assert kwiksort(T, range(3), rng) == (0, 1, 2)
assert kwiksort_aggregate((), 3) == (0, 1, 2)
assert kwiksort_aggregate(((2, 0, 1),), 3) == (2, 0, 1)
def test_transitive_tournament_is_sorted():
rng = random.Random(1)
for _ in range(100):
m = rng.randint(1, 12)
order = list(range(m))
rng.shuffle(order)
T = [[False] * m for _ in range(m)]
for i in range(m):
for j in range(i + 1, m):
T[order[i]][order[j]] = True
assert kwiksort(T, range(m), rng) == tuple(order)
assert fas_cost(T, order) == 0
def test_output_is_a_ranking_and_seeded():
rng = random.Random(2)
for _ in range(100):
m, n = rng.randint(1, 9), rng.randint(0, 7)
P = random_profile(rng, m, n)
r = kwiksort_aggregate(P, m, seed=5)
assert sorted(r) == list(range(m))
assert r == kwiksort_aggregate(P, m, seed=5)
def test_condorcet_winner_and_smith_set_on_top():
rng = random.Random(3)
for _ in range(150):
m, n = rng.randint(2, 8), rng.randint(1, 7)
P = random_profile(rng, m, n)
T = majority_tournament(P, m)
M = margins(P, m)
smith = None
for size in range(1, m + 1):
for S in combinations(range(m), size):
if all(M[a][b] > 0 for a in S for b in range(m) if b not in S):
smith = frozenset(S)
break
if smith:
break
r = kwiksort(T, range(m), random.Random(rng.random()))
assert frozenset(r[:len(smith)]) == smith
w = condorcet_winner(P, m)
if w is not None:
assert r[0] == w
def test_ratio_three_for_feedback_arc_set_in_tournaments():
rng = random.Random(4)
for _ in range(40):
m = rng.randint(2, 6)
T = random_tournament(rng, m)
opt = min(fas_cost(T, r) for r in permutations(range(m)))
dist = output_distribution(T, list(range(m)))
assert sum(dist.values()) == 1
expected = sum(p * fas_cost(T, r) for r, p in dist.items())
assert expected <= 3 * opt
def test_ratios_for_rank_aggregation():
rng = random.Random(5)
for _ in range(40):
m, n = rng.randint(2, 5), rng.choice((3, 4, 5, 6, 7))
P = random_profile(rng, m, n)
N = pairwise_counts(P, m)
T = majority_tournament(P, m)
opt = min(kemeny_cost(N, r) for r in permutations(range(m)))
dist = output_distribution(T, list(range(m)))
e_kwik = sum(p * kemeny_cost(N, r) for r, p in dist.items())
assert e_kwik <= 2 * opt
pick = [kemeny_cost(N, v) for v in P]
assert Fraction(sum(pick), n) <= 2 * opt
e_best = sum(p * min(kemeny_cost(N, r), c) for r, p in dist.items() for c in pick) / n
assert e_best <= Fraction(11, 7) * opt
best_ballot = min(pick)
e_ours = sum(p * min(kemeny_cost(N, r), best_ballot) for r, p in dist.items())
assert e_ours <= e_best
def test_larger_input():
rng = random.Random(6)
m, n = 100, 9
P = random_profile(rng, m, n)
N = pairwise_counts(P, m)
r = kwiksort_aggregate(P, m, seed=2)
assert sorted(r) == list(range(m))
assert kemeny_cost(N, r) <= min(kemeny_cost(N, v) for v in P)
History
Nir Ailon, Moses Charikar and Alantha Newman introduced KwikSort at STOC 2005 in a paper on aggregating inconsistent information, which treats feedback arc set in tournaments, rank aggregation and correlation clustering with one pivot method. The full version appeared in the Journal of the ACM in 2008. Their analysis by fractional triangle packings became a standard tool. Rank aggregation itself was studied for the web by Dwork, Kumar, Naor and Sivakumar in 2001, and Kemeny proposed the cost in 1959.
References
- Nir Ailon, Moses Charikar and Alantha Newman, Aggregating inconsistent information: ranking and clustering, Journal of the ACM 55(5) (2008), Article 23, the analysis of KwikSort for feedback arc set in tournaments (expected ratio 3, by a fractional packing of triangles), and the section on rank aggregation (expected ratio 2 for KwikSort on the majority tournament, and 11/7 for the better of KwikSort and Pick-A-Perm)
- Nir Ailon, Moses Charikar and Alantha Newman, Aggregating inconsistent information: ranking and clustering, Proceedings of the 37th ACM Symposium on Theory of Computing (STOC 2005), 684-693, the conference version of the same results
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 BHYQT7 Edit this page History Report an error Markdown