Algorithm Search⌘K

Algorithmresearch

Minimal test collection

Also called Carterette-Allan-Sitaraman method.

Judges pooled documents one at a time, each chosen for how much it can tighten bounds on the difference in average precision, and stops once the sign of that difference is fixed.

Time
O(m^3) worst
Space
O(m^2) extra
Where
m = the number of documents in either ranking
Properties
deterministiciterative

A minimal test collection is a set of relevance judgments that is just large enough to decide which of two retrieval systems has the higher average precision on a query. Carterette, Allan and Sitaraman introduced the method in 2006. It writes the difference in average precision as a sum over pairs of documents, keeps a lower and an upper bound on that sum over all relevance values of the documents not yet judged, and asks the assessor to judge the document that can move a bound the most. When the lower bound is above 0 or the upper bound is below 0, the sign of the difference is known, and the rest of the pool need not be judged.

In plain words

You want to know which of two search engines is better on a query, and judging each result costs time. You do not need the exact scores of the engines, only which one is higher.

Look at the results that the two engines rank in different places. A result that one engine puts near the top and the other puts low can change the comparison a lot, so judge it first. A result that both engines rank in the same place can change the comparison only a little, so it is judged late or never.

After each judgment, work out the best and the worst case for the comparison over every way the remaining results could turn out. When even the worst case says that one engine is better, stop.

The problem

The input is two rankings AA and BB for one query, and an assessor who returns xd=1x_d = 1 if document dd is relevant and 0 if not. Let PP be the mm documents in AA or BB, and RR the number of relevant documents in the collection. The output is the sign of AP(A)−AP(B)\mathrm{AP}(A) - \mathrm{AP}(B) and the list of documents judged, with the guarantee that the sign is the same for every relevance of the documents not judged. The goal is to judge few documents.

For a document ii at rank rA(i)r_A(i) of AA, let aii=1/rA(i)a_{ii} = 1 / r_A(i), and for two documents of AA let aij=1/max⁡(rA(i),rA(j))a_{ij} = 1 / \max(r_A(i), r_A(j)); let aij=0a_{ij} = 0 when one of them is not in AA. Define bijb_{ij} for BB in the same way, and cij=aij−bijc_{ij} = a_{ij} - b_{ij}. Then

R (AP(A)−AP(B))=D=∑i≤jcijxixj,R \, (\mathrm{AP}(A) - \mathrm{AP}(B)) = D = \sum_{i \le j} c_{ij} x_i x_j,

because a relevant document ii adds its precision at its rank, and that precision counts each relevant document jj ranked at or above ii with weight 1/r(i)1 / r(i). Relevant documents outside PP change RR but not the sign of DD.

The algorithm

Let SS be the documents judged relevant, NN those judged not relevant, and TT those not judged. A pair with a document in NN adds 0 to DD, and a pair inside SS adds cijc_{ij}. Every other pair lies in the set FF of pairs that are still open; it adds 00 or cijc_{ij}. So with K=∑i,j∈ScijK = \sum_{i, j \in S} c_{ij},

lo=K+∑Fmin⁡(0,cij)≤D≤K+∑Fmax⁡(0,cij)=hi.\mathrm{lo} = K + \sum_{F} \min(0, c_{ij}) \le D \le K + \sum_{F} \max(0, c_{ij}) = \mathrm{hi}.

For i∈Ti \in T, let wiRw^R_i and wiNw^N_i be the rise of lo if ii is judged relevant or not relevant, and viRv^R_i and viNv^N_i the fall of hi in the same two cases.

  1. MINIMAL-TEST-COLLECTION(A, B, judge, p)
  2. 1c_ij ← a_ij - b_ij for all documents i ≤ j of A ∪ B
  3. 2S ← ∅, N ← ∅, T ← the documents of A ∪ B
  4. 3loop
  5. 4lo, hi ← the bounds on D given S, N and T
  6. 5if lo > 0 return A, S ∪ N; if hi < 0 return B, S ∪ N; if lo = hi return tie, S ∪ N
  7. 6if the budget is used return undecided, S ∪ N
  8. 7for each i ∈ T do
  9. 8s_i ← max(p·w^R_i, (1 - p)·w^N_i, p·v^R_i, (1 - p)·v^N_i)
  10. 9i* ← the i ∈ T with the largest s_i, ties to the smallest id
  11. 10if judge(i*) = 1 then move i* from T to S else move i* from T to N

