Algorithm Search⌘K

Data structureresearch

PGM-index

Also called piecewise geometric model index.

A learned index of recursive piecewise linear models with a guaranteed error bound, built optimally in one pass over the sorted keys.

Time
O(log m + log ε) worst · averageO(log ε) best
Space
Θ(m) extra
Where
m = the number of segments on the bottom level; n = the number of keys; ε = the error bound of the bottom level; ε' = the error bound of the upper levels (a constant)
Properties
deterministicexactnot externalnot in placeofflinerecursive
Origin
Paolo Ferragina, Giorgio Vinciguerra, 2020

The PGM-index (piecewise geometric model index) is a learned index for a sorted array of keys. It replaces the nodes of a B+ tree by line segments: each segment takes a key and predicts its position in the array, and every prediction is within a fixed error ε\varepsilon of the true position. The segments are the fewest that meet the error bound, and they are found in one pass over the keys. The first keys of the segments are indexed in the same way, level by level, until one segment remains. A lookup follows one segment per level and finishes with a binary search over at most 2ε+12\varepsilon + 1 positions.

In plain words

Plot the sorted keys on a graph: the key across, its position in the array up. The points climb from left to right. Over a short stretch they lie almost on a straight line, so a line can stand in for all of them: give it a key, and it says roughly where the key is.

The PGM-index draws as few lines as it can, under one rule: no point may be more than ε\varepsilon places away from its line. To find a key, pick the right line, read off a guess, and look only at the 2ε+12\varepsilon + 1 places around the guess. To pick the right line, the index uses the same trick again on the first keys of the lines, so it is a short tree of lines.

The abstract type

A static set of nn distinct keys, stored sorted in an array K[0..n−1]K[0..n-1].

  • rank(x): the number of keys ≤x\le x. This gives predecessor search, membership and range queries.
  • lower_bound(x): the position of the first key ≥x\ge x.
  • contains(x) and range(lo, hi): membership, and the keys in [lo,hi][lo, hi].

The keys stay in the array. The index is the extra data that finds a position, as with a sparse index over a sorted file.

Representation

A segment is a triple (key, slope, intercept) and the run of positions a..ba..b that it covers. It predicts f(x)=intercept+slope⋅(x−key)f(x) = intercept + slope \cdot (x - key). A piecewise linear ε\varepsilon-approximation (PLA) of an array AA is a list of segments that cover the positions 0..N−10..N-1 in runs, with ∣f(A[i])−i∣≤ε|f(A[i]) - i| \le \varepsilon for every covered ii.

The index has levels. The bottom level is a PLA of KK with the error ε\varepsilon. The next level is a PLA, with the error ε′\varepsilon', of the array of the first keys of the bottom segments, and so on until a level has one segment, the root.

Operations

