Algorithm Search⌘K

Data structureresearch

Partitioned Elias-Fano index

Also called PEF.

Splits each posting list into chunks chosen by dynamic programming and codes each chunk with Elias-Fano or a bitmap, to fit local density.

Time
O(log m) accessO(n log(1/ε) / ε) build_approxO(n^2) build_exactO(log m + log n) next_geq
Space
O(n log(u / n) + n + log u) bitsO(n) build_extra
Where
m = the number of chunks; n = the number of values; u = one more than the largest value; ε = the approximation parameter
Properties
not concurrentnot externalnot persistent

A partitioned Elias-Fano index stores a strictly increasing list of document ids, a posting list, as a sequence of chunks. Each chunk is coded relative to the last value of the chunk before it, in the smallest of three forms: nothing at all for a run of consecutive ids, a bitmap for a dense chunk, or Elias-Fano for a sparse one. A small upper level, itself a pair of Elias-Fano lists in the original design, keeps the first index and the last value of each chunk. The cut points are chosen by a dynamic program that minimizes the total size, with a fixed cost for each chunk. Ottaviano and Venturini introduced it in 2014. Plain Elias-Fano, on its own page, uses one width for the whole list and so pays for the average density; this page is about the split into chunks and the choice of the cuts. The page on Simple-9 codes the gaps word by word and has no fast skip, and document identifier reassignment changes the ids so that the chunks here get denser.

In plain words

Elias-Fano is a good way to store a sorted list of numbers, but it picks its settings from the list as a whole. Real lists are not even. In one place the numbers come one after another, and in another place there are big holes. A setting that fits the whole list fits neither place well. So cut the list into pieces and store each piece in the way that fits it. A piece of numbers that come one after another needs no bits at all. A crowded piece is best stored as a row of yes and no bits. A thin piece is stored with Elias-Fano. Each piece costs a few extra bits for its entry in a small table, so too many pieces is also bad. A short computation over all the places to cut finds the best balance.

The abstract type

The structure stores a static strictly increasing list X=x0<x1<⋯<xn−1X = x_0 < x_1 < \cdots < x_{n-1} of nonnegative integers and answers:

  • access(q): return xqx_q, for 0≤q<n0 \le q < n;
  • next_geq(y): return the least qq with xq≥yx_q \ge y, or nn if there is none.

These are the same two queries as Elias-Fano encoding. In query processing, next_geq is the skip that list intersection and dynamic pruning use to jump over ids.

Representation

A partition is a list of cuts 0=c0<c1<⋯<cm=n0 = c_0 < c_1 < \cdots < c_m = n. Chunk tt holds xi,…,xj−1x_i, \ldots, x_{j-1} with i=ct−1i = c_{t-1} and j=ctj = c_t. Its base is β=0\beta = 0 for the first chunk and β=xi−1+1\beta = x_{i-1} + 1 otherwise. Its universe is U=xj−1−β+1U = x_{j-1} - \beta + 1, and its size is b=j−ib = j - i. It stores the bb distinct values xk−βx_k - \beta, which lie in [0,U)[0, U).

  • Run. If b=Ub = U, the chunk holds every integer from β\beta to xj−1x_{j-1}, and it needs no payload.
  • Bitmap. A bit vector of UU bits, with bit xk−βx_k - \beta set. It is used when UU is at most the Elias-Fano size.
  • Elias-Fano. The low parts and the unary high parts of the values, in E(b,U)=bℓ+b+⌊(U−1)/2ℓ⌋+1E(b, U) = b\ell + b + \lfloor (U-1)/2^\ell \rfloor + 1 bits with ℓ=⌊lg⁡(U/b)⌋\ell = \lfloor \lg(U/b) \rfloor.

So the payload of a chunk is 00 for a run and min⁡(U,E(b,U))\min(U, E(b, U)) otherwise. The upper level keeps the start index ct−1c_{t-1} and the last value xct−1x_{c_t - 1} of each chunk, with the kind of the chunk and the offset of its payload. In the paper these are Elias-Fano sequences too. The model here charges a fixed FF bits for each chunk's entry, and the paper bounds this by about 2lg⁡u+lg⁡n2 \lg u + \lg n bits. The implementation uses F=2⌈lg⁡(u+1)⌉+⌈lg⁡(n+1)⌉F = 2\lceil \lg(u+1) \rceil + \lceil \lg(n+1) \rceil by default.

