Algorithm Search⌘K

Data structurecore

Permuterm index

Also called permuterm vocabulary.

Indexes every rotation of each term with an end marker, so a wildcard query becomes a prefix lookup in a search tree.

Time
O(l (l log K + K)) delete · insertO(q log K + r log r + r l q) wildcard_more_starsO(q log K + r log r) wildcard_one_star
Space
O(K l) total
Where
K = the number of keys (L + n); L = the total length of the terms; l = the length of the longest term; n = the number of terms; q = the length of the query; r = the number of keys in the range of the query
Properties
not concurrentnot externalnot persistent

A permuterm index is a search tree, or a sorted array, over all the rotations of the terms of a dictionary, where each term tt gets an end mark and becomes $-terminated: "hello" gives the keys "hello$", "ello$h", "llo$he", "lo$hel", "o$hell" and "$hello", each pointing back to "hello". A wildcard query X*Y matches exactly the terms that have a rotation starting with Y$X, so it becomes one prefix lookup. The price is space: a term of length ℓ\ell has ℓ+1\ell + 1 keys, and Manning, Raghavan and Schuetze report an almost ten-fold space increase for a dictionary of English terms.

In plain words

A search tree over sorted words finds all words that start with "mo" quickly, but not all words that end with "on" or that start with "m" and end with "n". The permuterm index fixes this by turning every word around in all possible ways. Add a mark at the end of the word, then move letters one at a time from the front to the back, and store each result.

Now "m*n" asks for the words that end with "n" and start with "m". Rotate the query in the same way so that the star is at the end: "n, mark, m". Every word that matches has a stored form that starts with exactly these letters, and no other word has one. So one search for a prefix answers the query, with no check afterwards.

The abstract type

The structure holds a set VV of terms, strings over an alphabet without the end mark $ and the wildcard *. The operations are:

  • INSERT(I,t)(I, t) and DELETE(I,t)(I, t): add or remove the term tt.
  • MEMBER(I,t)(I, t): tell if tt is in VV.
  • WILDCARD(I,q)(I, q): return the sorted list of the terms of VV that match qq, where each * stands for any string, also the empty one.

Representation

For each term tt, the ∣t∣+1|t| + 1 rotations ρ0,…,ρ∣t∣\rho_0, \ldots, \rho_{|t|} of the string tt$ are its keys, with ρi=(t$)[i..] (t$)[..i]\rho_i = (t\$)[i..] \, (t\$)[..i]. All keys of all terms are kept in one sorted array, each with a pointer to its term; since the $ marks where the term ends, a key names its term, and two terms never share a key. A balanced search tree or a trie of the keys does the same with cheaper updates. The array has K=L+nK = L + n keys, and stored as strings they take ∑t(∣t∣+1)2\sum_t (|t| + 1)^2 characters; stored as a pointer to the term and a rotation offset, they take O(K)O(K) words.

Operations

A prefix range is found by two binary searches: the first key at least pp, and the first key at least pp followed by a character TOP that sorts after every character of a key.

  1. WILDCARD(I, q)
  2. 1if q has no * then return (q) if q$ is a key of I, else ()
  3. 2X ← the part of q before its first *; Y ← the part after its last *
  4. 3p ← Y $ X ▷ the rotation of X*Y with the star last
  5. 4[lo, hi) ← the range of the keys that start with p
  6. 5if q has exactly one * then return the sorted terms of the keys in [lo, hi)
  7. 6return the sorted terms t of the keys in [lo, hi) with MATCHES(t, q) ▷ the middle pieces
  8. INSERT(I, t)
  9. 7if t$ is a key of I then return
  10. 8for each rotation r of t$ do insert (r, t) into the sorted array of keys

DELETE removes the ∣t∣+1|t| + 1 keys of tt in the same way. MATCHES is the check of the k-gram index page: the first piece as a prefix, the last as a suffix, and the middle pieces in order between them.

The simple forms are cases of line L3: X* gives the prefix $X, X gives the prefix X$, and "mn" gives "n$m", as in Manning, Raghavan and Schuetze. In their query "moer", line L3 gives the prefix "er$"; its range holds "fishmonger" and "filibuster", and line L6 keeps "fishmonger". The code treats X as X*Y with empty X and Y, so its range is every key that starts with $, and line L6 checks every term; the variant below gives the direct lookup.

Example

Start empty and apply these operations.