The PLA is built greedily: a segment starts at a point and grows while some line is still within ee of all of its points. The set of such lines is a convex polygon in the plane of (slope, intercept). Each new point (xj,j)(x_j, j) cuts the polygon with the two half-planes j−e≤c+s(xj−xi)≤j+ej - e \le c + s(x_j - x_i) \le j + e. When the polygon becomes empty, the segment ends before that point.

  1. BUILD-PLA(A[0..N-1], e)
  2. 1i ← 0
  3. 2while i < N do
  4. 3P ← the lines within e of the points (A[i], i) and (A[i+1], i+1)
  5. 4j ← i + 2
  6. 5while j < N and P cut by the strip of the point (A[j], j) is not empty do
  7. 6P ← that cut; j ← j + 1
  8. 7output a segment with key A[i], a line from P and the positions i..j-1
  9. 8i ← j
  10. BUILD-PGM(K, ε, ε')
  11. 9A ← K; e ← ε
  12. 10repeat S ← BUILD-PLA(A, e); store S as a level
  13. 11A ← the first keys of the segments of S; e ← ε'
  14. 12until S has one segment

A query predicts a position, clamps it to the run of the segment, and searches a window of 2e+12e + 1 entries around it. The result names the segment of the next level down.

  1. RANK(x) ▷ the number of keys ≤ x
  2. 1if x < K[0] then return 0
  3. 2s ← the root segment
  4. 3for each level, from the root down do
  5. 4p ← ⌊f_s(x) clamped to [s.start, s.end]⌋
  6. 5r ← the number of entries ≤ x of the array of this level, by binary search in the positions max(s.start, p - e) to min(s.end + 1, p + e + 1)
  7. 6if this is the bottom level then return r
  8. 7s ← the segment of the next level whose first key is entry r - 1

The code uses exact fractions, so the test "is the polygon empty" has no rounding error. A segment with one point gets a flat line. If the chosen line has a negative slope, the code uses the flat line at the middle of the run, which is then valid (see the proof). The paper builds the PLA in O(N)O(N) time by keeping the convex hulls of the upper and lower ends of the strips (its Lemma 1, after O'Rourke 1981). The polygon of this page is easier to check and gives the same segments in count, but each cut costs time in the size of the polygon.

Example

Take the 12 keys

K=[2,3,5,8,12,13,14,20,30,31,40,41]K = [2, 3, 5, 8, 12, 13, 14, 20, 30, 31, 40, 41]

with ε=ε′=1\varepsilon = \varepsilon' = 1.

  1. Bottom level. The greedy segment from position 0 grows over the keys 2 to 20 (positions 0 to 7). At the key 30 (position 8) no line is within 1 of all nine points, so the segment ends. The code's line is f(x)=19/60+(49/120)(x−2)f(x) = 19/60 + (49/120)(x - 2). For example, f(13)=577/120≈4.81f(13) = 577/120 \approx 4.81 against the position 5, and f(20)=920/120≈7.67f(20) = 920/120 \approx 7.67 against 7. The second segment covers the keys 30 to 41 (positions 8 to 11).
  2. Root. The first keys are [2,30][2, 30], and one segment covers them, with f(x)=(x−2)/28f(x) = (x - 2)/28. The index has 2 levels and 3 segments.
  3. rank(13). The root predicts 11/28≈0.3911/28 \approx 0.39, so p=0p = 0. The window is the positions 0 to 1 of [2,30][2, 30], and the count of entries ≤13\le 13 is 1, so the next segment is the first bottom segment. It predicts 4.81, so p=4p = 4, and the window is the positions 3 to 5, with the keys 8, 12 and 13. The count is 6: six keys are ≤13\le 13.
  4. lower_bound(25). The root again picks the first bottom segment. It predicts f(25)≈9.7f(25) \approx 9.7, which is past the run 0 to 7, so the clamp gives p=7p = 7. The window is the positions 6 and 7, with the keys 14 and 20, and the count is 8. The key 25 is not present, and it would go at position 8.

Sizes (measurement). On 10,000 keys in clusters (seed 5 in the test file), the bottom level has 495 segments for ε=4\varepsilon = 4, 117 for ε=16\varepsilon = 16 and 16 for ε=64\varepsilon = 64. With ε′=4\varepsilon' = 4 the index has 3, 2 and 2 levels. A uniform sample of 10,000 keys from a range of 100,010 values needs 121 segments for ε=4\varepsilon = 4 and a single segment for ε=64\varepsilon = 64.

Correctness

The proofs are in proofs/correctness.md.

  • Theorem (optimal PLA). The greedy BUILD-PLA gives the fewest segments of any PLA with the error ee. The proof is an exchange argument: if any valid segment covers a run, then any shorter run inside it also has one, so the greedy end of the tt-th segment is never before the tt-th end of an optimal PLA.
  • Theorem (segment length). Every segment but the last covers at least 2e+12e + 1 positions, because the flat line at height i+ei + e is within ee of the positions ii to i+2ei + 2e. So m≤⌈n/(2ε+1)⌉m \le \lceil n / (2\varepsilon + 1) \rceil. The paper states this as at least 2ε2\varepsilon keys per segment (its Lemma 2).
  • Theorem (search). If xx lies between the first key of a segment and the first key of the next one, then its rank in the array of that level is within ee of the clamped prediction, with one more place on the right for keys between two array entries. So the window at L17 holds the answer, and induction on the levels shows that RANK returns the number of keys ≤x\le x.
Proof: The greedy PLA is optimal, each level shrinks by a factor of 2 epsilon + 1, and the windowed search finds the rankfull

We use the notation of the page. A level array A[0..N−1]A[0..N-1] is strictly increasing. A segment ss covers the positions a..ba..b of AA and predicts fs(x)=s.intercept+s.slope⋅(x−s.key)f_s(x) = s.intercept + s.slope \cdot (x - s.key), with s.key=A[a]s.key = A[a]. A segment is valid for the error ee if ∣fs(A[i])−i∣≤e|f_s(A[i]) - i| \le e for a≤i≤ba \le i \le b. The rank of xx is r(x)=∣{i:A[i]≤x}∣r(x) = |\{i : A[i] \le x\}|. The errors ee are integers at least 1.

Lemma 1 (the feasible region). For a fixed x0x_0, the set of pairs (s,c)(s, c) such that the line c+s(x−x0)c + s (x - x_0) is within ee of all of the points (A[i],i)(A[i], i), a≤i≤ja \le i \le j, is the intersection of the strips i−e≤c+s(A[i]−x0)≤i+ei - e \le c + s (A[i] - x_0) \le i + e. It is convex. For j=a+1j = a + 1 it is the parallelogram with the four vertices that BUILD-PLA makes at L3.

Proof. Each strip is the closed set between two parallel lines in the (s,c)(s, c) plane, so it is convex, and an intersection of convex sets is convex. For two points, the line takes the values cc at A[a]=x0A[a] = x_0 and c+sdc + s d at A[a+1]A[a+1], with d=A[a+1]−x0>0d = A[a+1] - x_0 > 0. The map (s,c)↦(c,c+sd)(s, c) \mapsto (c, c + s d) is a linear bijection, and the two conditions say that the image lies in the square [a−e,a+e]×[a+1−e,a+1+e][a - e, a + e] \times [a + 1 - e, a + 1 + e]. The four vertices at L3 are the preimages of the corners of the square, in order around it. □\square

_clip cuts a convex polygon with a half-plane by the Sutherland and Hodgman rule: it keeps the vertices inside and adds the point where an edge crosses the boundary. For a convex polygon this gives the exact intersection, and the arithmetic uses exact fractions. So at every step the polygon is exactly the feasible region of Lemma 1, and the loop at L5 stops at the first jj for which no valid line exists. The mean of the vertices is a convex combination of points of the region, so it is in the region.

Lemma 2 (a flat line). If some valid line over a..ba..b has a negative slope, then b−a<2eb - a < 2e, and the flat line at height (a+b)/2(a + b) / 2 is valid over a..ba..b.

Proof. Let u=f(A[a])u = f(A[a]) and w=f(A[b])w = f(A[b]). A negative slope gives w<uw < u, and validity gives u≤a+eu \le a + e and w≥b−ew \ge b - e. So b−e<a+eb - e < a + e, which is b−a<2eb - a < 2e. For a≤i≤ba \le i \le b, ∣(a+b)/2−i∣≤(b−a)/2<e|(a + b)/2 - i| \le (b - a)/2 < e. □\square

So the code replaces a mean with a negative slope by the flat line of Lemma 2, and every segment it outputs is valid and has a slope of at least 0.

Lemma 3 (prefix closure). If a valid segment over a..ba..b exists, then a valid segment over a′..b′a'..b' with a≤a′≤b′≤ba \le a' \le b' \le b exists.

Proof. Removing points removes constraints. □\square

Theorem 1 (the greedy PLA is optimal). Let gg be the number of segments of BUILD-PLA with the error ee, and let hh be the fewest segments of any PLA of AA with the error ee in which each segment covers a run of consecutive positions. Then g=hg = h.

Proof. Let the greedy segments end at b1<b2<⋯<bg=N−1b_1 < b_2 < \cdots < b_g = N - 1, and let an optimal PLA have segments that end at c1<⋯<ch=N−1c_1 < \cdots < c_h = N - 1. We show bt≥ctb_t \ge c_t for each t≤min⁡(g,h)t \le \min(g, h) by induction. For t=1t = 1: the optimal first segment covers 0..c10..c_1 and is valid, and the greedy segment from 0 grows as long as a valid line exists, so b1≥c1b_1 \ge c_1. For the step, suppose bt≥ctb_t \ge c_t and t<gt < g. If bt≥ct+1b_t \ge c_{t+1}, then bt+1>bt≥ct+1b_{t+1} > b_t \ge c_{t+1}. Otherwise the optimal segment t+1t + 1 covers ct+1..ct+1c_t + 1..c_{t+1}, which contains bt+1..ct+1b_t + 1..c_{t+1}. By Lemma 3 a valid segment over bt+1..ct+1b_t + 1..c_{t+1} exists, and the greedy segment t+1t + 1 starts at bt+1b_t + 1, so it ends at bt+1≥ct+1b_{t+1} \ge c_{t+1}. If g>hg > h, this gives bh≥ch=N−1b_h \ge c_h = N - 1, so the greedy method would have stopped after hh segments, which is false. So g≤hg \le h, and g≥hg \ge h because the greedy PLA is a PLA of this kind. □\square

Lemma 4 (segment length). Every segment of BUILD-PLA other than the last covers at least 2e+12e + 1 positions. So a level with NN entries has at most ⌈N/(2e+1)⌉\lceil N / (2e + 1) \rceil segments.

Proof. For any aa, the flat line at height a+ea + e is within ee of the points (A[i],i)(A[i], i) for a≤i≤a+2ea \le i \le a + 2e, because ∣i−(a+e)∣≤e|i - (a + e)| \le e. So a valid segment over a..min⁡(a+2e,N−1)a..\min(a + 2e, N - 1) exists, and the greedy segment from aa is at least that long. A segment that is not the last ends before N−1N - 1, so it covers at least 2e+12e + 1 positions. □\square

The paper (Lemma 2) states the bound with 2e2e keys per segment; Lemma 4 gives the slightly better 2e+12e + 1 for an integer ee. With the inner error e′≥1e' \ge 1, each level above the bottom has at most a third of the entries of the level below, so the number of levels is at most 1+⌈log⁡2e′+1m⌉1 + \lceil \log_{2e'+1} m \rceil for mm bottom segments, and the construction stops with one segment.

Lemma 5 (the window). Let ss be a segment over a..ba..b of AA with the error ee and a slope of at least 0. Let xx satisfy A[a]≤xA[a] \le x, and x<A[b+1]x < A[b + 1] if b+1<Nb + 1 < N. Let qq be fs(x)f_s(x) clamped to [a,b][a, b], and p=⌊q⌋p = \lfloor q \rfloor. Then r(x)r(x) lies in [max⁡(a,p−e),min⁡(b+1,p+e+1)][\max(a, p - e), \min(b + 1, p + e + 1)].

Proof. From the conditions on xx, a+1≤r(x)≤b+1a + 1 \le r(x) \le b + 1. Let i=r(x)−1i = r(x) - 1. Then a≤i≤ba \le i \le b, A[i]≤xA[i] \le x, and x<A[i+1]x < A[i + 1] if i<bi < b. Let f^\hat f be fsf_s clamped to [a,b][a, b]. It is nondecreasing, because fsf_s and the clamp are. Clamping a value yy to [a,b][a, b] gives a value between yy and any point of [a,b][a, b], so for yy within ee of a point of [a,b][a, b], the clamped value is also within ee of that point.

So q=f^(x)≥f^(A[i])≥i−eq = \hat f(x) \ge \hat f(A[i]) \ge i - e. If i<bi < b, then q≤f^(A[i+1])≤i+1+eq \le \hat f(A[i + 1]) \le i + 1 + e. If i=bi = b, then q≤b=iq \le b = i. In both cases i−e≤q≤i+1+ei - e \le q \le i + 1 + e, so q−e≤r(x)≤q+e+1q - e \le r(x) \le q + e + 1. Since r(x)r(x) is an integer, r(x)≥⌈q⌉−e≥p−er(x) \ge \lceil q \rceil - e \ge p - e and r(x)≤⌊q+e+1⌋=p+e+1r(x) \le \lfloor q + e + 1 \rfloor = p + e + 1. With a+1≤r(x)≤b+1a + 1 \le r(x) \le b + 1, the claim follows. □\square

Theorem 2 (search). QUERY(x)(x) returns r(x)r(x) for the key array KK, and the window of each level has at most 2e+22e + 2 positions, where ee is the error of that level.

Proof. If x<K[0]x < K[0], L13 returns 0=r(x)0 = r(x). Otherwise every level array starts with K[0]≤xK[0] \le x, because the first key of the first segment of each level is K[0]K[0]. The root segment covers its whole array, so it satisfies the conditions of Lemma 5. Suppose a segment ss of some level satisfies them. By Lemma 5 the window at L17 contains r(x)r(x), and the entries of the array before the window are ≤x\le x and the entries after it are >x> x. So the binary search, which counts the entries ≤x\le x inside the window and adds the start of the window, returns r(x)r(x). If this is the bottom level, L18 returns it. Otherwise r(x)≥1r(x) \ge 1, and the entry r(x)−1r(x) - 1 of the array is the first key of a segment tt of the level below, with t.key≤xt.key \le x, and with the first key of the next segment >x> x if there is one. That is, tt satisfies the conditions of Lemma 5 for its own array, and L19 continues with tt. The window holds min⁡(b+1,p+e+1)−max⁡(a,p−e)+1≤2e+2\min(b + 1, p + e + 1) - \max(a, p - e) + 1 \le 2e + 2 candidate values of r(x)r(x), which is 2e+12e + 1 array entries to compare. □\square

The tests check Theorem 1 against a dynamic program over all splits into runs, with a brute-force validity test by Helly's theorem: a run is valid if and only if every three of its points are, and three points are if and only if the middle one is within 2e2e of the line through the outer two. They check Lemma 4, the error bound of every segment, and Theorem 2 against bisect on three key distributions.

Complexity

  • Query (theorem). Each level costs one prediction and a binary search over at most 2e+12e + 1 entries. With ε′\varepsilon' a constant, every upper level has at most 1/(2ε′+1)1/(2\varepsilon' + 1) of the entries of the level below, so there are O(log⁡m)O(\log m) levels, and a query takes O(log⁡m+log⁡ε)O(\log m + \log \varepsilon) time. This is the bound of Theorem 1 of the paper.
  • Space (theorem). mm segments on the bottom level, and O(m/ε′)O(m / \varepsilon') on all the levels above it together, because each level is at most 1/(2ε′+1)1/(2\varepsilon' + 1) of the one below. Each segment is a key and two numbers. The keys themselves are not counted.
  • Build. The paper's convex-hull method builds each level in time linear in its size. The polygon method of the code takes time in the size of the polygon per point.
  • Trade-off. A larger ε\varepsilon gives fewer segments and a longer final search. The measurement in the Example shows how fast mm falls with ε\varepsilon on clustered data.

