Algorithm Search⌘K

Algorithmadvanced

Markov chain rank aggregation

Also called MC4 aggregation, Dwork-Kumar-Naor-Sivakumar aggregation.

Builds a Markov chain that moves from an item to one that a majority of rankings prefer, and ranks items by its stationary distribution.

Time
O(n^2 k + n^2 t) worst
Space
O(n^2 + n k) extra
Where
k = the number of lists; n = the number of distinct items in the input lists; t = the number of rounds of power iteration
Properties
not comparison baseddeterministiciterative
Origin
Cynthia Dwork, Ravi Kumar, Moni Naor, D. Sivakumar, 2001

Markov chain rank aggregation combines several ranked lists into one by a random walk on the items. Each list is a vote. The walk moves from an item to an item that the lists rank higher, and the final ranking orders the items by how much time the walk spends at each one in the long run, which is the stationary distribution of the Markov chain. Cynthia Dwork, Ravi Kumar, Moni Naor and D. Sivakumar defined four such chains, MC1 to MC4, in 2001 for metasearch, the rank aggregation of the result lists of several search engines. The same paper defines local Kemenization, a cheap clean-up pass that makes any aggregate agree with every strict majority on neighbouring items.

In plain words

Several search engines each give a ranked list of results. We want one list. Put a walker on one of the results. At each step the walker looks at another result and asks the lists which of the two is better. If most of the lists that show both results prefer the other one, the walker moves there, else it stays. Good results pull the walker in and keep it, so after many steps the walker is mostly at good results. We rank the results by how often the walker is at each one. To keep the walker from being stuck in a corner of the graph, it sometimes jumps to a random result, as in PageRank. A last pass then walks down the list and swaps any two neighbours when most lists prefer the lower one.

The problem

The input is kk ranked lists τ1,…,τk\tau_1, \ldots, \tau_k. Each list holds distinct items, best first, and it may be partial: a search engine returns only its top results, so two lists can hold different items. Let UU be the union of the items and n=∣U∣n = |U|. The output is one full ranking of UU. For a list τ\tau that holds xx, τ(x)\tau(x) is the rank of xx in it. Item QQ beats item PP, written Q≻PQ \succ P, when strictly more of the lists that hold both items put QQ above PP than put PP above QQ. A list that misses one of the two items does not vote on that pair.

The ideal answer is a Kemeny ranking, which minimizes the total Kendall tau distance to the lists. Finding it is NP-hard, as the Kemeny rank aggregation page explains, so this method gives a fast heuristic answer, with no bound on its distance from the Kemeny optimum.

The algorithm

Line L2 fills one row of the transition matrix MM for each item PP. The four chains differ only in the rule that picks the next state.

chain next state when the walk is at PP
MC1 an item chosen uniformly from the multiset of all items that some list holding PP ranks at or above PP
MC2 a list chosen uniformly among the lists that hold PP, then an item chosen uniformly among the items it ranks at or above PP
MC3 a list chosen uniformly among the lists that hold PP, then an item QQ chosen uniformly from that list; go to QQ if the list ranks QQ above PP, else stay at PP
MC4 an item QQ chosen uniformly from UU; go to QQ if Q≻PQ \succ P, else stay at PP

MC4 is the majority chain: it moves only along pairwise majorities. MC3 is the same walk with one list as the judge in place of the majority.

  1. MC-AGGREGATE(τ1, ..., τk, chain, ε)
  2. 1U ← the union of the items of τ1, ..., τk, in sorted order; n ← |U|
  3. 2for each P in U: fill row P of M by the move rule of chain
  4. 3M ← (1 - ε) M + (ε / n) J ▷ J is the n × n matrix of ones
  5. 4π ← (1/n, ..., 1/n)
  6. 5repeat π ← π M until the L1 change of π is below tol
  7. 6return U sorted by π, highest first, ties to the smaller item
  8. LOCAL-KEMENIZE(σ, τ1, ..., τk)
  9. 7for each x of σ, in order: append x to the end of ρ
  10. 8while x has an upper neighbour y in ρ and x ≻ y
  11. 9swap x and y in ρ
  12. return ρ

Line L3 is the teleport of PageRank: with probability ε\varepsilon the walk jumps to a uniform random item. Line L5 is power iteration. Lines L7 to L9 are insertion sort with the majority relation as the comparison, but ≻\succ need not be transitive, so the result is not a sorted order in general. The usual use is to run lines L7 to L9 on the output of line L6, or on the output of any other aggregation method.

Example

Take three items and five voters: three lists say a,b,ca, b, c and two lists say b,c,ab, c, a. The majorities are a≻ba \succ b (3 to 2), a≻ca \succ c (3 to 2) and b≻cb \succ c (5 to 0), so aa is the Condorcet winner, the item that beats every other item. The Borda count gives bb 12 points and aa 11, so it puts bb first.