operation terms keys notes
INSERT list 1 5 $list, ist$l, list$, st$li, t$lis
INSERT lists 2 11 adds the 6 rotations of lists$
INSERT sort 3 16 adds $sort, ort$s, rt$so, sort$, t$sor
WILDCARD li*t 3 16 p = t$li, range (t$lis), answer (list)
WILDCARD *t 3 16 p = t$, range (t$lis, t$sor), answer (list, sort)
WILDCARD lss 3 16 p = s$l, range (s$list), MATCHES keeps lists
DELETE lists 2 10 its 6 keys are removed

The query "li*t" shows the difference from the k-gram index: the range holds only the rotation of "list", and "lists" is never a candidate.

On the 50 terms of the toy collection the index has 284 keys with 1,834 characters in all, against 234 characters for the terms, a factor of 7.8. The query "sed" becomes the prefix "ed$s", whose range is the two keys "ed$sort" and "ed$spe", so the answer is sorted and speed. The query "st*d" becomes the prefix "d$s"; its range gives sorted and speed, and line L6 keeps sorted alone, because "speed" has no t between its s and its final d.

Correctness

The invariant is that the array is sorted, has no repeats, and holds exactly the rotations of tt$ for the terms tt of VV, each with its term; lines L9 and L10 and DELETE keep it. The key fact is that a term tt has a rotation starting with Y$X exactly when t=XSYt = XSY for some string SS, and then exactly one of its rotations starts with Y$X, because $ occurs once in each key. So for one star the range of line L4 holds one key for each answer and nothing else, and line L5 needs no filter. For more stars, X*Y is implied by the query, so the range holds every answer, and line L6 keeps exactly the answers. The full proof is in the proof file of this page.

Proof: A key range of the permuterm index holds exactly the terms with a given prefix and suffix, each oncefull

A term is a string, possibly empty, without the characters $, * and TOP, where TOP is a character that sorts after every character of a term and after $. For a term tt let s=t$s = t\$; the rotations of ss are the ∣t∣+1|t| + 1 strings ρi(t)=s[i..]⋅s[..i)\rho_i(t) = s[i..] \cdot s[..i) for 0≤i≤∣t∣0 \le i \le |t|. A query qq has no $ and no TOP, and each * in it stands for any string. Write q=P0∗P1∗⋯∗Prq = P_0 * P_1 * \cdots * P_r with pieces PiP_i that contain no *. A term tt matches qq if t=P0S1P1⋯SrPrt = P_0 S_1 P_1 \cdots S_r P_r for some strings SiS_i, and the answer over a vocabulary VV is A(q)={t∈V:t matches q}A(q) = \{t \in V : t \text{ matches } q\}.

Invariant (I). The array keyskeys is strictly increasing and is the set {ρi(t):t∈V,0≤i≤∣t∣}\{\rho_i(t) : t \in V, 0 \le i \le |t|\}, and owner[j]owner[j] is the term tt with keys[j]keys[j] a rotation of t$t\$.

Lemma 1 (a key names its term). Each rotation of t$t\$ contains $ exactly once, and the rotations ρ0(t),…,ρ∣t∣(t)\rho_0(t), \ldots, \rho_{|t|}(t) are distinct. A string is a rotation of t$t\$ for at most one term tt.

Proof. The string t$t\$ has one $, and a rotation keeps the multiset of characters. In ρi(t)\rho_i(t) the $ is at position ∣t∣−i|t| - i, so different ii give different positions of $ and different strings. If κ\kappa is a rotation of t$t\$, then rotating κ\kappa so that its $ comes last gives t$t\$ back, so κ\kappa determines tt. □\square

So ownerowner is well defined, and the number of keys is ∑t∈V(∣t∣+1)\sum_{t \in V} (|t| + 1).

Lemma 2. The constructor makes (I) true, and INSERT and DELETE keep it.

Proof. The empty index has no keys and V=∅V = \emptyset. By Lemma 1, the key t$=ρ0(t)t\$ = \rho_0(t) is in keyskeys if and only if t∈Vt \in V, so line L9 tests membership correctly, and INSERT of a term of VV changes nothing. For t∉Vt \notin V, Lemma 1 says that no rotation of t$t\$ is a key yet. Line L10 inserts each rotation at the place that binary search finds for it, with tt at the same place of ownerowner, which keeps keyskeys strictly increasing and ownerowner aligned. At the end keyskeys is the set for V∪{t}V \cup \{t\}. DELETE of t∈Vt \in V finds each rotation of t$t\$ at the place that binary search gives, since it is present, and removes it with its owner; the keys of other terms stay. □\square