In the word RAM model each operation on a key or a fraction costs O(1)O(1); the code uses exact fractions only to make the tests exact.

Variants

  • Dynamic PGM-index. The paper supports inserts and deletes by the logarithmic method: a set of static PGM-indexes of sizes that grow by powers of two, merged and rebuilt when one fills (its Theorem 2). Inserts can also go to a buffer.
  • Compressed PGM-index. The paper compresses the intercepts and the slopes of the segments, which reduces the space further at the same error.
  • Distribution-aware PGM-index. If the frequency of queries is known, the error bound can be smaller for keys that are queried often.
  • Choosing ε from a budget. The paper also gives a version that picks ε\varepsilon to meet a space bound or a time bound.
  • Other learned indexes. The recursive model index of Kraska et al. (2018) trains a fixed number of models and stores their measured errors, with no bound before training. ALEX adds gaps to its arrays to support inserts.

When to use it

Use a PGM-index for a large sorted array that is read much more often than it changes, such as a column of a read-only table or a sorted run of an LSM tree, when the space of the index matters. For a workload with many updates, or for variable-length keys such as strings, a B+ tree is the simpler choice. The paper reports, as a measurement, that the PGM-index used 63.3% less space than the FITing-tree, another index of linear segments.

Pitfalls

  • Rounding in the build. With floating-point numbers, the test "is the polygon empty" can be wrong for large keys, and a segment can break the error bound. Store the slopes with enough precision, or check the bound after the build.
  • Keys between segments. A key that is not in the array can be past the last key of its segment, and the line can then predict a position far outside the run. Clamp the prediction to the run before the window search.
  • Duplicate keys. The proofs assume distinct keys. With duplicates, index the distinct keys or the first position of each key.
  • Error bound for one level only. The upper levels need their own error ε′\varepsilon'. A large ε′\varepsilon' saves little space, because the upper levels are already small, and it makes each step longer.
  • Static by design. One insert can change the optimal segments of a whole level. Use the dynamic version, or a buffer, for updates.

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.