The weights have short forms. Judging ii relevant closes the pairs of ii with SS and with itself, so wiR=∑j∈S∪{i}max⁡(0,cij)w^R_i = \sum_{j \in S \cup \{i\}} \max(0, c_{ij}) and viR=∑j∈S∪{i}max⁡(0,−cij)v^R_i = \sum_{j \in S \cup \{i\}} \max(0, -c_{ij}). Judging ii not relevant sets all its open pairs to 0, so wiN=∑j∈S∪Tmax⁡(0,−cij)w^N_i = \sum_{j \in S \cup T} \max(0, -c_{ij}) and viN=∑j∈S∪Tmax⁡(0,cij)v^N_i = \sum_{j \in S \cup T} \max(0, c_{ij}). Carterette, Allan and Sitaraman state the rule of line L8 for one direction: to show that AA is better, judge the document with the largest max⁡(p wiR,(1−p) wiN)\max(p \, w^R_i, (1 - p) \, w^N_i), with p=0.5p = 0.5 when nothing is known about the document. The sign is not known in advance, so line L8 here takes the maximum over both directions.

Example

Take query q1 "sorted array search" of the toy collection of this area, with documents 1, 2 and 8 relevant, and the scores of its run: documents 1 and 6 tie at 2.0, document 8 has 1.5, and documents 2 and 4 tie at 1.0. Breaking the ties in two ways gives two rankings: A=(1,6,8,2,4)A = (1, 6, 8, 2, 4) by increasing id, and B=(6,1,8,4,2)B = (6, 1, 8, 4, 2) by decreasing id, which is the order trec_eval uses for ties. Their average precisions are 29/36=0.805629/36 = 0.8056 and 53/90=0.588953/90 = 0.5889. The nonzero coefficients are c11=1/2c_{11} = 1/2, c66=−1/2c_{66} = -1/2, c22=c26=c28=c12=1/20c_{22} = c_{26} = c_{28} = c_{12} = 1/20, and c44=c46=c48=c14=−1/20c_{44} = c_{46} = c_{48} = c_{14} = -1/20. Document 8 is at rank 3 in both, so c88=0c_{88} = 0, and the pair (1,6)(1, 6) has c16=1/2−1/2=0c_{16} = 1/2 - 1/2 = 0.

step S N lo hi s1s_1 s2s_2 s4s_4 s6s_6 s8s_8 judged
1 -7/10 7/10 11/40 1/10 1/10 11/40 1/40 1: relevant
2 1 -1/5 7/10 1/10 1/10 11/40 1/40 6: not relevant
3 1 6 7/20 13/20 stop: A

In step 1, documents 1 and 6 tie, and the smaller id wins. After two judgments lo=7/20>0\mathrm{lo} = 7/20 > 0, so AA is better whatever documents 2, 4 and 8 turn out to be. The true value is D=3 (29/36−53/90)=13/20D = 3 \, (29/36 - 53/90) = 13/20, which here equals hi. Two of the five pooled documents were enough: the comparison depends only on the order of the tied documents, and documents 1 and 6 are the ones whose order differs the most.

Correctness

The proof is in proofs/correctness.md. The identity D=R (AP(A)−AP(B))D = R \, (\mathrm{AP}(A) - \mathrm{AP}(B)) holds for every relevance vector, and every open pair lies between min⁡(0,cij)\min(0, c_{ij}) and max⁡(0,cij)\max(0, c_{ij}), so lo≤D≤hi\mathrm{lo} \le D \le \mathrm{hi} for every completion of the judgments. If lo>0\mathrm{lo} > 0, then D>0D > 0 in every completion, so some document is relevant, R>0R > 0 and AA has the higher average precision; the case hi<0\mathrm{hi} < 0 is the same, and lo=hi\mathrm{lo} = \mathrm{hi} means D=0D = 0 in every completion. Each pass judges one new document, and when none is left lo=hi\mathrm{lo} = \mathrm{hi}, so the loop stops after at most mm judgments. The rule of line L8 only changes how many judgments are made, not what the stop guarantees. The tests check the sign returned against a brute force over all relevance values of the documents not judged.

Proof: The minimal test collection loop stops only when the judgments fix the sign of the difference in average precisionfull

Let AA and BB be rankings with no repeated document, and let PP be the set of the mm documents in AA or BB. Let xd=1x_d = 1 if document dd is relevant and 0 otherwise, and let RR be the number of relevant documents in the whole collection, inside or outside PP. Write rA(d)r_A(d) for the rank of dd in AA, from 1. Lines refer to the pseudocode on the page.