Lemma 3 (the prefix range). If keyskeys is sorted, PREFIX-RANGE(p)(p) returns [lo,hi)[lo, hi) such that keys[j]keys[j] starts with pp if and only if lo≤j<hilo \le j < hi.

Proof. Here lolo is the number of keys less than pp, and hihi is the number of keys less than p⋅TOPp \cdot \mathrm{TOP}. A key κ\kappa that starts with pp is at least pp, and it is less than p⋅TOPp \cdot \mathrm{TOP}, because either κ=p\kappa = p or the character of κ\kappa after pp is less than TOP. A key κ<p\kappa < p is less than p⋅TOPp \cdot \mathrm{TOP} too. A key κ≥p\kappa \ge p that does not start with pp is not a proper prefix of pp, so it first differs from pp at a position j<∣p∣j < |p| with κ[j]>p[j]\kappa[j] > p[j], and then κ>p⋅TOP\kappa > p \cdot \mathrm{TOP}. In sorted order the keys are therefore: those less than pp, then those that start with pp, then the others, and the second group is the range [lo,hi)[lo, hi). □\square

Lemma 4 (the rotated query). Let XX and ZZ be strings without $. A term tt has a rotation of t$t\$ that starts with Z$XZ\$X if and only if t=XSZt = X S Z for some string SS, and then exactly one rotation of t$t\$ starts with Z$XZ\$X.

Proof. If t=XSZt = XSZ, then ρ∣XS∣(t)=Z$XS\rho_{|XS|}(t) = Z\$XS starts with Z$XZ\$X. Conversely, let a rotation κ\kappa of t$t\$ start with Z$XZ\$X. Its only $ is at position ∣Z∣|Z|, and the rotation with $ at that position is κ=t[∣t∣−∣Z∣..]⋅$⋅t[..∣t∣−∣Z∣)\kappa = t[|t| - |Z|..] \cdot \$ \cdot t[..|t| - |Z|), which needs ∣Z∣≤∣t∣|Z| \le |t|. So ZZ is the suffix of tt of length ∣Z∣|Z|, and XX is a prefix of t[..∣t∣−∣Z∣)t[..|t| - |Z|), which is t=XSZt = XSZ with SS the rest. Only one rotation has its $ at position ∣Z∣|Z|, so it is the only one that starts with Z$Z\$. □\square

Theorem. If (I) holds, WILDCARD(q)(q) returns A(q)A(q) in increasing order, with no term twice.

Proof. If qq has no *, then A(q)A(q) is {q}\{q\} when q∈Vq \in V and empty otherwise, and line L1 returns this by the membership test of Lemma 2.

Let qq have at least one *. Line L2 sets X=P0X = P_0, the part before the first *, and Z=PrZ = P_r, the part after the last *. Line L3 forms p=Z$Xp = Z\$X, and by Lemma 3 line L4 finds the keys that start with pp. By Lemmas 1 and 4, their owners are the terms t∈Vt \in V with t=XSZt = XSZ for some SS, each exactly once.

If qq has exactly one *, then q=X∗Zq = X * Z, and tt matches qq exactly when t=XSZt = XSZ. So the owners of the range are A(q)A(q), each once, and line L5 returns them sorted with no filter.

If qq has two or more stars, every tt that matches qq has the form XSZX S Z with S=S1P1⋯SrS = S_1 P_1 \cdots S_r, so A(q)A(q) is contained in the owners of the range, each once. Line L6 keeps the owners that pass MATCHES. That test is the same as on the k-gram index page, where it is proved to return true if and only if tt matches qq. So line L6 returns exactly A(q)A(q), sorted, with no repeats. ■\blacksquare

Complexity

operation time notes
MEMBER O(ℓlog⁡K)O(\ell \log K) one binary search with string comparisons
INSERT, DELETE O(ℓ(ℓlog⁡K+K))O(\ell(\ell \log K + K)) ℓ+1\ell + 1 keys, each placed by binary search and an array shift
WILDCARD, one star O(qlog⁡K+rlog⁡r)O(q \log K + r \log r) two binary searches, then sort the rr terms found
WILDCARD, more stars O(qlog⁡K+rlog⁡r+rℓq)O(q \log K + r \log r + r \ell q) plus one MATCHES for each of the rr terms
space O(Kℓ)O(K\ell) characters O(K)O(K) words if a key is a term and an offset