pgm_index.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/pgm-index/. The authors are listed in prov/YYKWMY.jsonl.

"""PGM-index of Ferragina and Vinciguerra (2020), static version.

The bottom level is an optimal piecewise linear approximation (PLA) of the
points (key, position) with a maximum error eps: every key is predicted
within eps of its position. The first keys of the segments are indexed in the
same way with the error eps_rec, level by level, until one segment is left.

The PLA is built greedily: a segment grows while some line stays within eps of
all its points. The set of such lines is a convex polygon in the (slope,
intercept) plane. Each new point cuts the polygon with two half-planes. The
arithmetic uses Fraction, so the test "is the polygon empty" is exact.
"""

from bisect import bisect_right
from fractions import Fraction
from typing import List, Sequence, Tuple


class Segment:
    __slots__ = ("key", "slope", "intercept", "start", "end")

    def __init__(self, key, slope, intercept, start: int, end: int):
        self.key = key              # the first key covered
        self.slope = slope
        self.intercept = intercept
        self.start = start          # the positions start..end of the level array
        self.end = end

    def predict(self, x) -> Fraction:
        return self.intercept + self.slope * (x - self.key)

    def __repr__(self):
        return f"Segment(key={self.key}, slope={self.slope}, intercept={self.intercept}, {self.start}..{self.end})"