Claim 1 (the quadratic form). For i,j∈Pi, j \in P with i≤ji \le j, let aii=1/rA(i)a_{ii} = 1/r_A(i) and aij=1/max⁡(rA(i),rA(j))a_{ij} = 1/\max(r_A(i), r_A(j)) when both are in AA, and 0 otherwise; define bijb_{ij} in the same way for BB, and let cij=aij−bijc_{ij} = a_{ij} - b_{ij}. Then

D(x)=∑i≤jcijxixj=R (AP(A)−AP(B)),D(x) = \sum_{i \le j} c_{ij} x_i x_j = R \, (\mathrm{AP}(A) - \mathrm{AP}(B)),

where AP is 0 when R=0R = 0. So when R>0R > 0, DD has the sign of AP(A)−AP(B)\mathrm{AP}(A) - \mathrm{AP}(B).

Proof. If R=0R = 0 then every xd=0x_d = 0, both sides are 0. Otherwise, by the definition of average precision,

R⋅AP(A)=∑i∈AxirA(i)∑j∈A, rA(j)≤rA(i)xj.R \cdot \mathrm{AP}(A) = \sum_{i \in A} \frac{x_i}{r_A(i)} \sum_{j \in A, \, r_A(j) \le r_A(i)} x_j.

The term for j=ij = i is xi/rA(i)=aiixixix_i / r_A(i) = a_{ii} x_i x_i, since xi2=xix_i^2 = x_i. Each pair i≠ji \ne j of documents of AA appears once, in the sum of the lower-ranked one, with factor 1/max⁡(rA(i),rA(j))=aij1 / \max(r_A(i), r_A(j)) = a_{ij}. So R⋅AP(A)=∑i≤jaijxixjR \cdot \mathrm{AP}(A) = \sum_{i \le j} a_{ij} x_i x_j. The same holds for BB, and the difference is DD. Relevant documents outside PP change RR but no term of DD. □\square

Fix the judgments made so far: a set SS of documents judged relevant, a set NN judged not relevant, and the set T=P∖(S∪N)T = P \setminus (S \cup N) not judged. A completion is any choice of xd∈{0,1}x_d \in \{0, 1\} for d∈Td \in T.

Claim 2 (the bounds of line L4). Let K=∑i≤j,  i,j∈ScijK = \sum_{i \le j, \; i, j \in S} c_{ij} and let FF be the set of pairs i≤ji \le j with no document in NN and at least one in TT. With lo=K+∑Fmin⁡(0,cij)\mathrm{lo} = K + \sum_{F} \min(0, c_{ij}) and hi=K+∑Fmax⁡(0,cij)\mathrm{hi} = K + \sum_{F} \max(0, c_{ij}), every completion has lo≤D≤hi\mathrm{lo} \le D \le \mathrm{hi}.

Proof. Split DD by pairs. A pair with a document in NN gives 0. A pair inside SS gives cijc_{ij}, and these sum to KK. A pair in FF gives cijxixj∈{0,cij}c_{ij} x_i x_j \in \{0, c_{ij}\}, which lies between min⁡(0,cij)\min(0, c_{ij}) and max⁡(0,cij)\max(0, c_{ij}). Add the bounds. □\square

This is the stopping condition of Carterette, Allan and Sitaraman, where the sum of the negative cijc_{ij} over FF is moved to the other side.

Claim 3 (the stop is sound). If the loop returns 1 in line L5, then AP(A)>AP(B)\mathrm{AP}(A) > \mathrm{AP}(B) for every completion and every relevance of the documents outside PP; the same holds with << for −1-1, and with == for 0.

Proof. If lo>0\mathrm{lo} > 0, Claim 2 gives D>0D > 0 for every completion. Then some xd=1x_d = 1, so R>0R > 0, and Claim 1 gives AP(A)>AP(B)\mathrm{AP}(A) > \mathrm{AP}(B). The case hi<0\mathrm{hi} < 0 is the same. If lo=hi\mathrm{lo} = \mathrm{hi} and neither test before it fired, then lo≤0≤hi=lo\mathrm{lo} \le 0 \le \mathrm{hi} = \mathrm{lo}, so D=0D = 0 for every completion, and by Claim 1 the difference is 0, also when R=0R = 0. □\square

Claim 4 (termination). The loop makes at most mm judgments, and with no budget it always returns a sign.

Proof. Each pass that does not return judges one document of TT in line L10, so ∣T∣|T| falls by 1. When T=∅T = \emptyset, FF is empty and lo=hi=K\mathrm{lo} = \mathrm{hi} = K, so one of the three tests of line L5 fires. □\square