For MC4, the walk at aa never moves, because nothing beats aa. At bb it moves to aa with probability 1/31/3. At cc it moves to aa or bb with probability 1/31/3 each. With ε=0.15\varepsilon = 0.15, line L3 gives the rows a:(9/10,1/20,1/20)a: (9/10, 1/20, 1/20), b:(1/3,37/60,1/20)b: (1/3, 37/60, 1/20) and c:(1/3,1/3,1/3)c: (1/3, 1/3, 1/3). The table shows the state of line L5 after each round, to 4 places.

round π(a)\pi(a) π(b)\pi(b) π(c)\pi(c)
0 0.3333 0.3333 0.3333
1 0.5222 0.3333 0.1444
2 0.6293 0.2798 0.0909
3 0.6899 0.2343 0.0758
4 0.7243 0.2042 0.0715
5 0.7438 0.1860 0.0702
6 0.7548 0.1753 0.0699
7 0.7611 0.1691 0.0698
8 0.7646 0.1656 0.0698
limit 10/13≈0.769210/13 \approx 0.7692 90/559≈0.161090/559 \approx 0.1610 3/43≈0.06983/43 \approx 0.0698

The order is a,b,ca, b, c from round 1 on, and it is the Kemeny ranking of this profile (total distance 4, against 5 for the Borda order b,a,cb, a, c). With ε=0\varepsilon = 0 all the mass ends at aa, and bb and cc both get 0. MC3 on the same lists, with ε=0.15\varepsilon = 0.15, has the stationary distribution (33/82,6517/14842,1176/7421)≈(0.4024,0.4391,0.1585)(33/82, 6517/14842, 1176/7421) \approx (0.4024, 0.4391, 0.1585) and gives b,a,cb, a, c, like Borda. Local Kemenization of b,a,cb, a, c inserts bb, then inserts aa and swaps it up because a≻ba \succ b, then inserts cc, which stays because b≻cb \succ c. The result is a,b,ca, b, c.

On the two runs of the toy collection for the query "sorted array search", the BM25 list 1,2,8,7,41, 2, 8, 7, 4 and the second list 1,6,8,2,41, 6, 8, 2, 4, MC4 with ε=0.15\varepsilon = 0.15 gives the exact stationary values π(1)=4/7\pi(1) = 4/7, π(6)=39072/215579≈0.1812\pi(6) = 39072/215579 \approx 0.1812, π(2)=π(8)=2580/30797≈0.0838\pi(2) = \pi(8) = 2580/30797 \approx 0.0838, π(7)=120/2369≈0.0507\pi(7) = 120/2369 \approx 0.0507 and π(4)=3/103≈0.0291\pi(4) = 3/103 \approx 0.0291. The order is 1,6,2,8,7,41, 6, 2, 8, 7, 4. Document 6 comes second although only one list holds it: that list puts it above 8, 2 and 4, and the other list does not vote on those pairs, so 6 beats each of them 1 to 0. Documents 2 and 8 tie because the two lists disagree on them.

Correctness

The file proofs/correctness.md proves four facts. Every row of MM is a probability distribution, for each of the four chains. For ε>0\varepsilon > 0, line L3 makes the map π↦πM\pi \mapsto \pi M shrink the L1L_1 distance between two distributions by the factor 1−ε1 - \varepsilon, so the stationary distribution is unique and the vectors of line L5 are within 2(1−ε)t2 (1 - \varepsilon)^t of it after tt rounds. With ε=0\varepsilon = 0 and a Condorcet winner, MC4 makes the winner absorbing and puts all the mass on it. On full lists, one round of MC3 from the uniform vector already gives the Borda order.

For lines L7 to L9 the invariant is that, after each insertion, no item of ρ\rho is directly below an item that it beats. Each swap of line L9 exchanges two neighbours of a full ranking with the lower one beating the upper one, so it lowers the total Kendall distance by at least 1. The output is therefore locally Kemeny optimal, it is never worse than its input, and it satisfies the extended Condorcet criterion: if every item of a set CC beats every item outside CC, the items of CC come first.

The method itself has no approximation guarantee for the Kemeny objective. Its order is the order of a stationary distribution, which is a different objective, and the toy example shows how far apart the two can be on partial lists.

Proof: The chains are stochastic, the teleported chain converges, and local Kemenization is locally optimalfull

Let τ1,…,τk\tau_1, \ldots, \tau_k be rankings of items from the union UU, with n=∣U∣n = |U|. A ranking may be partial. For a list τ\tau and an item xx in it, τ(x)\tau(x) is its rank, and "τ\tau puts QQ above PP" means τ(Q)<τ(P)\tau(Q) < \tau(P). Write Q≻PQ \succ P when strictly more of the lists that rank both PP and QQ put QQ above PP than put PP above QQ. The matrix MM is the one that line L2 builds, and Mε=(1−ε)M+(ε/n)JM_\varepsilon = (1 - \varepsilon) M + (\varepsilon / n) J is the matrix of line L3, where JJ is the n×nn \times n matrix of ones.

Lemma 1. For each of MC1 to MC4, every row of MM is a probability distribution.