Operations

  1. PARTITION(x[0..n-1], F) ▷ strictly increasing, x[0] ≥ 0
  2. 1C[0] ← 0
  3. 2for j ← 1 to n do
  4. 3C[j] ← ∞
  5. 4for i ← 0 to j - 1 do
  6. 5if C[i] + F + COST(i, j) < C[j] then C[j] ← C[i] + F + COST(i, j), back[j] ← i
  7. 6return the cuts n, back[n], back[back[n]], ..., 0 in increasing order
  8. BUILD(x, cuts)
  9. 7for each pair i < j of consecutive cuts do
  10. 8β ← 0 if i = 0 else x[i - 1] + 1, U ← x[j - 1] - β + 1, b ← j - i
  11. 9if b = U then kind ← RUN, payload ← empty
  12. 10else if U ≤ E(b, U) then kind ← BITMAP, payload ← U bits with bit x[k] - β set for i ≤ k < j
  13. 11else kind ← EF, payload ← ELIAS-FANO(x[i..j-1] - β, U)
  14. 12append (i, x[j - 1], kind, payload) to the upper level
  15. ACCESS(q)
  16. 13t ← the last chunk whose start is ≤ q
  17. 14return β_t + the element of rank q - start_t of chunk t
  18. NEXT-GEQ(y)
  19. 15t ← the first chunk whose last value is ≥ y, and return n if there is none
  20. 16return start_t + the rank of the first element ≥ y in chunk t

Partition. C[j]C[j] is the least size of a partition of the prefix x0,…,xj−1x_0, \ldots, x_{j-1}. The last chunk of such a partition is xi,…,xj−1x_i, \ldots, x_{j-1} for some ii, and its cost depends only on ii and jj, because its base is fixed by xi−1x_{i-1}. So lines L4 and L5 try every ii. This is a shortest path from 0 to nn in the DAG on the positions 0,…,n0, \ldots, n, with an edge i→ji \to j of weight F+COST(i,j)F + \text{COST}(i, j). Each weight takes O(1)O(1) time from bb and UU.

Build. Lines L8 to L11 code each chunk in the form with the fewest bits. The bitmap wins on dense chunks, where U/bU/b is small, and Elias-Fano wins on sparse ones.

Access. Line L13 is a search in the list of starts. Line L14 reads one element: a run gives β+r\beta + r for rank rr, a bitmap gives β\beta plus the position of its (r+1)(r+1)-th 1, and an Elias-Fano chunk gives β\beta plus its own access. With a select index on each bitmap and each high part, the read takes O(1)O(1) time.

Next-geq. All chunks before tt end below yy, so line L15 skips them in one search of the last values, and chunk tt contains the answer. Line L16 then searches inside that one chunk. This is the gain over plain gap codes: the skip touches the upper level and one chunk, not the ids in between.

Example

Take the list of 20 ids X=0,1,2,3,4,5,6,7,40,100,160,220,300,301,303,304,306,307,309,310X = 0, 1, 2, 3, 4, 5, 6, 7, 40, 100, 160, 220, 300, 301, 303, 304, 306, 307, 309, 310, with F=10F = 10 bits for each chunk. It has a run at the start, a sparse middle and a dense end. The optimal cuts are 0,8,13,200, 8, 13, 20:

chunk values base β\beta UU bb kind payload bits the other forms
1 0 to 7 0 8 8 run 0 Elias-Fano 16, bitmap 8
2 40, 100, 160, 220, 300 8 293 5 Elias-Fano 40 bitmap 293
3 301 to 310, without 302, 305, 308 301 10 7 bitmap 10 Elias-Fano 17

In chunk 2 the stored values are 32,92,152,212,29232, 92, 152, 212, 292 and ℓ=⌊lg⁡(293/5)⌋=5\ell = \lfloor \lg(293/5) \rfloor = 5. The low parts 0,28,24,20,40, 28, 24, 20, 4 take 25 bits, and the high parts 1,2,4,6,91, 2, 4, 6, 9 set bits 1,3,6,9,131, 3, 6, 9, 13 of a high part of 5+9+1=155 + 9 + 1 = 15 bits, so the payload is 0000011100110001010000100 then 010100100100010, 40 bits. Chunk 3 stores 0,2,3,5,6,8,90, 2, 3, 5, 6, 8, 9 as the bitmap 1011011011.