With a balanced tree in place of the array, an insertion costs O(ℓ2log⁡K)O(\ell^2 \log K). The query cost does not depend on the number of terms that do not match, which is the main gain over a scan of the dictionary.

Variants

  • Infix queries. For X, take the keys that start with X: a term contains X exactly when some rotation of tt$ starts with X. A term can have several such keys, so remove repeats. On the toy vocabulary, "or" gives the four keys "or$f", "ore$sc", "ort$s" and "orted$s", which are the answer.
  • Keys as offsets. Store each key as a pointer to the term and a rotation offset, and compare by reading the term from that offset. This cuts the space to O(K)O(K) words and makes each comparison a little slower.
  • Compressed permuterm index. Ferragina and Venturini (2007), as cited by Manning, Raghavan and Schuetze, give an approach to the space blowup of the permuterm index. Sorted rotations are also the base of the Burrows-Wheeler transform and the FM-index, which store them in compressed form.
  • Search tree and reverse search tree. For queries with one star only, a B-tree of the terms and one of the reversed terms answer X* and Y; XY is the intersection of the two results. This takes two copies of the dictionary, not ℓ+1\ell + 1, but needs an intersection.

When to use it

Use it when queries have one star, anywhere in the term, and must be fast and exact, and when the dictionary is small enough to store about ten times over. For long dictionaries with frequent updates or tight memory, the k-gram index is smaller, at the cost of a postfilter for every query. For queries with only a trailing star, a plain search tree is enough.

Pitfalls

  • Rotating the query the wrong way. The prefix is the part after the last star, then $, then the part before the first star: "m*n" becomes "n$m", not "m$n".
  • The end of the range. The range must end at the first key at least the prefix followed by a character above every key character. With a TOP that can occur in a term, keys are lost at the end of the range.
  • The end mark in a term. A term that contains $ has two marks in its keys, and a key no longer names its term. Reject such terms.
  • More than one star. The range of the outer pieces is a superset of the answer; skip line L6 and "std" returns "speed".
  • Space. Each term is stored ℓ+1\ell + 1 times, and as strings the keys of a term take (ℓ+1)2(\ell + 1)^2 characters. On the toy vocabulary the strings take 7.8 times the space of the terms.

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
permuterm_index.py 120 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/permuterm-index/. The authors are listed in prov/J3EW3B.jsonl.
"""A permuterm index of a vocabulary, for wildcard queries.

Each term t gets the end mark $, and every rotation of t$ is a key that
points back to t. The keys are kept in one sorted array. A query X*Y is
rotated to Y$X, and the answer is the set of terms whose keys start with
Y$X: one binary search for each end of the range. With more than one *,
the outer pieces give the range and a postfilter checks the middle pieces.
"""

import bisect

MARK = "$"
STAR = "*"
TOP = "\U0010ffff"  # sorts after every letter of a term and after $


def rotations(t: str) -> list[str]:
    """Return the |t| + 1 rotations of t$, starting with t$ itself. Cost O(|t|^2)."""
    s = t + MARK
    return [s[i:] + s[:i] for i in range(len(s))]


def matches(t: str, q: str) -> bool:
    """Tell if t matches q, where * stands for any string. Cost O(|t| |q|) at most."""
    pieces = q.split(STAR)
    if len(pieces) == 1:
        return t == q
    first, last = pieces[0], pieces[-1]
    if len(first) + len(last) > len(t) or not t.startswith(first) or not t.endswith(last):
        return False
    pos, end = len(first), len(t) - len(last)
    for p in pieces[1:-1]:
        i = t.find(p, pos, end)
        if i < 0:
            return False
        pos = i + len(p)
    return True