Proof. The entries are sums of nonnegative terms, so it is enough to show that each row sums to 1. For MC1 the row of PP spreads weight 1/∣S∣1/|S| on each element of a nonempty multiset SS; SS holds PP itself, since each list that holds PP ranks PP at or above PP. For MC2 the row is the average, over the lists that hold PP, of a uniform distribution on a nonempty set. For MC3 the row is the average, over the lists that hold PP, of a distribution that sends each of the ∣τ∣|\tau| items QQ of τ\tau either to QQ or to PP, with weight 1/∣τ∣1/|\tau| each. For MC4 each of the nn items QQ sends weight 1/n1/n either to QQ or to PP. Each item of UU is in at least one list, so the set of lists that hold PP is never empty. □\square

The matrix MεM_\varepsilon is then stochastic too, because J/nJ/n is stochastic and the set of stochastic matrices is convex.

Lemma 2 (contraction). Let 0<ε≤10 < \varepsilon \le 1. For any two probability row vectors μ,ν\mu, \nu, ∥μMε−νMε∥1≤(1−ε)∥μ−ν∥1\lVert \mu M_\varepsilon - \nu M_\varepsilon \rVert_1 \le (1 - \varepsilon) \lVert \mu - \nu \rVert_1.

Proof. Let x=μ−νx = \mu - \nu. Its entries sum to 0, so xJ=0x J = 0 and xMε=(1−ε)xMx M_\varepsilon = (1 - \varepsilon) x M. For a stochastic MM, ∥xM∥1=∑j∣∑ixiMij∣≤∑i∣xi∣∑jMij=∥x∥1\lVert x M \rVert_1 = \sum_j |\sum_i x_i M_{ij}| \le \sum_i |x_i| \sum_j M_{ij} = \lVert x \rVert_1. □\square

Theorem 1. For 0<ε≤10 < \varepsilon \le 1, MεM_\varepsilon has exactly one stationary distribution π\pi, and the vectors πt\pi_t of line L5, started from the uniform vector of line L4, satisfy ∥πt−π∥1≤2(1−ε)t\lVert \pi_t - \pi \rVert_1 \le 2 (1 - \varepsilon)^t.

Proof. The set of probability vectors with the L1L_1 distance is complete, and by Lemma 2 the map μ↦μMε\mu \mapsto \mu M_\varepsilon is a contraction on it. By the Banach fixed point theorem it has exactly one fixed point π\pi, which is a stationary distribution, and no other stationary distribution exists. Since πMε=π\pi M_\varepsilon = \pi, Lemma 2 gives ∥πt−π∥1≤(1−ε)t∥π0−π∥1≤2(1−ε)t\lVert \pi_t - \pi \rVert_1 \le (1 - \varepsilon)^t \lVert \pi_0 - \pi \rVert_1 \le 2 (1 - \varepsilon)^t. □\square

So line L5 stops after at most ⌈ln⁡(2/tol)/ε⌉+1\lceil \ln(2/\mathrm{tol}) / \varepsilon \rceil + 1 steps, since (1−ε)t≤e−εt(1 - \varepsilon)^t \le e^{-\varepsilon t}, and the order of line L6 is the order of the unique π\pi, up to items whose probabilities differ by less than the error.

Theorem 2 (MC4 and a Condorcet winner). Take ε=0\varepsilon = 0 and the chain MC4. Suppose some item ww satisfies w≻yw \succ y for every y≠wy \ne w. Then ww is absorbing, the stationary distribution is unique and equal to the unit vector ewe_w, and power iteration from any start converges to it.

Proof. From ww, a move to Q≠wQ \ne w needs Q≻wQ \succ w, which fails because w≻Qw \succ Q and the relation is asymmetric. So the row of ww is ewe_w. From any P≠wP \ne w, the chain picks Q=wQ = w with probability 1/n1/n and then moves, because w≻Pw \succ P. So for any distribution μ\mu, the mass off ww after one step is at most (1−1/n)(1 - 1/n) times the mass off ww before: mass at ww stays, and each state P≠wP \ne w sends at least μP/n\mu_P / n to ww. After tt steps the mass off ww is at most (1−1/n)t(1 - 1/n)^t, which tends to 0. A stationary π\pi is its own image after tt steps for each tt, so its mass off ww is 0, and π=ew\pi = e_w. □\square

Theorem 3 (MC3 after one step). Let all kk lists be full rankings of UU, and let R(Q)=∑l=1kτl(Q)R(Q) = \sum_{l=1}^{k} \tau_l(Q) be the total rank of QQ. For MC3 with ε=0\varepsilon = 0, one step from the uniform vector gives

π1(Q)=1n(1+k(n+1)−2R(Q)kn).\pi_1(Q) = \frac{1}{n} \left( 1 + \frac{k(n + 1) - 2 R(Q)}{k n} \right).

So the order of π1\pi_1 is the order of increasing total rank, which is the Borda order.