Point = Tuple[Fraction, Fraction]   # (slope, intercept)


def _clip(poly: List[Point], dx, lo, hi) -> List[Point]:
    """Cut the convex polygon with lo <= s * dx + c <= hi."""
    for sign, bound in ((1, hi), (-1, -lo)):
        out: List[Point] = []
        n = len(poly)
        for i in range(n):
            p, q = poly[i], poly[(i + 1) % n]
            hp = bound - sign * (p[0] * dx + p[1])
            hq = bound - sign * (q[0] * dx + q[1])
            if hp >= 0:
                out.append(p)
            if (hp > 0 > hq) or (hp < 0 < hq):
                t = hp / (hp - hq)
                out.append((p[0] + t * (q[0] - p[0]), p[1] + t * (q[1] - p[1])))
        poly = out
        if not poly:
            break
    return poly


def build_pla(xs: Sequence[int], eps: int, base: int = 0) -> List[Segment]:
    """The greedy PLA of the points (xs[i], base + i) with the error eps.

    It gives the fewest segments of any PLA with the error eps.
    """
    segs: List[Segment] = []
    n = len(xs)
    i = 0                                                            # @line L1
    while i < n:                                                     # @line L2
        x0 = xs[i]
        if i == n - 1:
            segs.append(Segment(x0, Fraction(0), Fraction(base + i), base + i, base + i))  # @line L7
            break
        d = xs[i + 1] - x0                                           # @line L3
        y0, y1 = base + i, base + i + 1
        poly: List[Point] = []
        for c, v in ((y0 - eps, y1 - eps), (y0 - eps, y1 + eps), (y0 + eps, y1 + eps), (y0 + eps, y1 - eps)):
            poly.append((Fraction(v - c, d), Fraction(c)))           # @line L3
        j = i + 2                                                    # @line L4
        while j < n:                                                 # @line L5
            cut = _clip(poly, xs[j] - x0, base + j - eps, base + j + eps)  # @line L5
            if not cut:
                break
            poly = cut                                               # @line L6
            j += 1                                                   # @line L6
        s = sum(p[0] for p in poly) / len(poly)
        c = sum(p[1] for p in poly) / len(poly)
        if s < 0:
            # A valid line with a negative slope exists only if the run is
            # shorter than 2 eps; then the flat line at the middle is valid.
            s, c = Fraction(0), Fraction(2 * base + i + j - 1, 2)
        segs.append(Segment(x0, s, c, base + i, base + j - 1))       # @line L7
        i = j                                                        # @line L8
    return segs