class PermutermIndex:
    """A sorted array of (key, term) pairs, one pair for each rotation of t$ of each term t.

    Terms are strings without $, * and the character TOP; the empty term is
    allowed. Invariant: keys is sorted, has no repeats, and holds exactly the
    rotations of t$ for the terms t of the vocabulary; owner[i] is the term of
    keys[i].
    """

    def __init__(self) -> None:
        self.keys: list[str] = []
        self.owner: list[str] = []
        self.count = 0

    def __len__(self) -> int:
        return self.count

    def __contains__(self, t: str) -> bool:
        key = t + MARK
        i = bisect.bisect_left(self.keys, key)
        return i < len(self.keys) and self.keys[i] == key

    def insert(self, t: str) -> None:
        """Add the term t. Cost O(|t|) binary searches, plus O(|t| K) to shift the arrays of K keys."""
        if MARK in t or STAR in t or TOP in t:
            raise ValueError("a term has no $, * or TOP")
        if t in self:  # @line L9
            return
        for r in rotations(t):  # @line L10
            i = bisect.bisect_left(self.keys, r)
            self.keys.insert(i, r)
            self.owner.insert(i, t)
        self.count += 1

    def delete(self, t: str) -> None:
        """Remove the term t if it is present. Same cost as insert."""
        if t not in self:
            return
        for r in rotations(t):
            i = bisect.bisect_left(self.keys, r)
            del self.keys[i]
            del self.owner[i]
        self.count -= 1

    def prefix_range(self, p: str) -> tuple[int, int]:
        """Return the range [lo, hi) of the keys that start with p. Cost O(|p| log K)."""
        return bisect.bisect_left(self.keys, p), bisect.bisect_left(self.keys, p + TOP)

    def wildcard(self, q: str) -> list[str]:
        """Return the sorted list of the terms that match q, where * stands for any string.

        Precondition: q has no $ and no TOP. Cost: O(|q| log K) for the range, plus
        O(r log r) to sort the r terms found; with two or more *, also
        O(|t| |q|) to check each term t of the range.
        """
        if STAR not in q:  # @line L1
            return [q] if q in self else []
        x, z = q[: q.index(STAR)], q[q.rindex(STAR) + 1 :]  # @line L2
        p = z + MARK + x  # @line L3
        lo, hi = self.prefix_range(p)  # @line L4
        c = self.owner[lo:hi]
        if q.count(STAR) == 1:  # @line L5
            return sorted(c)
        return sorted(t for t in c if matches(t, q))  # @line L6

    def range_terms(self, q: str) -> list[str]:
        """Return the terms of the key range of q before any postfilter, sorted. Precondition: q has a *."""
        x, z = q[: q.index(STAR)], q[q.rindex(STAR) + 1 :]
        lo, hi = self.prefix_range(z + MARK + x)
        return sorted(self.owner[lo:hi])

    def check_invariant(self) -> None:
        """Raise AssertionError unless keys and owner hold exactly the rotations of the terms, sorted."""
        assert len(self.keys) == len(self.owner)
        assert all(self.keys[i] < self.keys[i + 1] for i in range(len(self.keys) - 1))
        terms = {t for t in self.owner}
        assert len(terms) == self.count
        want = sorted((r, t) for t in terms for r in rotations(t))
        assert want == list(zip(self.keys, self.owner))
test_permuterm_index.py 118 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/permuterm-index/. The authors are listed in prov/J3EW3B.jsonl.

import fnmatch
import random
import re

import pytest

import irtoy
from permuterm_index import PermutermIndex, matches, rotations


def scan(vocab, q):
    """The oracle: a direct scan of the vocabulary with fnmatch, checked against a regular expression."""
    by_fn = sorted(t for t in vocab if fnmatch.fnmatchcase(t, q))
    rx = re.compile(".*".join(re.escape(p) for p in q.split("*")))
    assert by_fn == sorted(t for t in vocab if rx.fullmatch(t))
    return by_fn


def build(terms):
    idx = PermutermIndex()
    for t in terms:
        idx.insert(t)
        idx.check_invariant()
    return idx


def test_rotations_of_hello():
    assert rotations("hello") == ["hello$", "ello$h", "llo$he", "lo$hel", "o$hell", "$hello"]


def test_examples_of_manning_raghavan_schuetze():
    idx = build(["man", "moron", "moon", "melon", "fishmonger", "filibuster", "hello"])
    assert idx.wildcard("m*n") == ["man", "melon", "moon", "moron"]
    assert idx.wildcard("hel*") == ["hello"] and idx.wildcard("*llo") == ["hello"]
    assert idx.wildcard("hello") == ["hello"]
    # *mo*er: the key range of er$ holds both terms; the postfilter keeps one.
    assert idx.range_terms("*mo*er") == ["filibuster", "fishmonger"]
    assert idx.wildcard("*mo*er") == ["fishmonger"]