Proof. Each list holds each item. From P≠QP \ne Q, the chain moves to QQ when it picks a list τ\tau (probability 1/k1/k) with τ(Q)<τ(P)\tau(Q) < \tau(P) and then picks QQ (probability 1/n1/n). So MPQ=∣{l:τl(Q)<τl(P)}∣/(kn)M_{PQ} = |\{l : \tau_l(Q) < \tau_l(P)\}| / (k n). Summing over P≠QP \ne Q counts, for each list, the items below QQ: ∑P≠QMPQ=∑l(n−τl(Q))/(kn)\sum_{P \ne Q} M_{PQ} = \sum_l (n - \tau_l(Q)) / (k n). The chain leaves QQ for R′R' when it picks a list with τ(R′)<τ(Q)\tau(R') < \tau(Q) and then R′R', so 1−MQQ=∑l(τl(Q)−1)/(kn)1 - M_{QQ} = \sum_l (\tau_l(Q) - 1)/(k n). Then π1(Q)=1n(∑P≠QMPQ+MQQ)=1n(1+∑l(n+1−2τl(Q))/(kn))\pi_1(Q) = \frac{1}{n} (\sum_{P \ne Q} M_{PQ} + M_{QQ}) = \frac{1}{n} (1 + \sum_l (n + 1 - 2 \tau_l(Q))/(k n)), which is the formula. □\square

Lemma 3 (one swap). Let σ\sigma be a ranking of UU in which yy is directly above xx, and let σ′\sigma' be σ\sigma with the two swapped. Then K(σ′,τ1,…,τk)=K(σ,τ1,…,τk)−a+bK(\sigma', \tau_1, \ldots, \tau_k) = K(\sigma, \tau_1, \ldots, \tau_k) - a + b, where KK is the sum over the lists of the number of pairs that both rank in opposite orders, aa is the number of lists that rank both and put xx above yy, and bb the number that put yy above xx.

Proof. The swap changes the relative order of the pair {x,y}\{x, y\} only. Every other pair keeps its order in σ′\sigma', so its disagreements do not change. The pair {x,y}\{x, y\} was a disagreement for the aa lists before the swap and is one for the bb lists after. □\square

So x≻yx \succ y means exactly that the swap lowers KK. A ranking is locally Kemeny optimal when no swap of two neighbours lowers KK, that is, when no item is directly below an item that it beats.

Theorem 4 (local Kemenization). Lines L7 to L9 return a permutation ρ\rho of the input order σ\sigma such that (a) ρ\rho is locally Kemeny optimal, (b) K(ρ)≤K(σ)K(\rho) \le K(\sigma), and (c) if C⊂UC \subset U is a nonempty proper subset with x≻yx \succ y for all x∈Cx \in C and y∉Cy \notin C, then the items of CC are the first ∣C∣|C| items of ρ\rho.

Proof. (a) Invariant: after the step that inserts the mm-th item of σ\sigma, the output list holds the first mm items of σ\sigma and no item of it is directly below an item that it beats. It holds after the first step. Assume it before the insertion of xx. The new item starts at the bottom and moves up only past a neighbour that it beats. When it stops, its upper neighbour uu (if any) is not beaten by xx. Its lower neighbour vv (if any) is the item it passed last, so x≻vx \succ v and, by asymmetry, vv does not beat xx. The pair (u,v)(u, v) is no longer adjacent. All other adjacent pairs were adjacent before, in the same order, so the invariant holds.

(b) Consider the full ranking that has the current output list on top and the items of σ\sigma not yet inserted below it, in the order of σ\sigma. At the start it is σ\sigma, and at the end it is ρ\rho. Appending the next item does not change it. Each swap in line L9 exchanges two neighbours of this full ranking, with the lower one beating the upper one, so by Lemma 3 it lowers KK by b−a≥1b - a \ge 1.

(c) Suppose not. Then some y∉Cy \notin C is above some x∈Cx \in C in ρ\rho. Walk down ρ\rho from yy to xx: the walk starts outside CC and ends inside CC, so at some step an item y′∉Cy' \notin C is directly above an item x′∈Cx' \in C. By hypothesis x′≻y′x' \succ y', which contradicts (a). □\square

Each of the four theorems is checked on random small inputs in impl/python/test_markov_chain_rank_aggregation.py, with Theorem 1 compared against an exact solve of πMε=π\pi M_\varepsilon = \pi over the rationals.

Complexity

Line L2 takes O(n2k)O(n^2 k) time for each of the four chains with a position map for each list: MC4 asks each list about each pair of items, and MC1 to MC3 scan, for each item, the lists that hold it. Each round of line L5 is a vector times a dense n×nn \times n matrix, O(n2)O(n^2) time. By the contraction bound, t≤⌈ln⁡(2/tol)/ε⌉+1t \le \lceil \ln(2/\mathrm{tol}) / \varepsilon \rceil + 1 rounds reach the tolerance, so with ε=0.15\varepsilon = 0.15 and tol=10−12\mathrm{tol} = 10^{-12} at most 190 rounds are needed. Line L6 sorts in O(nlog⁡n)O(n \log n). The total is O(n2k+n2t)O(n^2 k + n^2 t) time and O(n2+nk)O(n^2 + n k) extra space for the matrix and the position maps. Lines L7 to L9 make O(n2)O(n^2) comparisons in the worst case, each a count over the kk lists, so O(n2k)O(n^2 k) time as written; the paper notes a faster way that uses O(nlog⁡n)O(n \log n) comparisons.

