Algorithm Search⌘K

Data structureadvanced

Signature file

Also called superimposed coding index.

Stores for each document a bit signature made by OR-ing hashed term codes, so a scan rejects most documents without false negatives.

Time
O(m D + F/w) insertO(m s + N F/w + c V) search
Space
O(N F/w) total
Where
D = the number of distinct terms of a document; F = the signature width in bits; N = the number of documents; V = the cost of checking one candidate against its document; c = the number of candidates; m = the bits set per term; s = the number of query terms; w = the word size in bits
Properties
not concurrentnot externalnot persistent

A signature file is an index that stores, for each document, one string of FF bits, its signature: each distinct term of the document is hashed to a code with mm bits set, and the signature is the OR of these codes, a method called superimposed coding. A query is coded in the same way, and a document can contain all the query terms only if its signature has a 1 wherever the query code has one. A sequential scan of the signatures rejects most documents with a few word operations each, never rejects a document that matches, and passes some false drops, which a check against the document removes. Each signature is a Bloom filter of the terms of one document.

In plain words

For every word, a fixed rule picks a few positions in a row of bits. A document gets one row: switch on the positions of every word it contains. To ask whether a document holds the word "sorted", look at the positions of "sorted" in its row. If one of them is off, the document cannot hold the word, and it is skipped.

If all of them are on, the document probably holds the word, but other words may have switched on the same positions by chance. So the documents that pass are read and checked. The rows are short and the test is fast, so a scan over all rows is cheap. A wider row with well chosen positions per word lets fewer wrong documents pass.

The abstract type

The structure holds a sequence of documents, each an id and a set of terms. The operations are:

  • INSERT(S,d,T)(S, d, T): append the document dd with the set of terms TT.
  • CANDIDATES(S,Q)(S, Q): return the ids, in insertion order, of the documents whose signature covers the code of the query terms QQ. This set contains every document whose terms include QQ.
  • SEARCH(S,Q)(S, Q): return the ids of the documents whose terms include QQ, in insertion order: the Boolean AND query of the Boolean retrieval model.

Representation

A term tt has the code sig(t)\mathrm{sig}(t), an FF-bit word with exactly mm bits set, at places chosen by a hash function of tt. The signature of a document with term set TT is sig(T)=⋁t∈Tsig(t)\mathrm{sig}(T) = \bigvee_{t \in T} \mathrm{sig}(t). The file is the array of the NN signatures, each ⌈F/w⌉\lceil F/w \rceil machine words, in the order of the documents, next to the documents or their term sets, which the check reads. The code here takes the mm places from 16-bit pieces of a keyed BLAKE2b hash, with rejection of the pieces that would bias a place and of places already taken, so that under the model of an ideal hash every set of mm places is equally likely.

Operations

  1. SEARCH(S, Q)
  2. 1q ← 0
  3. 2for each term t of Q do q ← q OR sig(t) ▷ the query code
  4. 3R ← ()
  5. 4for each document d with signature s and terms T, in order do
  6. 5if s AND q = q then ▷ d is a candidate
  7. 6if Q ⊆ T then append d to R ▷ the check removes false drops
  8. 7return R

INSERT computes sig(T)\mathrm{sig}(T) with one code for each distinct term and appends it. CANDIDATES is lines L1 to L5 without the check. The test of line L5 is one AND and one comparison per machine word of the signature.

Example

Take F=32F = 32 and m=2m = 2 on the toy collection. The code of "sorted" sets the bits 18 and 27, that of "merge" the bits 3 and 29, and that of "list" the bits 0 and 29. Apply these operations.

operation bits set CANDIDATES and SEARCH after it
INSERT d1d_1 (8 terms) 11: 3, 4, 7, 12, 15, 16, 18, 19, 22, 27, 30 sorted: (d1)(d_1) and (d1)(d_1)
INSERT d2d_2 (9 terms) 14 merge: (d2)(d_2) and (d2)(d_2)
INSERT d3d_3 (10 terms) 14: 0, 2, 3, 7, 9, 12, 15, 18, 19, 24, 25, 26, 29, 31 merge: (d2,d3)(d_2, d_3) and (d2)(d_2); list: (d3)(d_3) and (d3)(d_3)

After d3d_3, "merge" has a false drop: d3d_3 has bit 3 from "term" and bit 29 from "list", and it does not contain "merge".