class PGMIndex:
    """A static PGM-index over strictly increasing integer keys."""

    def __init__(self, keys: Sequence[int], eps: int = 8, eps_rec: int = 4):
        if eps < 1 or eps_rec < 1:
            raise ValueError("eps and eps_rec must be at least 1")
        keys = list(keys)
        for a, b in zip(keys, keys[1:]):
            if not a < b:
                raise ValueError("keys must be strictly increasing")
        self.keys = keys
        self.eps = eps
        self.eps_rec = eps_rec
        # levels[0] is the root level; arrays[l] is the array that levels[l] indexes.
        self.levels: List[List[Segment]] = []
        self.arrays: List[List[int]] = []
        self.errors: List[int] = []
        if not keys:
            return
        a, e = keys, eps                                             # @line L9
        while True:
            segs = build_pla(a, e)                                   # @line L10
            self.levels.append(segs)
            self.arrays.append(a)
            self.errors.append(e)
            if len(segs) == 1:                                       # @line L12
                break
            a, e = [s.key for s in segs], eps_rec                    # @line L11
        self.levels.reverse()
        self.arrays.reverse()
        self.errors.reverse()
        self.probes = 0

    @property
    def height(self) -> int:
        return len(self.levels)

    def segment_counts(self) -> List[int]:
        """The number of segments on each level, from the bottom up."""
        return [len(s) for s in reversed(self.levels)]

    def rank(self, x) -> int:
        """The number of keys <= x."""
        self.probes = 0
        if not self.keys or x < self.keys[0]:                        # @line L13
            return 0
        seg = self.levels[0][0]                                      # @line L14
        top = len(self.levels) - 1
        for lvl in range(len(self.levels)):                          # @line L15
            e, arr = self.errors[lvl], self.arrays[lvl]
            pos = min(max(seg.predict(x), seg.start), seg.end)       # @line L16
            p = pos.numerator // pos.denominator                     # @line L16
            lo = max(seg.start, p - e)                               # @line L17
            hi = min(seg.end + 1, p + e + 1)                         # @line L17
            r = bisect_right(arr, x, lo, hi)                         # @line L17
            self.probes = max(self.probes, hi - lo)
            if lvl == top:                                           # @line L18
                return r                                             # @line L18
            seg = self.levels[lvl + 1][r - 1]                        # @line L19
        raise AssertionError("unreachable")

    def lower_bound(self, x) -> int:
        """The position of the first key >= x."""
        r = self.rank(x)
        return r - 1 if r and self.keys[r - 1] == x else r

    def contains(self, x) -> bool:
        r = self.rank(x)
        return r > 0 and self.keys[r - 1] == x

    def range(self, lo, hi) -> List[int]:
        """The keys k with lo <= k <= hi."""
        return self.keys[self.lower_bound(lo):self.rank(hi)]

    def max_error(self) -> int:
        """The largest |prediction - position| over the keys of each level (for the tests)."""
        worst = Fraction(0)
        for segs, arr in zip(self.levels, self.arrays):
            for s in segs:
                for i in range(s.start, s.end + 1):
                    worst = max(worst, abs(s.predict(arr[i]) - i))
        return worst