The total is 3⋅10+0+40+10=803 \cdot 10 + 0 + 40 + 10 = 80 bits. One chunk for the whole list costs 10+119=12910 + 119 = 129 bits, because a single Elias-Fano code with ℓ=⌊lg⁡(311/20)⌋=3\ell = \lfloor \lg(311/20) \rfloor = 3 pays 3 low bits for every id, also in the run. Chunks of a fixed size cost 113 bits for size 4 and 115 bits for size 5. With the default F=23F = 23 of the implementation, the same cuts are optimal and the total is 119 bits.

Queries: next_geq(150) finds that chunk 2 is the first chunk whose last value, 300, is at least 150. It then reads 40, 100, 160 in that chunk and returns index 10, and access(10) is 160. next_geq(302) goes to chunk 3 and returns index 14, the id 303. next_geq(311) finds no chunk and returns 20.

Correctness

The proof shows that each chunk value lies in [0,U)[0, U) of its chunk, so each of the three codes gives back the chunk. It shows that the size of a partition is a sum of chunk costs that depend only on the two cuts, so the recurrence of lines L4 and L5 finds the least size of each prefix by induction. Finally, it shows that the search on the starts and on the last values finds the right chunk for access and next_geq. The tests compare the dynamic program with a search over all 2n−12^{n-1} partitions for n≤12n \le 12, check every payload length against the formulas, and compare both queries with a binary search on the plain list.

Proof: The partition is optimal, and every chunk and query gives back the stored valuesfull