With all 8 documents, the signatures have 11, 14, 14, 13, 16, 16, 14 and 12 bits set. The query "sorted" gives the candidates d1d_1, d2d_2, d4d_4, d6d_6 and d8d_8, and the check keeps d1d_1, d2d_2, d4d_4 and d8d_8. "quantum" occurs in no document and still has the candidate d5d_5. The query q2q_2, "posting list merge", has the candidates d3d_3 and d4d_4 and no answer. Over the 326 pairs of a term of the vocabulary and a document that does not contain it, 58 are false drops; the formula below predicts 63.8 on average.

Correctness

The invariant is that each stored signature is the OR of the codes of the terms of its document. If Q⊆TQ \subseteq T, every bit of qq is a bit of some sig(t)\mathrm{sig}(t) with t∈Tt \in T, so s AND q=qs \text{ AND } q = q: a matching document is always a candidate, and there are no false negatives. Line L6 is the exact test, so SEARCH returns exactly the documents of a direct scan, in the same order.

The rate of false drops depends on the hash. Model each term code as a uniform random set of mm of the FF places, independent across terms. For a one-term query whose term is not among the DD distinct terms of a document, the document is a false drop when each of the mm query places is set by some document term. By the inclusion-exclusion principle over the query places that stay empty,

Pfd=∑j=0m(−1)j(mj)((F−jm)(Fm))D.P_{\mathrm{fd}} = \sum_{j=0}^{m} (-1)^j \binom{m}{j} \left( \frac{\binom{F-j}{m}}{\binom{F}{m}} \right)^{D}.

The full proofs of both parts are in the proof file of this page.

Proof: The signature file has no false negatives, its search returns exactly the documents that contain the query, and the false drop rate has a closed formfull

Fix the width FF and the weight mm with 1≤m≤F1 \le m \le F. For a term tt, the term signature τ(t)\tau(t) is a set of exactly mm of the places 0,…,F−10, \ldots, F - 1, written as an FF-bit word; it depends only on tt (and the fixed salt). For a finite set TT of terms, the signature is σ(T)=⋃t∈Tτ(t)\sigma(T) = \bigcup_{t \in T} \tau(t), the bitwise OR of the term signatures, with σ(∅)=0\sigma(\emptyset) = 0. A document dd has a set of terms TdT_d. For a query, a finite set QQ of terms, the answer is A(Q)=(d:Q⊆Td)A(Q) = (d : Q \subseteq T_d), in the order of insertion.

Invariant (I). The arrays idsids, sigssigs and termsterms have the same length, and for each ii, sigs[i]=σ(terms[i])sigs[i] = \sigma(terms[i]), where terms[i]terms[i] is the term set of document ids[i]ids[i].

Lemma 1. The constructor makes (I) true and INSERT keeps it.

Proof. The empty file has three empty arrays. INSERT appends the id, the set TT of distinct terms, and SIGNATURE(T)(T), which ORs τ(t)\tau(t) over the distinct elements of TT, so it is σ(T)\sigma(T). □\square

Lemma 2 (no false negatives). If Q⊆TdQ \subseteq T_d, then σ(Q)⊆σ(Td)\sigma(Q) \subseteq \sigma(T_d), that is, σ(Td)&σ(Q)=σ(Q)\sigma(T_d) \mathbin{\&} \sigma(Q) = \sigma(Q).

Proof. σ(Q)=⋃t∈Qτ(t)⊆⋃t∈Tdτ(t)=σ(Td)\sigma(Q) = \bigcup_{t \in Q} \tau(t) \subseteq \bigcup_{t \in T_d} \tau(t) = \sigma(T_d), since the second union runs over a superset of the terms of the first. A set of places aa is contained in bb exactly when b&a=ab \mathbin{\&} a = a as words. □\square

The converse does not hold. Places of τ(t)\tau(t) for a term t∉Tdt \notin T_d can all be set by other terms of dd, and then dd passes the test of line L5 without containing tt. Such a document is a false drop.

Theorem 1. If (I) holds, SEARCH(Q)(Q) returns A(Q)A(Q), in the order of insertion.

Proof. Lines L1 and L2 compute q=σ(Q)q = \sigma(Q). Line L4 visits the documents in the order of insertion, with s=σ(Td)s = \sigma(T_d) by (I). If Q⊆TdQ \subseteq T_d, then line L5 passes by Lemma 2 and line L6 passes, so dd is appended. If Q⊈TdQ \not\subseteq T_d, then line L6 fails, whatever line L5 does, so dd is not appended. So the output is the sequence of the dd with Q⊆TdQ \subseteq T_d, in the order of insertion, which is A(Q)A(Q). For Q=∅Q = \emptyset, q=0q = 0, every document passes both lines, and A(∅)A(\emptyset) is every document. □\square

