Algorithm Search⌘K

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
Properties
comparison basedrandomizedrecursive
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 11/711/7. 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 mm candidates A={0,…,m−1}A = \{0, \ldots, m - 1\} and a profile PP of nn rankings. Let N(x,y)N(x, y) be the number of voters who rank xx above yy. The Kemeny cost of a ranking rr is the sum of its Kendall tau distances to the ballots,

K(r)=∑x above y in rN(y,x),K(r) = \sum_{x \text{ above } y \text{ in } r} N(y, x),

and the problem is to find a ranking with the least cost, OPT\mathrm{OPT}. The majority tournament TT has an arc x→yx \to y when N(x,y)>N(y,x)N(x, y) > N(y, x); this page breaks ties toward the candidate with the smaller index, so TT has exactly one arc between each pair. An algorithm with expected ratio α\alpha returns a ranking with E[K(r)]≤α⋅OPT\mathbb{E}[K(r)] \le \alpha \cdot \mathrm{OPT} on every profile.

The algorithm

  1. KWIKSORT(V, T)
  2. 1if |V| ≤ 1 then return V
  3. 2p ← a uniformly random member of V
  4. 3L ← [u ∈ V \ {p} : u → p in T]
  5. 4R ← [u ∈ V \ {p} : p → u in T]
  6. 5return KWIKSORT(L, T), then p, then KWIKSORT(R, T)
  7. AGGREGATE(P, m)
  8. 6T ← majority tournament of P
  9. 7r1 ← KWIKSORT(A, T)
  10. 8r2 ← the ballot of P with the least Kemeny cost
  11. 9return r2 if K(r2) ≤ K(r1), else r1

Lines L1 to L5 are randomized quicksort with the arcs of TT 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 a,b,c,da, b, c, d and 13 voters:

voters ranking
4 d≻b≻c≻ad \succ b \succ c \succ a
6 b≻a≻d≻cb \succ a \succ d \succ c
3 c≻a≻d≻bc \succ a \succ d \succ b

The majority tournament has the arcs b→ab \to a, b→cb \to c, d→cd \to c, a→da \to d, c→ac \to a and d→bd \to b. Each of the four first pivots has probability 1/41/4:

first pivot left, right output KK
aa {b,c}\{b, c\}, {d}\{d\} b≻c≻a≻db \succ c \succ a \succ d 33
bb {d}\{d\}, {a,c}\{a, c\} d≻b≻c≻ad \succ b \succ c \succ a 30
cc {b,d}\{b, d\}, {a}\{a\} d≻b≻c≻ad \succ b \succ c \succ a 30
dd {a}\{a\}, {b,c}\{b, c\} a≻d≻b≻ca \succ d \succ b \succ c 33

Every group of two is sorted by its single arc. The expected Kemeny cost of KwikSort is 31.531.5. The optimum is 2727, reached by b≻a≻d≻cb \succ a \succ d \succ c, which is also the ballot of the 6 voters. So line L8 finds it and line L9 returns it. Here KwikSort alone has ratio 31.5/27=7/631.5/27 = 7/6, 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 u→vu \to v ends in the wrong order only when a pivot ww separates them with v→w→uv \to w \to u, so that u,v,wu, v, w 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 11/711/7 exactly on small profiles by computing the full output distribution.

Proof: Correctness of KwikSort and its ratio for feedback arc set in tournamentsfull

Let TT be a tournament on a finite set VV: for each pair u≠vu \ne v, exactly one of u→vu \to v and v→uv \to u holds. For a ranking rr of VV, an arc u→vu \to v is backward when rr puts vv above uu, and fas(r)\mathrm{fas}(r) is the number of backward arcs. Let OPTT\mathrm{OPT}_T be the least fas(r)\mathrm{fas}(r). A triangle is a set {u,v,w}\{u, v, w\} 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(V,T)(V, T) returns each member of VV exactly once. If the arcs of TT form a linear order, it returns that order.

Proof. By induction on ∣V∣|V|. Lines L3 and L4 put each u≠pu \ne p in exactly one of LL and RR, because exactly one of u→pu \to p and p→up \to u holds, and ∣L∣,∣R∣<∣V∣|L|, |R| < |V|. If TT is a linear order, the members of LL are above pp and those of RR below it, and by induction each side is returned in order.

Claim 2 (separation). For u≠vu \ne v, there is exactly one call in which uu and vv 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 u→vu \to v is backward in the output exactly when, in the call of Claim 2 for uu and vv, the pivot ww is neither of them and v→w→uv \to w \to u. So fas\mathrm{fas} of the output equals the number of triangles tt for which some call has all of tt in its list and a member of tt as its pivot. Call such a triangle hit.

Proof. If the pivot is uu, then vv goes right since u→vu \to v, and the arc is forward. If the pivot is vv, uu goes left, and the arc is forward. If the pivot ww is neither and the two go to different sides, then vv goes left and uu goes right exactly when v→wv \to w and w→uw \to u, and then u→v→w→uu \to v \to w \to u is a triangle. In that call all of {u,v,w}\{u, v, w\} are in the list and ww is the pivot. Conversely, if a triangle {u,v,w}\{u, v, w\} with u→v→w→uu \to v \to w \to u is in a list whose pivot is ww, then vv goes left and uu goes right, so u→vu \to v 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 uu and vv, 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). E[fas(KWIKSORT(V,T))]≤3⋅OPTT\mathbb{E}[\mathrm{fas}(\mathrm{KWIKSORT}(V, T))] \le 3 \cdot \mathrm{OPT}_T.