Let x0<x1<⋯<xn−1x_0 < x_1 < \cdots < x_{n-1} be nonnegative integers, and let F≥0F \ge 0 be the fixed cost of a chunk. A partition is a list of cuts 0=c0<c1<⋯<cm=n0 = c_0 < c_1 < \cdots < c_m = n, and chunk tt is xct−1,…,xct−1x_{c_{t-1}}, \ldots, x_{c_t - 1}. For a chunk xi,…,xj−1x_i, \ldots, x_{j-1}, let β=0\beta = 0 if i=0i = 0 and β=xi−1+1\beta = x_{i-1} + 1 otherwise, let U=xj−1−β+1U = x_{j-1} - \beta + 1, and let b=j−ib = j - i. Write COST(i,j)=0\text{COST}(i, j) = 0 if b=Ub = U, and COST(i,j)=min⁡(U,E(b,U))\text{COST}(i, j) = \min(U, E(b, U)) otherwise, where E(b,U)=bℓ+b+⌊(U−1)/2ℓ⌋+1E(b, U) = b\ell + b + \lfloor (U-1)/2^\ell \rfloor + 1 with ℓ=⌊lg⁡(U/b)⌋\ell = \lfloor \lg(U/b) \rfloor is the length of the Elias-Fano code of bb values in [0,U)[0, U).

  1. The chunk values fit their universe. For i≤k<ji \le k < j, xk≥xi≥βx_k \ge x_i \ge \beta, because xi>xi−1x_i > x_{i-1} when i>0i > 0. Also xk≤xj−1=β+U−1x_k \le x_{j-1} = \beta + U - 1. So the values vk=xk−βv_k = x_k - \beta are bb distinct integers in [0,U)[0, U), in increasing order, and b≤Ub \le U.

  2. Each chunk code gives back its values. If b=Ub = U, then bb distinct integers in [0,U)[0, U) are all of 0,…,U−10, \ldots, U - 1, so vk=k−iv_k = k - i and the run needs no bits; the element of rank k−ik - i is β+(k−i)\beta + (k - i). If the chunk is a bitmap (line L10), bit vv of the UU bits is 1 exactly when vv is a value, so the position of the (r+1)(r+1)-th 1 is the value of rank rr. Otherwise line L11 stores the Elias-Fano code of the vkv_k in [0,U)[0, U), which is valid by step 1, and its access gives back vkv_k. In all three cases the reader adds β\beta, so it returns xkx_k. The payload has exactly COST(i,j)\text{COST}(i, j) bits: the run has none, and line L10 picks the bitmap exactly when U≤E(b,U)U \le E(b, U).

  3. The cost of a partition is a sum over its chunks. The stored size is FF for each chunk plus its payload, and by step 2 the payload of a chunk depends only on its ends ii and jj. So a partition with cuts c0,…,cmc_0, \ldots, c_m costs ∑t=1m(F+COST(ct−1,ct))\sum_{t=1}^{m} (F + \text{COST}(c_{t-1}, c_t)).

  4. The recurrence finds the cheapest partition of each prefix. Let OPT(j)\text{OPT}(j) be the least cost of a partition of x0,…,xj−1x_0, \ldots, x_{j-1} into chunks, with OPT(0)=0\text{OPT}(0) = 0. We show C[j]=OPT(j)C[j] = \text{OPT}(j) by induction on jj. Line L1 gives C[0]=0C[0] = 0. For j≥1j \ge 1, the last chunk of any partition of the prefix is xi,…,xj−1x_i, \ldots, x_{j-1} for some 0≤i<j0 \le i < j, and the cuts before it form a partition of x0,…,xi−1x_0, \ldots, x_{i-1}. The value β\beta of the last chunk depends only on ii, not on the earlier cuts, so by step 3 the cost is that of the earlier part plus F+COST(i,j)F + \text{COST}(i, j), and it is least when the earlier part is optimal. So OPT(j)=min⁡0≤i<j(OPT(i)+F+COST(i,j))\text{OPT}(j) = \min_{0 \le i < j} (\text{OPT}(i) + F + \text{COST}(i, j)). Lines L4 and L5 compute this minimum with C[i]=OPT(i)C[i] = \text{OPT}(i) for i<ji < j, by the hypothesis, and record in back[j]\text{back}[j] an ii that attains it.

  5. The back pointers give a partition of that cost. Line L6 starts at nn and steps to back[n]\text{back}[n], then to back[back[n]]\text{back}[\text{back}[n]], and so on. Each step goes to a smaller index, so it reaches 0. By step 4, if i=back[j]i = \text{back}[j] then C[j]=C[i]+F+COST(i,j)C[j] = C[i] + F + \text{COST}(i, j), so summing along the path, the cuts found have cost C[n]=OPT(n)C[n] = \text{OPT}(n).

  6. Access returns xqx_q. Line L12 appends the first index ct−1c_{t-1} of each chunk to the list of starts, which is strictly increasing. For 0≤q<n0 \le q < n, line L13 picks the last chunk tt whose start is ≤q\le q. Then ct−1≤q<ctc_{t-1} \le q < c_t, because the next start is ct>qc_t > q, or t=mt = m and cm=n>qc_m = n > q. So xqx_q is the element of rank q−ct−1q - c_{t-1} of chunk tt, and line L14 returns it by step 2.

  7. Next-geq returns the least qq with xq≥yx_q \ge y. The list of last values xc1−1<xc2−1<⋯x_{c_1 - 1} < x_{c_2 - 1} < \cdots is strictly increasing. Line L15 finds the first chunk tt whose last value is ≥y\ge y. If there is none, every element is at most the last value of the last chunk, which is <y< y, and the answer is nn. Otherwise every chunk before tt ends with a value <y< y, so all its elements are <y< y, and chunk tt has at least one element ≥y\ge y, its last. Line L16 reads the elements of chunk tt in increasing order and returns the index of the first one that is ≥y\ge y. That index is the least qq with xq≥yx_q \ge y. ■\blacksquare

The cost of a chunk depends on the cut before it only through β=xi−1+1\beta = x_{i-1} + 1, which is fixed once ii is fixed. This is why the problem splits into prefixes, and why a shortest path over the prefix positions 0,…,n0, \ldots, n, with an edge from ii to jj of weight F+COST(i,j)F + \text{COST}(i, j), solves it.

Complexity

The exact dynamic program does n(n+1)/2n(n+1)/2 steps of O(1)O(1) each, so it takes O(n2)O(n^2) time and O(n)O(n) space. This is too slow for lists of millions of ids. The paper gives a (1+ε)(1 + \varepsilon) approximation instead. It keeps, for each start, only one edge for each cost level, where the levels grow by a factor of 1+ε1 + \varepsilon, and it finds a partition within a factor (1+ε)(1 + \varepsilon) of the best in O(nlog⁡1+ε(1/ε))O(n \log_{1+\varepsilon}(1/\varepsilon)) time. For small ε\varepsilon this is O(nlog⁡(1/ε)/ε)O(n \log(1/\varepsilon) / \varepsilon), which is linear for a fixed ε\varepsilon. The implementation here runs the exact program.