The same argument shows that CANDIDATES(Q)(Q), which stops after line L5, returns A(Q)A(Q) followed in order by the false drops: every answer is a candidate, and a candidate is not an answer exactly when it is a false drop.

The random model. To count false drops, model each term signature as a uniform random mm-subset of the FF places, independent for different terms. The code is built so that this model is the right one for an ideal hash: each 16-bit hash value below 65536−(65536 mod F)65536 - (65536 \bmod F) gives a uniform place modulo FF, values above it are rejected, and places already taken are skipped, so the mm distinct places form a uniform mm-subset when the hash values are independent and uniform. BLAKE2b is not proved to be such a hash; the model is the usual assumption, and the tests check the rate that it predicts.

Theorem 2 (the false drop rate). Let dd have DD distinct terms, and let tt be a term not in TdT_d. In the random model, the probability that dd is a false drop for the query {t}\{t\} is

p(F,m,D)=∑j=0m(−1)j(mj)((F−jm)(Fm))D.p(F, m, D) = \sum_{j=0}^{m} (-1)^j \binom{m}{j} \left( \frac{\binom{F-j}{m}}{\binom{F}{m}} \right)^{D}.

Proof. Condition on τ(t)=P\tau(t) = P, a fixed set of mm places. The signatures of the DD terms of dd are independent of τ(t)\tau(t), since the terms are different. The document is a false drop when every place of PP is set in σ(Td)\sigma(T_d). For p∈Pp \in P let EpE_p be the event that pp is not set. By the inclusion-exclusion principle,

Pr⁡[⋂p∈PEp‾]=∑J⊆P(−1)∣J∣Pr⁡[⋂p∈JEp].\Pr\Big[\bigcap_{p \in P} \overline{E_p}\Big] = \sum_{J \subseteq P} (-1)^{|J|} \Pr\Big[\bigcap_{p \in J} E_p\Big].

The event ⋂p∈JEp\bigcap_{p \in J} E_p says that no term of dd sets a place of JJ. One uniform mm-subset of the FF places avoids a fixed set of j=∣J∣j = |J| places with probability (F−jm)/(Fm)\binom{F-j}{m} / \binom{F}{m}, the share of the mm-subsets of the other F−jF - j places, and the DD terms are independent, so the probability is that number to the power DD. It depends on JJ only through jj, and PP has (mj)\binom{m}{j} subsets of size jj. This gives the formula, and since it does not depend on PP, it is also the probability without the condition. ■\blacksquare

Remark (the usual approximation). If the places of each term were chosen with repetition, a place would stay unset with probability (1−1/F)mD(1 - 1/F)^{mD}, and treating the mm places of the query as independent gives the false drop probability (1−(1−1/F)mD)m≈(1−e−mD/F)m(1 - (1 - 1/F)^{mD})^m \approx (1 - e^{-mD/F})^m. For fixed FF and DD this is smallest near m=(F/D)ln⁡2m = (F / D) \ln 2, the same analysis as for the Bloom filter. The exact formula of Theorem 2 is the one the code computes, with exact fractions.

Complexity

operation time notes
INSERT O(mD+F/w)O(mD + F/w) mm places for each of the DD distinct terms, in expectation over the rejections
CANDIDATES O(ms+NF/w)O(ms + NF/w) the query code, then one pass over all signatures
SEARCH O(ms+NF/w+cV)O(ms + NF/w + cV) plus one check of each of the cc candidates
space O(NF/w)O(NF/w) words plus the documents for the check

The scan reads every signature for every query, so the time grows with NN whatever the size of the answer. An inverted index reads only the posting lists of the query terms.