def test_worked_example_on_the_toy_vocabulary():
    vocab = sorted({t for d in irtoy.DOCS for t in irtoy.tokenize(irtoy.DOCS[d])})
    idx = build(vocab)
    assert len(idx) == 50 and len(idx.keys) == 284
    assert idx.wildcard("s*ed") == ["sorted", "speed"]
    assert idx.wildcard("li*t") == ["list"]
    assert idx.wildcard("*ing") == ["encoding", "posting"]
    assert idx.wildcard("in*") == ["in", "index", "into", "inverted"]
    assert idx.range_terms("s*t*d") == ["sorted", "speed"]
    assert idx.wildcard("s*t*d") == ["sorted"]
    lo, hi = idx.prefix_range("ed$s")
    assert idx.keys[lo:hi] == ["ed$sort", "ed$spe"]


def test_one_star_needs_no_postfilter():
    rng = random.Random(11)
    for _ in range(300):
        vocab = {"".join(rng.choice("abc") for _ in range(rng.randint(0, 6))) for _ in range(rng.randint(0, 25))}
        idx = build(vocab)
        for _ in range(10):
            x = "".join(rng.choice("abc") for _ in range(rng.randint(0, 3)))
            y = "".join(rng.choice("abc") for _ in range(rng.randint(0, 3)))
            q = x + "*" + y
            assert idx.range_terms(q) == scan(vocab, q)


def test_edge_cases():
    idx = PermutermIndex()
    assert idx.wildcard("*") == [] and idx.wildcard("a") == [] and idx.wildcard("a*b*c") == []
    idx.insert("")
    idx.insert("a")
    idx.insert("a")
    idx.check_invariant()
    assert len(idx) == 2 and idx.keys == ["$", "$a", "a$"]
    assert idx.wildcard("*") == ["", "a"] and idx.wildcard("") == [""] and idx.wildcard("a*a") == []
    assert idx.wildcard("**") == ["", "a"] and idx.wildcard("*a*") == ["a"]
    idx.delete("b")
    idx.delete("")
    idx.check_invariant()
    assert idx.wildcard("*") == ["a"]
    with pytest.raises(ValueError):
        idx.insert("a$")
    assert matches("abcb", "a*b*b") and not matches("ab", "a*b*b")


def test_random_operations_against_a_scan():
    rng = random.Random(1976)
    needed = 0
    for _ in range(300):
        idx = PermutermIndex()
        model: set[str] = set()
        letters = "ab" if rng.random() < 0.5 else "abcd"
        for _ in range(40):
            r = rng.random()
            if r < 0.5:
                t = "".join(rng.choice(letters) for _ in range(rng.randint(0, 6)))
                idx.insert(t)
                model.add(t)
            elif r < 0.65 and model:
                t = rng.choice(sorted(model))
                idx.delete(t)
                model.discard(t)
            else:
                pieces = ["".join(rng.choice(letters) for _ in range(rng.randint(0, 3))) for _ in range(rng.randint(1, 4))]
                q = "*".join(pieces)
                want = scan(model, q)
                assert idx.wildcard(q) == want
                if "*" in q:
                    cand = idx.range_terms(q)
                    assert set(want) <= set(cand)
                    needed += cand != want
            idx.check_invariant()
            assert sorted(set(idx.owner)) == sorted(model) and len(idx) == len(model)
    # With two or more *, the range alone is often too large.
    assert needed > 50

History

Manning, Raghavan and Schuetze credit Garfield (1976) with one of the first complete descriptions of the permuterm index. Witten, Moffat and Bell describe the same idea as a rotated lexicon and compare it with an index of n-grams of the lexicon.

References

  1. Christopher D. Manning, Prabhakar Raghavan and Hinrich Schuetze, Introduction to Information Retrieval, Cambridge University Press, 2008, Chapter 3, Section 3.2.1 (permuterm indexes, the end mark $ and the rotations of hello$, the query m*n rotated to n$m*, and the query *mo*er, answered by the range of er$ and a filter that keeps fishmonger and removes filibuster), Section 3.2.2 (the almost ten-fold space increase for a dictionary of English terms), and Section 3.5 (Garfield 1976 and Ferragina and Venturini 2007)
  2. Ian H. Witten, Alistair Moffat and Timothy C. Bell, Managing Gigabytes, Compressing and Indexing Documents and Images, second edition, Morgan Kaufmann, 1999, Chapter 4, Section 4.2 (partially specified query terms, with rotated lexicons compared with an index of n-grams and with a scan of the lexicon)

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.delete
  • a full proof of time.insert
  • a full proof of time.wildcard_more_stars
  • a full proof of time.wildcard_one_star
  • 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)
WritingW2 basic
  • at least three sources