Claim 5 (the weights of line L8). For i∈Ti \in T, let wiR=∑j∈S∪{i}max⁡(0,cij)w^R_i = \sum_{j \in S \cup \{i\}} \max(0, c_{ij}), viR=∑j∈S∪{i}max⁡(0,−cij)v^R_i = \sum_{j \in S \cup \{i\}} \max(0, -c_{ij}), wiN=∑j∈S∪Tmax⁡(0,−cij)w^N_i = \sum_{j \in S \cup T} \max(0, -c_{ij}) and viN=∑j∈S∪Tmax⁡(0,cij)v^N_i = \sum_{j \in S \cup T} \max(0, c_{ij}), with cijc_{ij} read as cjic_{ji} when j<ij < i. Judging ii relevant raises lo by wiRw^R_i and lowers hi by viRv^R_i; judging it not relevant raises lo by wiNw^N_i and lowers hi by viNv^N_i.

Proof. Only the pairs that contain ii change. If ii is judged relevant, the pairs with j∈S∪{i}j \in S \cup \{i\} leave FF and become constants, so their part of lo goes from min⁡(0,cij)\min(0, c_{ij}) to cijc_{ij}, a rise of max⁡(0,cij)\max(0, c_{ij}), and their part of hi goes from max⁡(0,cij)\max(0, c_{ij}) to cijc_{ij}, a fall of max⁡(0,−cij)\max(0, -c_{ij}); the pairs with j∈T∖{i}j \in T \setminus \{i\} stay in FF. If ii is judged not relevant, every pair with j∈S∪Tj \in S \cup T leaves FF and becomes 0, so lo rises by −min⁡(0,cij)-\min(0, c_{ij}) and hi falls by max⁡(0,cij)\max(0, c_{ij}). □\square

All four weights are at least 0, so lo never falls and hi never rises. The choice rule only affects how many judgments are needed, not the soundness of Claim 3.

Claim 6 (the stop is not necessary). The sign can be fixed while lo≤0<hi\mathrm{lo} \le 0 < \mathrm{hi}.

Proof. Let A=(3,2,4,1)A = (3, 2, 4, 1) and B=(3,4,1,2)B = (3, 4, 1, 2), with documents 2 and 4 judged relevant and 1 judged not relevant. Then K=c22+c24+c44=1/4+1/12−1/6=1/6K = c_{22} + c_{24} + c_{44} = 1/4 + 1/12 - 1/6 = 1/6, and the pairs in FF are (3,3)(3, 3), (2,3)(2, 3) and (3,4)(3, 4) with c=0c = 0, 1/41/4 and −1/6-1/6. So lo=1/6−1/6=0\mathrm{lo} = 1/6 - 1/6 = 0 and hi=1/6+1/4=5/12\mathrm{hi} = 1/6 + 1/4 = 5/12, but D=1/6D = 1/6 when x3=0x_3 = 0 and D=1/6+1/4−1/6=1/4D = 1/6 + 1/4 - 1/6 = 1/4 when x3=1x_3 = 1, both positive. The bound treats the two pairs that contain document 3 as if they could take their worst values apart, which they cannot. □\square

Cost. Line L1 builds O(m2)O(m^2) coefficients. In each pass, line L4 reads every pair once, O(m2)O(m^2), and each weight in line L8 reads one row, O(m)O(m), so the scan of line L7 is O(m2)O(m^2). With at most mm passes the total is O(m3)O(m^3) time and O(m2)O(m^2) space. ■\blacksquare

Complexity

  • Time. Line L1 builds O(m2)O(m^2) coefficients. Each pass reads every pair once in line L4 and one row of coefficients per document in line L8, so it takes O(m2)O(m^2) time, and at most mm passes take O(m3)O(m^3). The paper gives O(S2n2)O(S^2 n^2) for SS systems and nn documents, since the weights are taken over all pairs of systems.
  • Space. The coefficients take O(m2)O(m^2) space. Only pairs of documents that both rankings retrieve near each other have large values, so a sparse table helps in practice.
  • Judgments. At most mm, and often far fewer. In the paper's experiments on the Robust 2005 track, 2200 judgments in about 2.5 hours ranked the systems with high confidence, while the NIST pool for the same track took 37,798 judgments and 280.5 hours.