Variants

  • Choice of m. For F=64F = 64 and D=10D = 10, the formula gives the false drop rates 0.1457, 0.0713, 0.0520, 0.0472, 0.0490, 0.0551, 0.0654 and 0.0800 for m=1m = 1 to 8. The best is m=4m = 4, near the value (F/D)ln⁡2≈4.44(F/D)\ln 2 \approx 4.44 of the approximation Pfd≈(1−e−mD/F)mP_{\mathrm{fd}} \approx (1 - e^{-mD/F})^m, which gives 0.0466 at m=4m = 4 against the exact 0.0472. This is the same optimum as for a Bloom filter, on the page about the optimal number of hash functions. Doubling the width to F=128F = 128 with m=4m = 4 cuts the exact rate to 0.00489.
  • Bit-sliced storage. Store the file by columns: one bit vector of length NN for each of the FF places. A query reads only the columns of its set bits and ANDs them, so the work per query is about msms columns of NN bits, not all NFNF bits. This is close to a bitmap index over hashed places.
  • Signatures of blocks. Cut long documents into blocks of a fixed number of distinct terms, and give each block its own signature, so that DD stays near the value the width was chosen for.
  • Several queries in one pass. A sequential scan can test many query codes against each signature it reads.

When to use it

Signature files suit conjunctive queries over many small records with a fixed upper bound on their terms, where appends are frequent, and where a scan of a compact file is acceptable. Zobel, Moffat and Ramamohanarao compared the two methods for text indexing and found inverted files distinctly superior: faster, smaller and more functional. A signature file keeps no term weights for ranking and no positions for phrase queries, and a NOT in a query cannot use the signatures at all, because a set bit does not prove that a term is present. For text search, use an inverted index; keep signatures for filters inside other structures.

Pitfalls

  • Long documents. A document with many distinct terms sets most of the bits and becomes a candidate for almost every query. With F=32F = 32 and m=2m = 2 the toy documents of 10 terms already have a false drop rate of 0.22 for one query term. Choose FF for the largest DD, or split documents into blocks.
  • Dropping the check. CANDIDATES is not the answer: "quantum" has a candidate on the toy collection. The check of line L6 needs access to the documents.
  • Codes with fewer than m bits. Taking mm hash values modulo FF without removing repeats gives some terms fewer bits, and those terms pass more false drops. Choose distinct places.
  • Biased places. Reducing a 16-bit value modulo an FF that does not divide 2162^{16} makes small places more likely. Reject the values at or above the largest multiple of FF below 2162^{16}.
  • Testing the rate without a tolerance. A measured false drop rate is random. Compare it with the formula within a bound such as Hoeffding's inequality: with 150,000 trials, a gap of 0.00695 has probability at most about 10−610^{-6} under the model.

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
signature_file.py 123 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/signature-file/. The authors are listed in prov/WA5X66.jsonl.
"""A sequential signature file with superimposed coding.

Each term sets m distinct bits out of F. The signature of a document is the
OR of the signatures of its distinct terms. A query is the OR of the
signatures of its terms, and a document is a candidate when its signature
has a 1 in every place where the query has one. Candidates are then checked
against the terms of the document, which removes the false drops.
"""

import hashlib
from typing import Hashable, Iterable


class SignatureFile:
    """Signatures of F bits, m bits per term, one signature per document, in insertion order.

    The term sets of the documents are kept as well, in the role of the text
    file that the verification step reads.
    """

    def __init__(self, f: int = 64, m: int = 4, salt: bytes = b"") -> None:
        if not (1 <= m <= f <= 65536):
            raise ValueError("need 1 <= m <= f <= 65536")
        self.f, self.m, self.salt = f, m, salt[:16]
        self.ids: list[Hashable] = []
        self.sigs: list[int] = []
        self.terms: list[frozenset[str]] = []
        self._cache: dict[str, int] = {}

    def __len__(self) -> int:
        return len(self.ids)

    def term_signature(self, t: str) -> int:
        """Return the F-bit word of t: m distinct places, chosen by a keyed hash of t.

        The places come from 16-bit values of BLAKE2b, with rejection of values
        that would bias the place and of places already taken, so under the
        usual model of an ideal hash every m-subset is equally likely.
        Cost O(m) hash calls in expectation.
        """
        if t in self._cache:
            return self._cache[t]
        f, places, counter = self.f, set(), 0
        limit = 65536 - 65536 % f
        while len(places) < self.m:
            h = hashlib.blake2b(t.encode() + counter.to_bytes(4, "big"), key=self.salt, digest_size=32).digest()
            counter += 1
            for i in range(0, 32, 2):
                x = int.from_bytes(h[i : i + 2], "big")
                if x < limit:
                    places.add(x % f)
                    if len(places) == self.m:
                        break
        w = 0
        for p in places:
            w |= 1 << p
        if len(self._cache) < 1 << 16:
            self._cache[t] = w
        return w

    def signature(self, terms: Iterable[str]) -> int:
        """Return the OR of the term signatures of the distinct terms. Cost O(m) per term."""
        s = 0
        for t in set(terms):
            s |= self.term_signature(t)
        return s

    def insert(self, doc_id: Hashable, terms: Iterable[str]) -> None:
        """Append the signature of a document. Cost O(m) per distinct term of the document."""
        ts = frozenset(terms)
        self.ids.append(doc_id)
        self.sigs.append(self.signature(ts))
        self.terms.append(ts)

    def candidates(self, query: Iterable[str]) -> list[Hashable]:
        """Return the ids whose signature covers the query signature: the answers and the false drops.

        Cost: one scan of the N signatures, O(N F / w) word operations for words of w bits.
        """
        q = self.signature(query)
        return [d for d, s in zip(self.ids, self.sigs) if s & q == q]

    def search(self, query: Iterable[str]) -> list[Hashable]:
        """Return the ids of the documents that contain every query term, in insertion order.

        Cost: the scan of candidates, plus one check of the terms of each candidate.
        """
        qs = frozenset(query)
        q = 0  # @line L1
        for t in qs:  # @line L2
            q |= self.term_signature(t)
        r: list[Hashable] = []  # @line L3
        for d, s, ts in zip(self.ids, self.sigs, self.terms):  # @line L4
            if s & q == q:  # @line L5
                if qs <= ts:  # @line L6
                    r.append(d)
        return r  # @line L7

    def check_invariant(self) -> None:
        """Raise AssertionError unless each stored signature is the OR of the signatures of its terms."""
        assert len(self.ids) == len(self.sigs) == len(self.terms)
        for s, ts in zip(self.sigs, self.terms):
            assert s == self.signature(ts)
            assert 0 <= s < 1 << self.f