Properties

  • Majority driven. MC4 depends on the lists only through the majority relation ≻\succ. Two profiles with the same majorities give the same chain, however large the margins are.
  • Condorcet consistent at ε=0\varepsilon = 0. A Condorcet winner takes all the mass. With ε>0\varepsilon > 0 it gets the largest share in the examples above, but the theorem covers only ε=0\varepsilon = 0.
  • Handles partial lists. No chain needs a full ranking. A list votes only on items that it holds.
  • Deterministic. The chain and the tie rule of line L6 depend only on the input. The walk is a way to define the scores; nothing in the computation is random.
  • Not a metric optimum. The output need not minimize the Kendall or the footrule distance, and Dwork and coauthors note that the chains need not satisfy the extended Condorcet criterion, which is why the paper adds local Kemenization.

Variants and improvements

  • MC1 to MC3. These chains move to an item that one list ranks higher, with no majority vote. MC1 favours items that many lists hold near the top, and MC3 behaves like a smoothed Borda count, as the one-step result shows.
  • Missing items below. A common change is to treat an item that a list misses as ranked below every item it holds. Then that list votes on the pair. On the toy runs this gives 1,2,8,6,4,71, 2, 8, 6, 4, 7, the Borda order, and document 6 no longer climbs on a one-list majority.
  • Footrule aggregation. The ranking that minimizes the total Spearman footrule distance to full lists is a minimum weight perfect matching of items to positions, so it can be found in polynomial time, and it is within a factor 2 of the Kemeny optimum by the Diaconis-Graham inequality. The paper uses it as another starting point for local Kemenization.
  • Exact stationary vector. For small nn, solving πM=π\pi M = \pi with ∑π=1\sum \pi = 1 by Gaussian elimination gives π\pi directly. The test file does this in rational numbers as the reference.
  • Other fusion methods. Reciprocal rank fusion and CombMNZ are linear time and need no matrix; they are the common choices when only speed matters.

When to use it

Use MC4 when the lists come from systems whose scores cannot be compared, when you care about pairwise majorities more than about rank positions, and when the number of items to merge is small enough for an n×nn \times n matrix, a few hundred to a few thousand. Run local Kemenization on the result, or on the output of any cheaper method, when one bad list must not lift an item above the item that most lists prefer. For large lists of web results, a positional method such as Borda or reciprocal rank fusion is simpler and faster.

Pitfalls

  • A majority of one list. The MC4 rule of line L2 counts only the lists that hold both items. An item that appears in one list only beats every item that this list ranks below it, as document 6 does in the toy example. If missing items should count as poor, change line L2 so that a list votes QQ over PP when it holds QQ and not PP, as in the variant above.
  • No teleport. With ε=0\varepsilon = 0, line L3 does nothing, the chain is usually reducible, and line L5 can converge to a vector with many zeros. The order of the items with probability 0 is then only the tie rule of line L6: the toy runs at ε=0\varepsilon = 0 give 1,2,4,6,7,81, 2, 4, 6, 7, 8, which is document 1 followed by the documents in id order. Keep ε>0\varepsilon > 0, or use the zero entries only to find the top item.
  • Rounding splits ties. Documents 2 and 8 have the same exact probability, but power iteration gives two floats that can differ in the last bits. Sorting the raw floats in line L6 then orders them by noise. Round the probabilities to well above the tolerance, or compare exact values, before the sort.
  • Quadratic memory. The dense matrix of line L2 has n2n^2 entries. Merge only the top of each list, or store MC4 as the majority relation and compute each row when it is needed.
  • Local Kemenization keeps the input order. Lines L7 to L9 only repair neighbours. Two items that no majority links stay in the order of the input, so the result still depends on the method that produced it.

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.

markov_chain_rank_aggregation.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/markov-chain-rank-aggregation/. The authors are listed in prov/DF298Z.jsonl.

from fractions import Fraction
from typing import Any, Hashable, Sequence

Ranking = Sequence[Hashable]


def _union(rankings: Sequence[Ranking]) -> list[Any]:
    items = set()
    for r in rankings:
        items.update(r)
    return sorted(items)