Properties

  • Sound. When the loop returns a sign, no relevance of the documents not judged can change it, and documents outside the pool cannot change it either.
  • Sufficient, not necessary. The bounds take the worst value of each open pair on its own. Let A=(3,2,4,1)A = (3, 2, 4, 1) and B=(3,4,1,2)B = (3, 4, 1, 2), with documents 2 and 4 judged relevant and 1 not relevant. Then lo=0\mathrm{lo} = 0 and hi=5/12\mathrm{hi} = 5/12, but DD is 1/61/6 or 1/41/4 for the two values of document 3, so the sign is already fixed and the loop judges one more document.
  • Monotone. All four weights are at least 0, so each judgment keeps lo or raises it and keeps hi or lowers it.
  • Equal ranks cancel. A document at the same rank in both rankings has cii=0c_{ii} = 0, and a pair has cij=0c_{ij} = 0 when the same one of its two documents is the lower one in both rankings, at the same rank. In the example, document 8 is at rank 3 in both, and its only nonzero coefficients come from documents 2 and 4 below it, so its score stays at 1/401/40.
  • Optimal in one sense. The appendix of the paper proves an optimality result for the choice rule when all pp are equal, and the authors say that it covers only part of the method. The number of judgments that the loop makes is not shown to be the minimum.

Variants and improvements

  • Tighter bounds. Group all the open pairs of a document ii with SS and with itself into one linear coefficient ℓi=cii+∑j∈Scij\ell_i = c_{ii} + \sum_{j \in S} c_{ij}, and bound ℓixi\ell_i x_i by min⁡(0,ℓi)\min(0, \ell_i) and max⁡(0,ℓi)\max(0, \ell_i). This is never looser, because min⁡(0,u+v)≥min⁡(0,u)+min⁡(0,v)\min(0, u + v) \ge \min(0, u) + \min(0, v). In the example above it gives ℓ3=0+1/4−1/6=1/12\ell_3 = 0 + 1/4 - 1/6 = 1/12 and lo=1/6>0\mathrm{lo} = 1/6 > 0, so the loop stops one judgment earlier. The pairs inside TT still need their own bounds.
  • A stop with confidence. Treat each unknown xdx_d as a coin with probability pdp_d, and stop when the probability that D>0D > 0 is high under a normal approximation; the paper uses 95%. This stops much earlier than the sound rule, at the cost of a small chance of error.
  • Mean average precision and many systems. Sum the forms over queries to compare MAP, and take each document's weight as the largest over all pairs of systems to rank many systems at once. The paper also uses the expected value of AP, with pd=1/2p_d = 1/2 for documents not judged, to give each system a score.
  • Other measures. A measure that is linear in the relevance values, such as precision at k or discounted cumulative gain with binary gains, has only terms ciixic_{ii} x_i, and the same bounds apply with no pairs.

When to use it

Use it when the question is which of a few systems is better and the judging budget is small, for example when a lab compares new runs on new topics. It is not a way to estimate the value of AP itself, and the judgments it collects are chosen for the systems being compared, so they are not a fair sample for scoring a new system later. For an estimate of AP from a random sample of judgments, use inferred average precision.

Pitfalls

  • Treating documents not judged as not relevant. Line L4 must bound DD over every completion. If it puts xd=0x_d = 0 for d∈Td \in T, as trec_eval does for a missing judgment, it computes one value of DD and can stop with the wrong sign.
  • Dropping the pairs inside T. In line L4 the pairs with both documents not judged are open too. A bound that keeps only the pairs with one document in SS misses terms such as c46c_{46} in the example and is not sound.
  • Rounding at the stop. When two rankings differ only by documents that cancel, DD is exactly 0, but floating point sums can give a tiny positive lo and line L5 then declares a winner. Use exact fractions, as the code does, or a tolerance.
  • One direction only. If line L8 uses only wRw^R and wNw^N, the loop keeps trying to show that AA is better even when BB is, and judges documents that cannot lower hi. It still stops, but later.
  • Reading the judgments as a test collection. The documents in S∪NS \cup N were chosen by the two rankings, so a third system scored on them gets a biased value of AP.

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.

irtoy.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Shared helper of the information retrieval pages of https://algorithm.tamnd.com/. The authors are listed in prov/.
"""The toy collection of the information retrieval pages.

Eight short documents, four queries with graded judgments and one fixed
run. Tokens are the lower-case words split on spaces, with no stemming
and no stop words. The helper holds only the data and the statistics
tokenize, tf, df, cf, doc_len and avgdl. Scoring and metrics live on the
pages that define them.
"""

DOCS = {
    1: "binary search finds a key in a sorted array",
    2: "merge sort merges two sorted runs into one sorted array",
    3: "an inverted index maps each term to a posting list",
    4: "a posting list is a sorted list of document ids",
    5: "skip pointers speed up the merge of two posting lists",
    6: "a hash table finds a key in constant expected time",
    7: "search engines rank documents by a score for the query",
    8: "the sorted array of ids is compressed with gap encoding",
}