def false_drop_probability(f: int, m: int, d: int) -> float:
    """The exact probability that a one-term query that is not in a document of d distinct terms is a false drop.

    Model: each term sets a uniform random m-subset of the f places,
    independently. By inclusion and exclusion over the m places of the query,
    the result is sum over j of (-1)^j C(m, j) (C(f - j, m) / C(f, m))^d.
    Cost O(m) big-integer operations.
    """
    from fractions import Fraction
    from math import comb

    total = Fraction(0)
    for j in range(m + 1):
        total += (-1) ** j * comb(m, j) * Fraction(comb(f - j, m), comb(f, m)) ** d
    return float(total)
test_signature_file.py 128 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/signature-file/. The authors are listed in prov/WA5X66.jsonl.

import itertools
import math
import random
from fractions import Fraction

import pytest

import irtoy
from signature_file import SignatureFile, false_drop_probability


def toy(f: int = 32, m: int = 2) -> SignatureFile:
    s = SignatureFile(f, m)
    for d, text in irtoy.DOCS.items():
        s.insert(d, irtoy.tokenize(text))
        s.check_invariant()
    return s


def scan(docs: dict, query: list[str]) -> list:
    return [d for d, ts in docs.items() if set(query) <= set(ts)]


def test_worked_example_of_the_page():
    s = toy()
    sig = s.term_signature("sorted")
    assert [p for p in range(32) if sig >> p & 1] == [18, 27]
    assert s.candidates(["sorted"]) == [1, 2, 4, 6, 8]
    assert s.search(["sorted"]) == [1, 2, 4, 8]
    assert s.candidates(["quantum"]) == [5]
    assert s.search(["quantum"]) == []
    q = irtoy.tokenize(irtoy.QUERIES["q2"])
    assert s.candidates(q) == [3, 4]
    assert s.search(q) == []
    assert s.search(irtoy.tokenize(irtoy.QUERIES["q1"])) == [1]


def test_no_false_negatives_on_the_toy_collection():
    s = toy()
    docs = {d: irtoy.tokenize(t) for d, t in irtoy.DOCS.items()}
    vocab = sorted({t for ts in docs.values() for t in ts})
    for t in vocab + ["quantum", "lists", "document"]:
        want = scan(docs, [t])
        assert s.search([t]) == want
        assert set(want) <= set(s.candidates([t]))


def test_edge_cases():
    s = SignatureFile()
    assert s.search(["a"]) == [] and s.candidates([]) == []
    s.insert("e", [])
    s.insert("x", ["a"])
    s.check_invariant()
    # The empty query has the zero signature, which every document covers.
    assert s.search([]) == ["e", "x"]
    assert s.search(["a"]) == ["x"]
    assert s.search(["a", "a"]) == ["x"]
    full = SignatureFile(8, 8)
    full.insert(1, ["p"])
    full.insert(2, ["q"])
    # With m = F every term sets every bit, so every document is a candidate.
    assert full.candidates(["r"]) == [1, 2]
    assert full.search(["r"]) == []
    with pytest.raises(ValueError):
        SignatureFile(4, 5)