def transition_matrix(rankings: Sequence[Ranking], chain: str = "MC4", exact: bool = False) -> tuple[list[Any], list[list[Any]]]:
    """Return (items, M), where M[i][j] is the probability that the chain moves from items[i] to items[j].

    Each ranking lists distinct items, best first, and may be partial. The chains are
    MC1 to MC4 of Dwork, Kumar, Naor and Sivakumar (2001), with no teleport. With
    exact=True the entries are Fractions, else floats.
    """
    one = Fraction(1) if exact else 1.0
    items = _union(rankings)  # @line L1
    n = len(items)
    idx = {x: i for i, x in enumerate(items)}
    pos = [{x: i + 1 for i, x in enumerate(r)} for r in rankings]
    m = [[0 * one for _ in range(n)] for _ in range(n)]
    for p in items:  # @line L2
        i = idx[p]
        lists_p = [t for t in pos if p in t]
        if chain == "MC1":
            pool = [q for t in lists_p for q in t if t[q] <= t[p]]
            for q in pool:
                m[i][idx[q]] += one / len(pool)
        elif chain == "MC2":
            for t in lists_p:
                above = [q for q in t if t[q] <= t[p]]
                for q in above:
                    m[i][idx[q]] += one / len(lists_p) / len(above)
        elif chain == "MC3":
            for t in lists_p:
                for q in t:
                    target = q if t[q] < t[p] else p
                    m[i][idx[target]] += one / len(lists_p) / len(t)
        elif chain == "MC4":
            for q in items:
                both = [t for t in pos if p in t and q in t]
                wins = sum(1 for t in both if t[q] < t[p])
                target = q if q != p and 2 * wins > len(both) else p
                m[i][idx[target]] += one / n
        else:
            raise ValueError("chain must be MC1, MC2, MC3 or MC4")
    return items, m


def teleport(m: list[list[Any]], eps: Any) -> list[list[Any]]:
    """Return (1 - eps) M + eps J / n, the chain that jumps to a uniform state with probability eps."""
    n = len(m)
    return [[(1 - eps) * m[i][j] + eps / n for j in range(n)] for i in range(n)]  # @line L3


def stationary(m: list[list[float]], tol: float = 1e-12, max_iter: int = 100000) -> list[float]:
    """Power iteration from the uniform distribution, until the L1 change is below tol."""
    n = len(m)
    pi = [1.0 / n] * n  # @line L4
    for _ in range(max_iter):
        new = [sum(pi[i] * m[i][j] for i in range(n)) for j in range(n)]  # @line L5
        if sum(abs(a - b) for a, b in zip(new, pi)) < tol:
            return new
        pi = new
    return pi


def aggregate(rankings: Sequence[Ranking], chain: str = "MC4", eps: float = 0.15) -> list[Any]:
    """Rank the items of the union by the stationary probability of the chain, high first, ties by item.

    The probabilities are rounded to 10 decimals before the sort, so that two states with
    the same exact probability are not split by rounding noise of the power iteration.
    """
    items, m = transition_matrix(rankings, chain)
    pi = stationary(teleport(m, eps) if eps > 0 else m)
    order = sorted(range(len(items)), key=lambda i: (-round(pi[i], 10), items[i]))  # @line L6
    return [items[i] for i in order]


def _prefers(pos: Sequence[dict], x: Hashable, y: Hashable) -> bool:
    over = sum(1 for t in pos if x in t and y in t and t[x] < t[y])
    under = sum(1 for t in pos if x in t and y in t and t[y] < t[x])
    return over > under


def prefers(rankings: Sequence[Ranking], x: Hashable, y: Hashable) -> bool:
    """True when strictly more of the rankings that hold both x and y put x above y than y above x."""
    return _prefers([{z: i for i, z in enumerate(r)} for r in rankings], x, y)


def local_kemenize(order: Sequence[Hashable], rankings: Sequence[Ranking]) -> list[Any]:
    """Insertion sort of order where an item moves up past its upper neighbour only when a strict majority prefers it."""
    pos = [{z: i for i, z in enumerate(r)} for r in rankings]
    out: list[Any] = []
    for x in order:  # @line L7
        out.append(x)
        j = len(out) - 1
        while j > 0 and _prefers(pos, out[j], out[j - 1]):  # @line L8
            out[j - 1], out[j] = out[j], out[j - 1]  # @line L9
            j -= 1
    return out
test_markov_chain_rank_aggregation.py 228 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/markov-chain-rank-aggregation/. The authors are listed in prov/DF298Z.jsonl.

import itertools
import random
from fractions import Fraction

from markov_chain_rank_aggregation import (
    aggregate,
    local_kemenize,
    prefers,
    stationary,
    teleport,
    transition_matrix,
)

CHAINS = ("MC1", "MC2", "MC3", "MC4")


def exact_stationary(m):
    """Solve pi M = pi with sum(pi) = 1 by Gaussian elimination over Fractions. None if not unique."""
    n = len(m)
    # Equations: for each j, sum_i pi_i (M[i][j] - [i == j]) = 0; replace the last by sum pi = 1.
    a = [[m[i][j] - (1 if i == j else 0) for i in range(n)] + [Fraction(0)] for j in range(n)]
    a[n - 1] = [Fraction(1)] * n + [Fraction(1)]
    for c in range(n):
        p = next((r for r in range(c, n) if a[r][c] != 0), None)
        if p is None:
            return None
        a[c], a[p] = a[p], a[c]
        for r in range(n):
            if r != c and a[r][c] != 0:
                f = a[r][c] / a[c][c]
                a[r] = [x - f * y for x, y in zip(a[r], a[c])]
    return [a[i][n] / a[i][i] for i in range(n)]