The size is never more than that of a single chunk, which is FF plus the Elias-Fano size n⌈lg⁡(u/n)⌉+2nn \lceil \lg(u/n) \rceil + 2n at most. So the space is O(nlog⁡(u/n)+n+log⁡u)O(n \log(u/n) + n + \log u) bits, and on lists with dense regions it is often much less. With search over the upper level, access takes O(log⁡m)O(\log m) time for mm chunks plus O(1)O(1) in the chunk with select indexes. next_geq adds a search inside one chunk, in O(log⁡n)O(\log n) time at most. With the Elias-Fano upper level of the paper, the chunk search is itself an Elias-Fano next_geq. The implementation reads the bits of a chunk one by one, so its in-chunk reads take time linear in the payload.

Variants

  • Chunks of a fixed size. Cut every 128 ids, for example, and choose only the code of each chunk. This needs no dynamic program and is simpler, but it misses the run and the dense regions that do not align with the cuts. In the example it costs 113 bits against 80.
  • Approximate partition. The (1+ε)(1 + \varepsilon) method of the paper, with one edge kept for each cost level. Pibiri and Venturini state that the paper uses two parameters, ε1=0.03\varepsilon_1 = 0.03 and ε2=0.3\varepsilon_2 = 0.3.
  • Other chunk codes. The same partition scheme works with any code whose cost for a chunk is known from its ends, and later work puts other codes in the chunks. Clustered Elias-Fano, by Pibiri and Venturini, shares one reference list among a cluster of similar posting lists.
  • Uniform Elias-Fano with skips. The quasi-succinct index of Vigna stores one Elias-Fano code for each list, with forward pointers into the high part for fast skips. It is the case of a single chunk.

When to use it

Use it for a static inverted index that must be both small and fast to intersect, where queries skip a lot with next_geq. It gains the most on lists with clusters of close ids, which is common after document identifier reassignment and for sites crawled in URL order. For lists that are read in full, with few skips, a block code such as PForDelta may decode faster. For an index that changes all the time, use a dynamic scheme and code each merged partition anew.

Pitfalls

  • Code each chunk relative to the chunk before it. If a chunk stores its values against 0, its universe is the whole range up to its last value, and it loses the gain of the partition.
  • Count the upper level. If FF is too small, the program cuts the list into many tiny chunks whose entries cost more than they save. If it is too large, the program gives one chunk. The value of FF must model the real cost of the upper level.
  • Compare against the real Elias-Fano size. The choice between the bitmap and Elias-Fano must use the exact E(b,U)E(b, U), with the floor in ℓ\ell, not an estimate such as b(2+lg⁡(U/b))b(2 + \lg(U/b)).
  • Do not scan the chunks. next_geq must find the chunk from the upper level. Walking the chunks one by one throws away the skip.
  • The exact program is quadratic. Use the approximation, or a cap on the chunk length, on long lists.

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.

partitioned_elias_fano.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/partitioned-elias-fano/. The authors are listed in prov/PX2K2C.jsonl.

import bisect

RUN, BITMAP, EF = "run", "bitmap", "ef"