N = len(DOCS)

QUERIES = {
    "q1": "sorted array search",
    "q2": "posting list merge",
    "q3": "rank documents",
    "q4": "quantum circuit",
}

# Graded judgments: 2 is highly relevant, 1 is relevant, absent is 0.
QRELS = {
    "q1": {1: 2, 2: 1, 8: 1},
    "q2": {5: 2, 4: 1, 3: 1},
    "q3": {7: 2},
    "q4": {},
}

# A fixed run for the metric pages, as scores per query.
RUN = {
    "q1": {1: 2.0, 6: 2.0, 8: 1.5, 2: 1.0, 4: 1.0},
}


def tokenize(text):
    """Lower-case words split on spaces."""
    return text.lower().split()


_TOKENS = {d: tokenize(t) for d, t in DOCS.items()}


def tf(term, doc_id):
    """Number of times term occurs in document doc_id."""
    return _TOKENS[doc_id].count(term)


def df(term):
    """Number of documents that contain term."""
    return sum(1 for toks in _TOKENS.values() if term in toks)


def cf(term):
    """Number of occurrences of term in the whole collection."""
    return sum(toks.count(term) for toks in _TOKENS.values())


def doc_len(doc_id):
    """Number of tokens in document doc_id."""
    return len(_TOKENS[doc_id])


def avgdl():
    """Average document length in tokens."""
    return sum(len(toks) for toks in _TOKENS.values()) / N
minimal_test_collection.py 113 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/minimal-test-collection/. The authors are listed in prov/19JM8C.jsonl.

from fractions import Fraction
from typing import Callable, Hashable, Optional, Sequence

Pair = tuple[Hashable, Hashable]


def coefficients(a: Sequence[Hashable], b: Sequence[Hashable]) -> tuple[list[Hashable], dict[Pair, Fraction]]:
    """Return the pooled documents (sorted) and c[(i, j)] for i <= j with
    R * (AP(a) - AP(b)) = sum of c[(i, j)] * x_i * x_j, where x_d is 1 if d is relevant.

    Precondition: a and b have no repeated document and the ids are comparable.
    For one ranking, c_ii = 1 / rank(i) and c_ij = 1 / max(rank(i), rank(j)).
    Exact fractions keep the signs exact. Time and space O(m^2) for m pooled documents.
    """
    ra = {d: r + 1 for r, d in enumerate(a)}
    rb = {d: r + 1 for r, d in enumerate(b)}
    docs = sorted(set(a) | set(b))

    def one(rank: dict, i: Hashable, j: Hashable) -> Fraction:
        if i in rank and j in rank:
            return Fraction(1, max(rank[i], rank[j]))
        return Fraction(0)

    c: dict[Pair, Fraction] = {}
    for x, i in enumerate(docs):
        for j in docs[x:]:
            c[(i, j)] = one(ra, i, j) - one(rb, i, j)
    return docs, c


def pair(c: dict[Pair, Fraction], i: Hashable, j: Hashable) -> Fraction:
    return c[(i, j)] if (i, j) in c else c[(j, i)]


def bounds(c: dict[Pair, Fraction], judged: dict[Hashable, int]) -> tuple[Fraction, Fraction]:
    """Return (lo, hi) with lo <= D <= hi for D = sum c_ij x_i x_j and every
    relevance of the documents not judged.

    A term with a judged nonrelevant document is 0, a term with two judged
    relevant documents is c_ij, and any other term lies between min(0, c_ij)
    and max(0, c_ij). Time O(m^2).
    """
    lo = hi = Fraction(0)
    for (i, j), v in c.items():
        xi, xj = judged.get(i), judged.get(j)
        if xi == 0 or xj == 0:
            continue
        if xi == 1 and xj == 1:
            lo += v
            hi += v
        else:
            lo += min(0, v)
            hi += max(0, v)
    return lo, hi


def weights(docs: Sequence[Hashable], c: dict[Pair, Fraction], judged: dict[Hashable, int], i: Hashable) -> tuple[Fraction, Fraction, Fraction, Fraction]:
    """Return (wR, wN, vR, vN): the rise of lo and the fall of hi if i is judged
    relevant (R) or not relevant (N). Precondition: i is not judged. Time O(m)."""
    w_r = w_n = v_r = v_n = Fraction(0)
    for j in docs:
        xj = judged.get(j)
        if xj == 0:
            continue
        v = pair(c, i, j)
        if j == i or xj == 1:  # the term becomes the constant c_ij
            w_r += max(0, v)
            v_r += max(0, -v)
        w_n += max(0, -v)  # the term becomes 0
        v_n += max(0, v)
    return w_r, w_n, v_r, v_n