def random_profile(rng, n, k, partial):
    items = list(range(1, n + 1))
    out = []
    for _ in range(k):
        r = items[:]
        rng.shuffle(r)
        if partial:
            r = r[: rng.randint(1, n)]
        out.append(r)
    return out


def kendall(sigma, tau):
    """Pairs ranked by both lists in opposite orders."""
    ps = {x: i for i, x in enumerate(sigma)}
    pt = {x: i for i, x in enumerate(tau)}
    common = [x for x in sigma if x in pt]
    return sum(1 for x, y in itertools.combinations(common, 2) if (ps[x] - ps[y]) * (pt[x] - pt[y]) < 0)


def footrule(sigma, tau):
    pt = {x: i for i, x in enumerate(tau)}
    return sum(abs(i - pt[x]) for i, x in enumerate(sigma))


def total(dist, sigma, profile):
    return sum(dist(sigma, t) for t in profile)


def test_rows_are_distributions():
    rng = random.Random(1)
    for _ in range(200):
        prof = random_profile(rng, rng.randint(1, 6), rng.randint(1, 4), partial=True)
        for c in CHAINS:
            _, m = transition_matrix(prof, c, exact=True)
            for row in m:
                assert sum(row) == 1 and min(row) >= 0


def test_power_iteration_matches_exact_solve():
    rng = random.Random(2)
    eps = Fraction(3, 20)
    for _ in range(120):
        prof = random_profile(rng, rng.randint(2, 5), rng.randint(1, 4), partial=rng.random() < 0.5)
        for c in CHAINS:
            _, mx = transition_matrix(prof, c, exact=True)
            _, mf = transition_matrix(prof, c)
            pi_exact = exact_stationary(teleport(mx, eps))
            pi_float = stationary(teleport(mf, 0.15))
            assert pi_exact is not None
            assert sum(pi_exact) == 1
            for a, b in zip(pi_exact, pi_float):
                assert abs(float(a) - b) < 1e-9


def test_mc4_condorcet_winner_takes_all_mass():
    rng = random.Random(3)
    seen = 0
    for _ in range(300):
        n = rng.randint(2, 5)
        prof = random_profile(rng, n, rng.choice([1, 3, 5]), partial=False)
        items = sorted(prof[0])
        winners = [w for w in items if all(prefers(prof, w, y) for y in items if y != w)]
        if not winners:
            continue
        seen += 1
        w = winners[0]
        its, m = transition_matrix(prof, "MC4", exact=True)
        i = its.index(w)
        assert m[i][i] == 1
        pi = exact_stationary(m)
        assert pi == [Fraction(1) if j == i else Fraction(0) for j in range(n)]
    assert seen > 100


def test_mc3_one_step_from_uniform_is_borda_order():
    rng = random.Random(4)
    for _ in range(200):
        n, k = rng.randint(2, 6), rng.randint(1, 5)
        prof = random_profile(rng, n, k, partial=False)
        items, m = transition_matrix(prof, "MC3", exact=True)
        step = [sum(Fraction(1, n) * m[i][j] for i in range(n)) for j in range(n)]
        for j, x in enumerate(items):
            rank_sum = sum(r.index(x) + 1 for r in prof)
            assert step[j] == Fraction(1, n) * (1 + Fraction(k * (n + 1) - 2 * rank_sum, k * n))


def kemeny_costs(prof, perms):
    """Total Kendall distance of each permutation to the full lists of prof."""
    pos = [{x: i for i, x in enumerate(r)} for r in prof]
    items = sorted(prof[0])
    w = {(x, y): sum(1 for t in pos if t[x] < t[y]) for x in items for y in items}
    n = len(items)
    return [sum(w[p[j], p[i]] for i in range(n) for j in range(i + 1, n)) for p in perms]


def footrule_costs(prof, perms):
    pos = [{x: i for i, x in enumerate(r)} for r in prof]
    return [sum(abs(i - t[x]) for t in pos for i, x in enumerate(p)) for p in perms]


def test_kemeny_costs_agree_with_kendall():
    rng = random.Random(8)
    for _ in range(20):
        prof = random_profile(rng, rng.randint(1, 5), rng.randint(1, 4), partial=False)
        perms = list(itertools.permutations(sorted(prof[0])))
        assert kemeny_costs(prof, perms) == [total(kendall, p, prof) for p in perms]
        assert footrule_costs(prof, perms) == [total(footrule, p, prof) for p in perms]


def test_condorcet_ranking_is_the_unique_kemeny_ranking():
    rng = random.Random(5)
    seen = 0
    for _ in range(150):
        n = rng.randint(2, 6)
        prof = random_profile(rng, n, rng.choice([1, 3, 5, 7]), partial=False)
        items = sorted(prof[0])
        beats = {(x, y): prefers(prof, x, y) for x in items for y in items}
        perms = list(itertools.permutations(items))
        cond = [p for p in perms if all(beats[p[i], p[j]] for i in range(n) for j in range(i + 1, n))]
        if not cond:
            continue
        seen += 1
        cost = kemeny_costs(prof, perms)
        best = min(cost)
        assert [p for p, c in zip(perms, cost) if c == best] == cond
    assert seen > 30