test_pgm_index.py 147 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/pgm-index/. The authors are listed in prov/YYKWMY.jsonl.

import bisect
import random
import unittest
from fractions import Fraction
from itertools import combinations

from pgm_index import PGMIndex, build_pla


def feasible(xs, ys, eps):
    """Brute force: is there a line within eps of all points?

    By Helly's theorem in the (slope, intercept) plane, this holds if and only
    if it holds for every three points. For three points it holds if and only
    if the middle point is within 2 eps of the line through the outer two.
    """
    for a, b, c in combinations(range(len(xs)), 3):
        mid = Fraction(ys[a]) + Fraction(ys[c] - ys[a], xs[c] - xs[a]) * (xs[b] - xs[a])
        if abs(ys[b] - mid) > 2 * eps:
            return False
    return True


def optimal_count(xs, eps):
    """The fewest segments of any PLA with the error eps, by dynamic programming."""
    n = len(xs)
    best = [0] + [n + 1] * n
    for j in range(1, n + 1):
        for i in range(j):
            if best[i] + 1 < best[j] and feasible(xs[i:j], list(range(i, j)), eps):
                best[j] = best[i] + 1
    return best[n]


def random_keys(rng, n, kind):
    if kind == "uniform":
        return sorted(rng.sample(range(10 * n + 10), n))
    if kind == "clustered":
        out = set()
        while len(out) < n:
            centre = rng.randrange(10 ** 6)
            for _ in range(rng.randrange(1, 30)):
                out.add(centre + rng.randrange(200))
        return sorted(out)[:n]
    # gaps that grow fast, a hard case for a linear model
    out, x = [], 0
    for i in range(n):
        x += 1 + rng.randrange(1 + i * i // 50)
        out.append(x)
    return out


class TestPLA(unittest.TestCase):
    def test_error_bound_and_coverage(self):
        rng = random.Random(1)
        for kind in ("uniform", "clustered", "growing"):
            for eps in (1, 2, 4, 16):
                xs = random_keys(rng, 250, kind)
                segs = build_pla(xs, eps)
                self.assertEqual(segs[0].start, 0)
                self.assertEqual(segs[-1].end, len(xs) - 1)
                for a, b in zip(segs, segs[1:]):
                    self.assertEqual(a.end + 1, b.start)
                for s in segs:
                    for i in range(s.start, s.end + 1):
                        self.assertLessEqual(abs(s.predict(xs[i]) - i), eps)
                # every segment but the last covers at least 2 eps + 1 keys
                for s in segs[:-1]:
                    self.assertGreaterEqual(s.end - s.start + 1, 2 * eps + 1)
                self.assertLessEqual(len(segs), -(-len(xs) // (2 * eps)))

    def test_greedy_is_optimal(self):
        rng = random.Random(2)
        for trial in range(30):
            n = rng.randrange(3, 22)
            xs = random_keys(rng, n, rng.choice(["uniform", "growing", "clustered"]))
            eps = rng.choice([1, 1, 2])
            self.assertEqual(len(build_pla(xs, eps)), optimal_count(xs, eps), (xs, eps))

    def test_feasible_matches_greedy_on_one_segment(self):
        rng = random.Random(3)
        for _ in range(60):
            n = rng.randrange(2, 12)
            xs = random_keys(rng, n, "growing")
            one = len(build_pla(xs, 1)) == 1
            self.assertEqual(one, feasible(xs, list(range(n)), 1))


class TestPGMIndex(unittest.TestCase):
    def test_against_bisect(self):
        rng = random.Random(4)
        for kind in ("uniform", "clustered", "growing"):
            for eps, eps_rec in ((1, 1), (4, 2), (16, 4), (64, 4)):
                keys = random_keys(rng, 500, kind)
                keyset = set(keys)
                t = PGMIndex(keys, eps, eps_rec)
                self.assertEqual(t.segment_counts()[-1], 1)
                self.assertLessEqual(t.max_error(), max(eps, eps_rec))
                lo, hi = keys[0] - 5, keys[-1] + 5
                probes = list(keys[::9]) + [rng.randrange(lo, hi) for _ in range(80)] + [lo, hi]
                for x in probes:
                    self.assertEqual(t.rank(x), bisect.bisect_right(keys, x))
                    self.assertLessEqual(t.probes, 2 * max(eps, eps_rec) + 2)
                    self.assertEqual(t.lower_bound(x), bisect.bisect_left(keys, x))
                    self.assertEqual(t.contains(x), x in keyset)
                a = rng.randrange(lo, hi)
                b = a + rng.randrange(1000)
                self.assertEqual(t.range(a, b), [k for k in keys if a <= k <= b])

    def test_levels_shrink(self):
        keys = random_keys(random.Random(5), 1200, "growing")
        t = PGMIndex(keys, 2, 1)
        counts = t.segment_counts()
        self.assertGreaterEqual(len(counts), 3)
        self.assertLessEqual(counts[0], -(-len(keys) // 5))       # at least 2 eps + 1 = 5 keys per segment
        for below, above in zip(counts, counts[1:]):
            self.assertLessEqual(above, -(-below // 3))         # at least 2 eps_rec + 1 = 3 keys per segment

    def test_example_of_the_page(self):
        keys = [2, 3, 5, 8, 12, 13, 14, 20, 30, 31, 40, 41]
        t = PGMIndex(keys, 1, 1)
        segs = t.levels[-1]
        self.assertEqual([(s.start, s.end) for s in segs], [(0, 7), (8, 11)])
        self.assertEqual((segs[0].slope, segs[0].intercept), (Fraction(49, 120), Fraction(19, 60)))
        self.assertEqual(t.segment_counts(), [2, 1])
        self.assertEqual(t.rank(13), 6)
        self.assertEqual(t.lower_bound(25), 8)
        self.assertFalse(t.contains(25))

    def test_small_and_bad_inputs(self):
        t = PGMIndex([], 4)
        self.assertEqual(t.rank(10), 0)
        self.assertFalse(t.contains(10))
        t = PGMIndex([7], 4)
        self.assertEqual((t.rank(6), t.rank(7), t.rank(8)), (0, 1, 1))
        self.assertTrue(t.contains(7))
        with self.assertRaises(ValueError):
            PGMIndex([1, 1, 2])
        with self.assertRaises(ValueError):
            PGMIndex([1, 2], eps=0)


if __name__ == "__main__":
    unittest.main()

History

Tim Kraska, Alex Beutel, Ed Chi, Jeffrey Dean and Neoklis Polyzotis proposed learned indexes at SIGMOD 2018, with models that are trained and whose errors are measured after the training. Paolo Ferragina and Giorgio Vinciguerra presented the PGM-index in PVLDB in 2020. They used an optimal piecewise linear approximation with a fixed error, a construction known from the approximation of time series, at every level of the index. This gave a learned index with worst-case bounds on time and space, and with dynamic and compressed versions.

References

  1. Paolo Ferragina and Giorgio Vinciguerra, The PGM-index: a fully-dynamic compressed learned index with provable worst-case bounds, PVLDB 13(8) (2020), pp. 1162 to 1175, the optimal piecewise linear ε-approximation and its construction (Lemma 1), the bound on the number of segments (Lemma 2), the recursive index and its query bound (Theorem 1), the dynamic version (Theorem 2), the compressed and distribution-aware versions, and the experiments
  2. Tim Kraska, Alex Beutel, Ed H. Chi, Jeffrey Dean and Neoklis Polyzotis, The case for learned index structures, SIGMOD 2018, pp. 489 to 504, the index as a model of the cumulative distribution and the recursive model index, which the PGM-index compares with

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.average
  • a full proof of time.best
  • 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