def minimal_test_collection(
    a: Sequence[Hashable],
    b: Sequence[Hashable],
    judge: Callable[[Hashable], int],
    p: Fraction = Fraction(1, 2),
    budget: Optional[int] = None,
) -> tuple[Optional[int], list[Hashable]]:
    """Judge pooled documents one at a time until the sign of AP(a) - AP(b) is fixed.

    Precondition: judge(d) returns 1 for a relevant document and 0 otherwise.
    Returns (sign, order). The sign is 1, -1 or 0 when every relevance of the
    documents not judged gives that sign of R * (AP(a) - AP(b)), and None when
    the budget runs out first. Each step costs O(m^2), so O(m^3) in total.
    """
    docs, c = coefficients(a, b)  # @line L1
    judged: dict[Hashable, int] = {}  # @line L2
    order: list[Hashable] = []
    while True:  # @line L3
        lo, hi = bounds(c, judged)  # @line L4
        if lo > 0:  # @line L5
            return 1, order
        if hi < 0:
            return -1, order
        if lo == hi:
            return 0, order
        if budget is not None and len(order) >= budget:  # @line L6
            return None, order
        best, best_score = None, Fraction(-1)
        for i in docs:  # @line L7
            if i in judged:
                continue
            w_r, w_n, v_r, v_n = weights(docs, c, judged, i)
            score = max(p * w_r, (1 - p) * w_n, p * v_r, (1 - p) * v_n)  # @line L8
            if score > best_score:  # @line L9
                best, best_score = i, score
        judged[best] = judge(best)  # @line L10
        order.append(best)
test_minimal_test_collection.py 148 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/minimal-test-collection/. The authors are listed in prov/19JM8C.jsonl.

import itertools
import random
from fractions import Fraction

from irtoy import QRELS, RUN
from minimal_test_collection import bounds, coefficients, minimal_test_collection, weights


def average_precision(ranking, rel, r_total):
    if r_total == 0:
        return Fraction(0)
    hits = 0
    s = Fraction(0)
    for k, d in enumerate(ranking, 1):
        if rel.get(d, 0):
            hits += 1
            s += Fraction(hits, k)
    return s / r_total


def d_value(c, x):
    return sum(v * x[i] * x[j] for (i, j), v in c.items())


def completions(docs, judged):
    free = [d for d in docs if d not in judged]
    for bits in itertools.product((0, 1), repeat=len(free)):
        x = dict(judged)
        x.update(zip(free, bits))
        yield x


def sign(v):
    return (v > 0) - (v < 0)


def random_case(rng, n_max):
    n = rng.randint(1, n_max)
    universe = list(range(1, n + 3))
    a = rng.sample(universe, rng.randint(1, n))
    b = rng.sample(universe, rng.randint(1, n))
    rel = {d: rng.randint(0, 1) for d in universe}
    return a, b, rel


def test_toy_collection_two_tie_orders():
    rel = {d: 1 for d in QRELS["q1"]}
    scores = RUN["q1"]
    a = sorted(scores, key=lambda d: -scores[d])  # stable: 1, 6, 8, 2, 4
    b = sorted(scores, key=lambda d: (-scores[d], -d))  # ties by reverse id: 6, 1, 8, 4, 2
    assert a == [1, 6, 8, 2, 4] and b == [6, 1, 8, 4, 2]
    r_total = len(rel)
    assert average_precision(a, rel, r_total) == Fraction(29, 36)
    assert average_precision(b, rel, r_total) == Fraction(53, 90)
    s, order = minimal_test_collection(a, b, lambda d: rel.get(d, 0))
    assert s == 1 and order == [1, 6]
    docs, c = coefficients(a, b)
    assert bounds(c, {}) == (Fraction(-7, 10), Fraction(7, 10))
    assert weights(docs, c, {}, 1) == (Fraction(1, 2), Fraction(1, 20), 0, Fraction(11, 20))
    assert weights(docs, c, {}, 6) == (0, Fraction(11, 20), Fraction(1, 2), Fraction(1, 20))
    assert bounds(c, {1: 1}) == (Fraction(-1, 5), Fraction(7, 10))
    lo, hi = bounds(c, {1: 1, 6: 0})
    assert (lo, hi) == (Fraction(7, 20), Fraction(13, 20))
    vals = [d_value(c, x) for x in completions(docs, {1: 1, 6: 0})]
    assert min(vals) == lo and max(vals) == hi
    assert r_total * (average_precision(a, rel, r_total) - average_precision(b, rel, r_total)) == Fraction(13, 20)