def test_footrule_optimum_is_a_two_approximation_of_kemeny():
    rng = random.Random(6)
    for _ in range(60):
        n = rng.randint(2, 6)
        prof = random_profile(rng, n, rng.randint(1, 5), partial=False)
        perms = list(itertools.permutations(sorted(prof[0])))
        kc, fc = kemeny_costs(prof, perms), footrule_costs(prof, perms)
        kem, fbest = min(kc), min(fc)
        for k_cost, f_cost in zip(kc, fc):
            assert k_cost <= f_cost <= 2 * k_cost  # Diaconis and Graham, summed over the lists
            if f_cost == fbest:
                assert k_cost <= 2 * kem


def test_local_kemenization():
    rng = random.Random(7)
    for _ in range(300):
        n = rng.randint(1, 7)
        prof = random_profile(rng, n, rng.randint(1, 5), partial=rng.random() < 0.5)
        start = sorted({x for r in prof for x in r})
        rng.shuffle(start)
        out = local_kemenize(start, prof)
        assert sorted(out) == sorted(start)
        # Locally Kemeny optimal: no adjacent swap lowers the total Kendall distance.
        for i in range(len(out) - 1):
            assert not prefers(prof, out[i + 1], out[i])
        assert total(kendall, out, prof) <= total(kendall, start, prof)
        # Extended Condorcet: if every item of a top set beats every other item, the set comes first.
        for size in range(1, len(out)):
            for top in itertools.combinations(sorted(out), size):
                rest = [y for y in out if y not in top]
                if all(prefers(prof, x, y) for x in top for y in rest):
                    assert set(out[:size]) == set(top)


def test_extended_procedure_on_the_page_example():
    prof = [list("abc")] * 3 + [list("bca")] * 2
    assert aggregate(prof, "MC4", eps=0.0)[0] == "a"
    assert aggregate(prof, "MC4", eps=0.15) == list("abc")
    assert aggregate([list("bc")] * 3 + [list("bc")] * 2, "MC4", eps=0.0) == list("bc")
    assert local_kemenize(list("bac"), prof) == list("abc")


def test_toy_runs():
    bm25 = [1, 2, 8, 7, 4]
    run = [1, 6, 8, 2, 4]
    # Document 6 is in one list only, so it beats 2, 8 and 4 by a "majority" of one list.
    assert aggregate([bm25, run], "MC4", eps=0.15) == [1, 6, 2, 8, 7, 4]
    items, m = transition_matrix([bm25, run], "MC4", exact=True)
    pi = exact_stationary(teleport(m, Fraction(3, 20)))
    assert dict(zip(items, pi)) == {1: Fraction(4, 7), 2: Fraction(2580, 30797), 4: Fraction(3, 103), 6: Fraction(39072, 215579), 7: Fraction(120, 2369), 8: Fraction(2580, 30797)}
    # With no teleport, document 1 is a Condorcet winner and holds all the mass.
    assert aggregate([bm25, run], "MC4", eps=0.0) == [1, 2, 4, 6, 7, 8]


def test_five_voter_profile_mc3_against_mc4():
    prof = [list("abc")] * 3 + [list("bca")] * 2
    assert aggregate(prof, "MC3", eps=0.0) == list("bac")
    _, m = transition_matrix(prof, "MC3", exact=True)
    assert exact_stationary(m) == [Fraction(3, 7), Fraction(13, 28), Fraction(3, 28)]
    _, m = transition_matrix(prof, "MC4", exact=True)
    assert exact_stationary(teleport(m, Fraction(3, 20))) == [Fraction(10, 13), Fraction(90, 559), Fraction(3, 43)]

History

Dwork, Kumar, Naor and Sivakumar presented rank aggregation for the web at the WWW10 conference in Hong Kong in 2001. Their aim was a metasearch engine that resists spam: a page that tricks one search engine should not reach the top of the merged list. The paper proves that the Kemeny ranking is NP-hard to find already for four lists, which motivated the cheap chains. It defines MC1 to MC4 as heuristics, compares them with Borda and footrule aggregation on the results of real search engines, and introduces local Kemenization and the extended Condorcet criterion. The paper builds the chains without a jump; the teleport of line L3 is the standard repair, taken from PageRank, that later uses of these chains add to make the stationary distribution unique.

References

  1. Cynthia Dwork, Ravi Kumar, Moni Naor and D. Sivakumar, Rank aggregation methods for the Web, Proceedings of the 10th International World Wide Web Conference (WWW10), 613-622, the Markov chain methods MC1 to MC4, the definition of local Kemenization and the extended Condorcet criterion, and the NP-hardness of Kemeny aggregation for four lists
  2. Cynthia Dwork, Ravi Kumar, Moni Naor and D. Sivakumar, Rank aggregation revisited, manuscript (2001), the longer version of the WWW10 paper, with the proofs on local Kemenization and on the footrule as an approximation of the Kendall distance

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