Proof. For a triangle tt, let qtq_t be the probability that tt is hit. Consider the first call whose pivot lies in tt, if any. Before it, tt 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 tt, each of the three members of tt is the pivot with probability 1/31/3. So for each member ww of tt, the probability that tt is hit with pivot ww is qt/3q_t / 3. Fix an arc e=(u,v)e = (u, v). By Claim 3, the event that t∋et \ni e is hit with the pivot opposite ee is the event that ee is made backward by that pivot in its separating call. There is only one separating call for ee, so these events are disjoint for the triangles that contain ee, and ∑t∋eqt/3≤1\sum_{t \ni e} q_t / 3 \le 1.

Let FF be the set of backward arcs of an optimal ranking. Every triangle has at least one arc in FF, since a ranking cannot follow all three arcs of a cycle. So

∑tqt3≤∑tqt3 ∣t∩F∣=∑e∈F∑t∋eqt3≤∣F∣=OPTT.\sum_t \frac{q_t}{3} \le \sum_t \frac{q_t}{3} \, |t \cap F| = \sum_{e \in F} \sum_{t \ni e} \frac{q_t}{3} \le |F| = \mathrm{OPT}_T.

By Claim 3, E[fas]=∑tqt≤3⋅OPTT\mathbb{E}[\mathrm{fas}] = \sum_t q_t \le 3 \cdot \mathrm{OPT}_T.

Claim 5 (Smith set on top). Let SS be a nonempty set with x→yx \to y for every x∈Sx \in S and y∉Sy \notin S. Then KWIKSORT ranks every member of SS 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 x∈Sx \in S and y∉Sy \notin S and their call from Claim 2. If the pivot is xx, yy goes right; if it is yy, xx goes left. If the pivot ww is neither, yy left and xx right would need y→wy \to w and w→xw \to x. If w∈Sw \in S, then w→yw \to y; if w∉Sw \notin S, then x→wx \to w. Both contradict this. So xx ends above yy. 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 r2r_2 of line L8 has K(r2)≤2⋅OPTK(r_2) \le 2 \cdot \mathrm{OPT}, so the output of line L9 does too.

Proof. Let dd be the Kendall tau distance, which is a metric, let π∗\pi^* be optimal, and let v1,…,vnv_1, \ldots, v_n be the ballots. Then K(vj)=∑id(vj,vi)≤∑i(d(vj,π∗)+d(π∗,vi))=n d(vj,π∗)+OPTK(v_j) = \sum_i d(v_j, v_i) \le \sum_i (d(v_j, \pi^*) + d(\pi^*, v_i)) = n \, d(v_j, \pi^*) + \mathrm{OPT}. The average of d(vj,π∗)d(v_j, \pi^*) over jj is OPT/n\mathrm{OPT}/n, so the average of K(vj)K(v_j) is at most 2⋅OPT2 \cdot \mathrm{OPT}, and the least K(vj)K(v_j) is not larger.

Claim 7 (time). AGGREGATE runs in O(nm2)O(n m^2) time and O(m2)O(m^2) space in the worst case.

Proof. The counts and the tournament take O(nm2)O(n m^2) time and O(m2)O(m^2) space. A call of KWIKSORT on a list of k≥2k \ge 2 members compares the pivot with the k−1k - 1 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 m(m−1)/2m(m - 1)/2 comparisons. There are at most mm calls with a pivot, and the lists of one level of the call tree are disjoint, so the other work is O(m2)O(m^2) too. Line L8 computes nn costs in O(m2)O(m^2) each, and line L9 two more. ■\blacksquare

Complexity

Counting NN takes O(nm2)O(n m^2) time, and line L8 also takes O(nm2)O(n m^2) to compute the cost of every ballot. KwikSort itself compares each pair at most once, so it makes at most m(m−1)/2m(m - 1)/2 comparisons. When the majority relation is a linear order, it is exactly randomized quicksort and makes O(mlog⁡m)O(m \log m) comparisons in expectation. The total is O(nm2)O(n m^2) time in the worst case on the word RAM, with O(m2)O(m^2) space for NN and TT. 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, E[K(KwikSort)]≤2⋅OPT\mathbb{E}[K(\mathrm{KwikSort})] \le 2 \cdot \mathrm{OPT}, and the better of KwikSort and Pick-A-Perm has expected cost at most 117⋅OPT\frac{11}{7} \cdot \mathrm{OPT}. 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 2⋅OPT2 \cdot \mathrm{OPT}. 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 O(nm2)O(n m^2) time. For very long lists, sample voters or count only the pairs that the sort compares.
  • Recursion depth. With bad luck the recursion is mm 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.

agtprefs.pyI0RawGitHub
# 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

  1. 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)
  2. 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.

LadderLevelWhat the next level needs
Human proofH1 sketch
  • a full proof of time.worst
  • a full proof of space.extra
LeanL0 no Lean part
  • name a Lean module in the lean field (07)
Code (python)I0 not checked yet
  • the tests did not run in this build
VisualV0 none
  • add viz/scene.ts or a figure (10)
WritingW2 basic
  • at least three sources
  • a scene preset for the example