def low_width(b: int, u: int) -> int:
    """The Elias-Fano low width floor(log2(u / b)) for 1 <= b <= u, in integers."""
    return (u // b).bit_length() - 1


def ef_bits(b: int, u: int) -> int:
    """Bits of the Elias-Fano code of b distinct values in [0, u): b*l low bits plus b + floor((u-1)/2^l) + 1 high bits."""
    lw = low_width(b, u)
    return b * lw + b + ((u - 1) >> lw) + 1


def chunk_bits(b: int, u: int) -> int:
    """Payload bits of a chunk of b distinct values whose largest value is u - 1."""
    if b == u:
        return 0
    return min(u, ef_bits(b, u))


def chunk_universe(x: list[int], i: int, j: int) -> tuple[int, int, int]:
    """For the chunk x[i..j-1], return (base, U, b): values are coded as x - base in [0, U)."""
    base = 0 if i == 0 else x[i - 1] + 1
    return base, x[j - 1] - base + 1, j - i


def partition_cost(x: list[int], cuts: list[int], fixed: int) -> int:
    """Total bits of a partition given by cuts = [0, ..., n]: fixed bits per chunk plus the payloads."""
    total = 0
    for i, j in zip(cuts, cuts[1:]):
        _, u, b = chunk_universe(x, i, j)
        total += fixed + chunk_bits(b, u)
    return total


def optimal_partition(x: list[int], fixed: int) -> tuple[int, list[int]]:
    """The exact optimal partition by dynamic programming over prefixes. Cost O(n^2) time, O(n) space."""
    n = len(x)
    c = [0] + [0] * n  # @line L1
    back = [0] * (n + 1)
    for j in range(1, n + 1):  # @line L2
        best = None  # @line L3
        for i in range(j):  # @line L4
            _, u, b = chunk_universe(x, i, j)
            v = c[i] + fixed + chunk_bits(b, u)
            if best is None or v < best:  # @line L5
                best, back[j] = v, i
        c[j] = best if best is not None else 0
    cuts = [n]  # @line L6
    while cuts[-1] > 0:
        cuts.append(back[cuts[-1]])
    cuts.reverse()
    return c[n], cuts


def uniform_partition(n: int, size: int) -> list[int]:
    """Cuts for chunks of a fixed size, the last one possibly shorter."""
    return list(range(0, n, size)) + [n]


def ef_encode(vals: list[int], u: int) -> str:
    """Elias-Fano bit string of distinct increasing vals in [0, u): the low parts, then the high part H."""
    b = len(vals)
    lw = low_width(b, u)
    low = "".join(format(v & ((1 << lw) - 1), f"0{lw}b") if lw else "" for v in vals)
    high = ["0"] * (b + ((u - 1) >> lw) + 1)
    for k, v in enumerate(vals):
        high[(v >> lw) + k] = "1"
    return low + "".join(high)


def ef_access(payload: str, b: int, u: int, k: int) -> int:
    """Element k of an Elias-Fano chunk. Cost O(size of H) here; a select structure makes it O(1)."""
    lw = low_width(b, u)
    low = int(payload[k * lw:(k + 1) * lw], 2) if lw else 0
    high = payload[b * lw:]
    pos = -1
    for _ in range(k + 1):
        pos = high.index("1", pos + 1)
    return ((pos - k) << lw) | low


class PartitionedEliasFano:
    """A strictly increasing list of nonnegative integers, cut into chunks.

    Each chunk is coded relative to the last value of the chunk before it, as
    a run (no bits), a bitmap, or Elias-Fano, whichever is smallest. The upper
    level keeps, for each chunk, its first index and its last value; its size is
    modelled as fixed bits per chunk.
    """

    def __init__(self, x: list[int], fixed: int | None = None, chunk_size: int | None = None) -> None:
        for a, b in zip(x, x[1:]):
            if not a < b:
                raise ValueError("the list must be strictly increasing")
        if x and x[0] < 0:
            raise ValueError("values must be nonnegative")
        self.n = len(x)
        u = x[-1] + 1 if x else 1
        self.fixed = fixed if fixed is not None else 2 * u.bit_length() + self.n.bit_length()
        if not x:
            cuts = [0]
        elif chunk_size is None:
            _, cuts = optimal_partition(x, self.fixed)
        else:
            cuts = uniform_partition(self.n, chunk_size)
        self.cuts = cuts
        self.starts: list[int] = []
        self.lasts: list[int] = []
        self.chunks: list[tuple[str, int, int, int, str]] = []  # (kind, base, U, b, payload)
        for i, j in zip(cuts, cuts[1:]):  # @line L7
            base, u_j, b = chunk_universe(x, i, j)  # @line L8
            vals = [v - base for v in x[i:j]]
            if b == u_j:  # @line L9
                kind, payload = RUN, ""
            elif u_j <= ef_bits(b, u_j):  # @line L10
                bits = ["0"] * u_j
                for v in vals:
                    bits[v] = "1"
                kind, payload = BITMAP, "".join(bits)
            else:
                kind, payload = EF, ef_encode(vals, u_j)  # @line L11
            self.starts.append(i)  # @line L12
            self.lasts.append(x[j - 1])
            self.chunks.append((kind, base, u_j, b, payload))

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

    def bits(self) -> int:
        """Total size in the cost model: fixed bits per chunk plus all payload bits."""
        return sum(self.fixed + len(c[4]) for c in self.chunks)

    def _element(self, j: int, k: int) -> int:
        kind, base, u, b, payload = self.chunks[j]
        if kind == RUN:
            return base + k
        if kind == BITMAP:
            pos = -1
            for _ in range(k + 1):
                pos = payload.index("1", pos + 1)
            return base + pos
        return base + ef_access(payload, b, u, k)

    def access(self, q: int) -> int:
        """The value at index q, 0 <= q < n."""
        if not 0 <= q < self.n:
            raise IndexError("index out of range")
        j = bisect.bisect_right(self.starts, q) - 1  # @line L13
        return self._element(j, q - self.starts[j])  # @line L14

    def next_geq(self, y: int) -> int:
        """The least index q with value >= y, or n if there is none."""
        j = bisect.bisect_left(self.lasts, y)  # @line L15
        if j == len(self.lasts):
            return self.n
        b = self.chunks[j][3]
        for k in range(b):  # @line L16
            if self._element(j, k) >= y:
                return self.starts[j] + k
        return self.n

    def decode(self) -> list[int]:
        """All values in order."""
        return [self._element(j, k) for j in range(len(self.chunks)) for k in range(self.chunks[j][3])]
test_partitioned_elias_fano.py 138 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/partitioned-elias-fano/. The authors are listed in prov/PX2K2C.jsonl.

import bisect
import math
import random

from partitioned_elias_fano import (
    BITMAP,
    EF,
    RUN,
    PartitionedEliasFano,
    chunk_bits,
    ef_bits,
    ef_encode,
    optimal_partition,
    partition_cost,
    uniform_partition,
)

EXAMPLE = [0, 1, 2, 3, 4, 5, 6, 7, 40, 100, 160, 220, 300, 301, 303, 304, 306, 307, 309, 310]


def brute_force_best(x: list[int], fixed: int) -> int:
    """Try every set of cut points between 1 and n - 1."""
    n = len(x)
    best = None
    for mask in range(1 << (n - 1)):
        cuts = [0] + [i for i in range(1, n) if mask >> (i - 1) & 1] + [n]
        c = partition_cost(x, cuts, fixed)
        best = c if best is None or c < best else best
    return best


def check_structure(p: PartitionedEliasFano, x: list[int]) -> None:
    assert p.decode() == x and len(p) == len(x)
    total = 0
    for (kind, base, u, b, payload), i, j in zip(p.chunks, p.cuts, p.cuts[1:]):
        assert b == j - i and base == (0 if i == 0 else x[i - 1] + 1) and u == x[j - 1] - base + 1
        if kind == RUN:
            assert b == u and payload == ""
        elif kind == BITMAP:
            assert len(payload) == u <= ef_bits(b, u) and payload.count("1") == b
        else:
            assert kind == EF and len(payload) == ef_bits(b, u) < u
        assert len(payload) == chunk_bits(b, u)
        total += p.fixed + len(payload)
    assert p.bits() == total == partition_cost(x, p.cuts, p.fixed)


def test_ef_bits_formula() -> None:
    for b in range(1, 40):
        for u in range(b, 300):
            lw = math.floor(math.log2(u / b)) if u > b else 0
            while (b << (lw + 1)) <= u:
                lw += 1
            while lw > 0 and (b << lw) > u:
                lw -= 1
            want = b * lw + b + (u - 1) // (1 << lw) + 1
            assert ef_bits(b, u) == want
            vals = sorted(random.Random(b * 1000 + u).sample(range(u), b))
            assert len(ef_encode(vals, u)) == want


def test_example() -> None:
    p = PartitionedEliasFano(EXAMPLE, fixed=10)
    assert p.cuts == [0, 8, 13, 20]
    assert [c[0] for c in p.chunks] == [RUN, EF, BITMAP]
    assert [len(c[4]) for c in p.chunks] == [0, 40, 10]
    assert p.chunks[1][4] == "0000011100110001010000100010100100100010"
    assert p.bits() == 80
    assert partition_cost(EXAMPLE, [0, 20], 10) == 129
    assert partition_cost(EXAMPLE, uniform_partition(20, 4), 10) == 113
    assert partition_cost(EXAMPLE, uniform_partition(20, 5), 10) == 115
    assert p.access(10) == 160 and p.next_geq(150) == 10 and p.next_geq(302) == 14 and p.next_geq(311) == 20
    check_structure(p, EXAMPLE)


def test_edge_cases() -> None:
    p = PartitionedEliasFano([])
    assert len(p) == 0 and p.decode() == [] and p.next_geq(0) == 0 and p.bits() == 0
    p = PartitionedEliasFano([0])
    assert p.chunks[0][0] == RUN and p.access(0) == 0 and p.next_geq(1) == 1
    p = PartitionedEliasFano([5])
    assert p.decode() == [5] and p.next_geq(0) == 0
    big = [0, 1, 2, 10 ** 9, 10 ** 9 + 1, 2 ** 40]
    p = PartitionedEliasFano(big)
    check_structure(p, big)
    dense = list(range(100, 200))
    p = PartitionedEliasFano(dense)
    check_structure(p, dense)
    for bad in ([1, 1], [3, 2], [-1, 4]):
        try:
            PartitionedEliasFano(bad)
        except ValueError:
            pass
        else:
            raise AssertionError("bad input was accepted")
    try:
        PartitionedEliasFano([1, 2]).access(2)
    except IndexError:
        pass
    else:
        raise AssertionError("access out of range was accepted")


def test_dp_against_brute_force() -> None:
    rng = random.Random(20261120)
    for _ in range(250):
        n = rng.randint(1, 12)
        u = rng.choice([n, n + 3, 2 * n, 10 * n, 1000])
        x = sorted(rng.sample(range(u), n))
        fixed = rng.choice([0, 1, 4, 10, 30])
        cost, cuts = optimal_partition(x, fixed)
        assert cuts[0] == 0 and cuts[-1] == n and cuts == sorted(set(cuts))
        assert partition_cost(x, cuts, fixed) == cost == brute_force_best(x, fixed)


def test_random_lists() -> None:
    rng = random.Random(20261121)
    for _ in range(300):
        n = rng.randint(1, 120)
        # mix dense runs and sparse stretches
        x: list[int] = []
        v = rng.randint(0, 5)
        while len(x) < n:
            x.append(v)
            v += 1 if rng.random() < 0.5 else rng.randint(2, rng.choice([4, 50, 5000]))
        size = rng.choice([None, 1, 3, 8, 128])
        p = PartitionedEliasFano(x, chunk_size=size)
        check_structure(p, x)
        if size is None:
            for s in (1, 4, 16, n):
                assert p.bits() <= partition_cost(x, uniform_partition(n, s), p.fixed)
        for q in range(n):
            assert p.access(q) == x[q]
        for y in rng.sample(range(-2, x[-1] + 3), min(30, x[-1] + 5)):
            assert p.next_geq(y) == bisect.bisect_left(x, y)

History

Elias published the high and low bit representation in 1974, after a memo by Fano. Vigna made it practical for inverted indexes in his quasi-succinct indices of 2013. Ottaviano and Venturini noticed that one Elias-Fano code for a whole list cannot use its local clusters, and in 2014 they split the list into chunks chosen by a dynamic program, with the bitmap and the run as cheaper codes for dense chunks. Their index was smaller than plain Elias-Fano at about the same query speed, and it became a standard point of comparison in later work on index compression.

References

  1. Giuseppe Ottaviano and Rossano Venturini, Partitioned Elias-Fano indexes, Proceedings of the 37th International ACM SIGIR Conference (SIGIR 2014), pages 273 to 282, the two-level representation with Elias-Fano, bitmap and run chunks, the exact dynamic program for the partition, and its (1 + ε) approximation on a pruned graph
  2. Sebastiano Vigna, Quasi-succinct indices, Sixth ACM International Conference on Web Search and Data Mining (WSDM 2013), pages 83 to 92, the Elias-Fano representation of posting lists with skipping, which the partitioned form splits into chunks
  3. Techniques for inverted index compression, the section on Elias-Fano and its partitioned form, with the comparison of index codes in space and speed

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.access
  • a full proof of time.build_approx
  • a full proof of time.build_exact
  • a full proof of time.next_geq
  • a full proof of space.bits
  • a full proof of space.build_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)
WritingW4 complete
  • a review of the text: no review record reviews/PX2K2C/text.yaml