def test_term_signature_has_m_bits():
    for f, m in [(1, 1), (7, 3), (64, 4), (100, 7), (16, 16)]:
        s = SignatureFile(f, m, salt=b"k")
        for i in range(200):
            w = s.term_signature("t%d" % i)
            assert bin(w).count("1") == m and w < 1 << f


def test_random_collections_against_a_direct_scan():
    rng = random.Random(84)
    for _ in range(600):
        f = rng.choice([8, 16, 32, 64])
        m = rng.randint(1, 4)
        s = SignatureFile(f, m, salt=bytes([rng.randrange(256)]))
        alphabet = ["w%d" % i for i in range(rng.randint(1, 30))]
        docs = {}
        for d in range(rng.randint(0, 12)):
            docs[d] = rng.sample(alphabet, rng.randint(0, min(8, len(alphabet))))
            s.insert(d, docs[d])
        s.check_invariant()
        for _ in range(5):
            q = rng.sample(alphabet, rng.randint(1, min(3, len(alphabet))))
            want = scan(docs, q)
            assert s.search(q) == want
            assert set(want) <= set(s.candidates(q))


def test_formula_against_full_enumeration():
    # All (C(F, m))^(D+1) choices of the m-subsets, for small F, m and D.
    for f, m, d in [(4, 1, 2), (5, 2, 2), (6, 2, 3), (6, 3, 2)]:
        subsets = [frozenset(c) for c in itertools.combinations(range(f), m)]
        hits = 0
        for doc in itertools.product(subsets, repeat=d):
            union = frozenset().union(*doc)
            hits += sum(1 for q in subsets if q <= union)
        exact = Fraction(hits, len(subsets) ** (d + 1))
        assert math.isclose(false_drop_probability(f, m, d), float(exact), rel_tol=1e-12)


def test_false_drop_rate_matches_the_formula():
    f, m, d, n = 16, 2, 4, 150000
    s = SignatureFile(f, m, salt=b"rate")
    rng = random.Random(1984)
    drops = 0
    for _ in range(n):
        terms = ["d%d" % rng.getrandbits(60) for _ in range(d)]
        q = "q%d" % rng.getrandbits(60)
        doc = s.signature(terms)
        qs = s.term_signature(q)
        drops += doc & qs == qs
        s._cache.clear()
    p = false_drop_probability(f, m, d)
    # Hoeffding: P(|rate - p| >= t) <= 2 exp(-2 n t^2) = delta.
    delta = 1e-6
    t = math.sqrt(math.log(2 / delta) / (2 * n))
    assert abs(drops / n - p) < t
    # The approximation (1 - e^(-m d / F))^m is close to the exact value.
    assert abs((1 - math.exp(-m * d / f)) ** m - p) < 0.005

History

Faloutsos and Christodoulakis (1984) presented signature files with superimposed coding as an access method for documents and analyzed their performance and their false drop probability, and Faloutsos (1985) surveyed them with full text scanning, inversion and clustering as the access methods for text. Zobel, Moffat and Ramamohanarao (1998) compared signature files with compressed inverted files and found the inverted files better on time, space and the range of queries, and inverted indexes became the standard for text search.

References

  1. Christos Faloutsos and Stavros Christodoulakis, Signature files, An access method for documents and its analytical performance evaluation, ACM Transactions on Office Information Systems 2(4), 267 to 288, 1984, the signature file with superimposed coding of the words of a document, the false drop probability, and the choice of the number of bits per word
  2. Christos Faloutsos, Access methods for text, ACM Computing Surveys 17(1), 49 to 74, 1985, the survey of text access methods, with full text scanning, inversion, signature files and clustering
  3. Justin Zobel, Alistair Moffat and Kotagiri Ramamohanarao, Inverted files versus signature files for text indexing, ACM Transactions on Database Systems 23(4), 453 to 490, 1998, the experimental comparison, with the conclusion that inverted files are distinctly superior to signature files, being faster, smaller and more functional

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.insert
  • a full proof of time.search
  • a full proof of space.total
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)
WritingW4 complete
  • a review of the text: no review record reviews/WA5X66/text.yaml