def test_quadratic_form_is_r_times_delta_ap():
    rng = random.Random(1)
    for _ in range(500):
        a, b, rel = random_case(rng, 6)
        docs, c = coefficients(a, b)
        r_total = sum(rel.values())
        lhs = r_total * (average_precision(a, rel, r_total) - average_precision(b, rel, r_total))
        assert lhs == d_value(c, {d: rel[d] for d in docs})


def test_bounds_are_sound():
    rng = random.Random(2)
    for _ in range(400):
        a, b, rel = random_case(rng, 6)
        docs, c = coefficients(a, b)
        judged = {d: rel[d] for d in docs if rng.random() < 0.4}
        lo, hi = bounds(c, judged)
        vals = [d_value(c, x) for x in completions(docs, judged)]
        assert lo <= min(vals) and max(vals) <= hi


def test_weights_match_recomputed_bounds():
    rng = random.Random(3)
    for _ in range(300):
        a, b, rel = random_case(rng, 6)
        docs, c = coefficients(a, b)
        judged = {d: rel[d] for d in docs if rng.random() < 0.3}
        lo, hi = bounds(c, judged)
        for i in docs:
            if i in judged:
                continue
            w_r, w_n, v_r, v_n = weights(docs, c, judged, i)
            lo1, hi1 = bounds(c, {**judged, i: 1})
            lo0, hi0 = bounds(c, {**judged, i: 0})
            assert (w_r, w_n, v_r, v_n) == (lo1 - lo, lo0 - lo, hi - hi1, hi - hi0)
            assert min(w_r, w_n, v_r, v_n) >= 0


def test_judgments_decide_the_sign_against_brute_force():
    rng = random.Random(4)
    saved = 0
    for _ in range(600):
        a, b, rel = random_case(rng, 7)
        s, order = minimal_test_collection(a, b, lambda d: rel[d])
        docs, c = coefficients(a, b)
        assert len(order) == len(set(order)) <= len(docs)
        saved += len(docs) - len(order)
        judged = {d: rel[d] for d in order}
        for x in completions(docs, judged):
            assert sign(d_value(c, x)) == s
            full = rel.copy()
            full.update(x)
            r_total = sum(full.values())
            delta = average_precision(a, full, r_total) - average_precision(b, full, r_total)
            assert sign(delta) == s
    assert saved > 0


def test_stop_rule_is_sufficient_not_necessary():
    a, b = [3, 2, 4, 1], [3, 4, 1, 2]
    docs, c = coefficients(a, b)
    judged = {2: 1, 4: 1, 1: 0}
    vals = [d_value(c, x) for x in completions(docs, judged)]
    assert sorted(vals) == [Fraction(1, 6), Fraction(1, 4)]
    assert bounds(c, judged) == (0, Fraction(5, 12))


def test_edge_cases():
    same = [3, 1, 2]
    assert minimal_test_collection(same, same, lambda d: 1) == (0, [])
    s, order = minimal_test_collection([1], [2], lambda d: 1)
    assert s == 0 and sorted(order) == [1, 2]
    s, order = minimal_test_collection([1], [2], lambda d: int(d == 1))
    assert s == 1
    assert minimal_test_collection([1, 2], [2, 1], lambda d: 1, budget=0) == (None, [])
    s, order = minimal_test_collection([1, 2], [2, 1], lambda d: int(d == 2), budget=1)
    assert s is None and len(order) == 1

History

Carterette, Allan and Sitaraman presented minimal test collections at SIGIR 2006. They connected evaluation with the building of the test collection: instead of judging a fixed pool and then computing measures, the measure to compare decides which documents to judge. On the Robust 2005 track they ranked the systems with a small fraction of the judgments that NIST had made, and after 1000 judgments, about one hour of work, the ranking had 90% confidence. The method was later used, with sampling methods such as inferred average precision, in TREC tracks with many queries and few judgments per query.

References

  1. Ben Carterette, James Allan and Ramesh Sitaraman, Minimal test collections for retrieval evaluation, SIGIR 2006, pp. 268-275, Section 3 (the difference in AP as a sum over pairs and the stopping condition), Section 3.1 (the weights and the rule that judges the document with the largest of p times the weight for relevant and 1 - p times the weight for not relevant, p = 0.5), Section 3.2 (a stop with 95% confidence), Section 3.3 (MAP), Section 4.5 (cost and many systems), the appendix (Algorithm 1 and Theorem 1), and the Robust 2005 experiments

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
  • History with a source
  • at least three sources
  • a scene preset for the example