Algorithm Search⌘K

Algorithmadvanced

Word-aligned hybrid compression

Also called WAH, WAH bitmap compression.

Compress a bitmap into literal and fill words of machine size, so that AND, OR and XOR run on the compressed form in time linear in the number of compressed words.

Time
O(p + q) worst · averageO(max(p, q)) best
Space
O(p + q) extra
Where
N = the number of bits of a bitmap; h = the number of set bits; p = the number of words of the first operand; q = the number of words of the second operand; w = the word length in bits (32 on this page)
Properties
deterministicexactnot externalnot in placeonlineiterative
Origin
Kesheng Wu, Ekow J. Otoo, Arie Shoshani, 2002

Word-aligned hybrid compression (WAH) is a form of run-length encoding for bitmaps that cuts the bitmap into groups of w−1w - 1 bits and writes each group, or each run of identical groups, as one machine word. Because every word covers whole groups, a logical operation on two compressed bitmaps walks both word lists once and never decodes them bit by bit. The bitmap index page shows where WAH is used and gives a short example; this page holds the full algorithm, the word count theorem and the cost proofs.

In plain words

A long row of switches is mostly off, with a few short patches where some are on. Instead of writing every switch, cut the row into pieces of 31 switches. A piece that is all off, or all on, joins its neighbors of the same kind, and the whole stretch is written as one word that says "this many pieces, all off". A piece with a mix is written as it is, in one word.

To combine two such rows, you read both lists of words side by side. When both say "many pieces of the same kind", you can answer for all of those pieces in one step. When one of them is a mixed piece, you combine that one piece. So the work depends on how many words there are, not on how many switches.

The problem

Input: a bitmap XX of NN bits, and for the logical operations a second bitmap YY of the same length NN and an operation ∘\circ (AND, OR or XOR, applied bit by bit). Output: the compressed form of XX, and the compressed form of X∘YX \circ Y computed from the compressed forms of XX and YY.

The words have w=32w = 32 bits; the 64-bit version uses w=64w = 64 in the same way. Cut the bitmap into M=⌊N/31⌋M = \lfloor N / 31 \rfloor full groups of 31 bits, and a tail of N−31MN - 31 M bits. On this page, as in Fig. 2 of the paper, the first bit of a group is the highest of its 31 bits.

  • A literal word has top bit 0. Its low 31 bits are one group as it is.
  • A fill word has top bit 1. The next bit is the fill bit ff, and the low 30 bits are a count k≥1k \ge 1. It stands for kk groups of 31 copies of ff, so 31k31 k bits.
  • The active word holds the tail of N−31M<31N - 31 M < 31 bits, with its length. It is kept apart from the regular words.

The algorithm

  1. COMPRESS(b, N) ▷ b is a sequence of N bits
  2. 1Z ← an empty list of words
  3. 2M ← ⌊N / 31⌋
  4. 3for i ← 0 to M - 1 do
  5. 4g ← bits 31i to 31i + 30 of b, the first bit highest
  6. 5APPEND-LITERAL(Z, g)
  7. 6active ← the last N - 31M bits of b; nbits ← N - 31M
  8. 7return (Z, active, nbits)
  9. APPEND-LITERAL(Z, g) ▷ g is one group of 31 bits
  10. 8if g = 0 then APPEND-FILL(Z, 0, 1)
  11. 9else if g = 2^31 - 1 then APPEND-FILL(Z, 1, 1)
  12. 10else append g to Z ▷ a literal word
  13. APPEND-FILL(Z, f, k) ▷ k groups of the bit f
  14. 11if the last word of Z is a fill with bit f then
  15. 12add k to its count
  16. 13else append the fill word 2^31 + f · 2^30 + k to Z

A count has 30 bits, so it holds at most 230−12^{30} - 1 groups. Lemma 1 of the paper shows that, for w>5w > 5, any run of at most 2w2^w bits fits in one fill word, so a bitmap of at most 2322^{32} bits never overflows a count. The code starts a new fill word when a count is full.

The logical operation reads both word lists from the left. RUN(X,i)(X, i) gives the 31-bit value of word ii of XX (31 copies of the fill bit for a fill word) and the number of groups it still covers.

  1. WAH-OP(X, Y, ∘) ▷ X and Y have the same N
  2. 1Z ← an empty list; i ← 0; j ← 0
  3. 2(x, nx) ← RUN(X, 0); (y, ny) ← RUN(Y, 0)
  4. 3while i < |X| and j < |Y| do
  5. 4k ← min(nx, ny)
  6. 5if word i of X and word j of Y are both fills then APPEND-FILL(Z, the bit of x ∘ y, k)
  7. 6else APPEND-LITERAL(Z, x ∘ y) ▷ here k = 1
  8. 7nx ← nx - k; ny ← ny - k
  9. 8if nx = 0 then i ← i + 1; (x, nx) ← RUN(X, i)
  10. 9if ny = 0 then j ← j + 1; (y, ny) ← RUN(Y, j)
  11. 10active ← active(X) ∘ active(Y), masked to nbits
  12. 11return (Z, active, nbits)

Two fills give a fill of the shorter length in one step, whatever their counts are. A fill and a literal give one literal, and APPEND-LITERAL turns an all-0 or all-1 result back into a fill, so the output has the same form that COMPRESS would give.

Example

Fig. 2 of the paper. The 128 bits are one 1, twenty 0s, three 1s, seventy-nine 0s and twenty-five 1s. So M=4M = 4 groups and a tail of 4 bits.

group bits word
0 1, twenty 0s, three 1s, seven 0s literal 0x40000380
1 and 2 62 zeros fill 0x80000002 (bit 0, count 2)
3 ten 0s, twenty-one 1s literal 0x001FFFFF
tail four 1s active word 0x0000000F, 4 bits

The 128 bits need three regular words and the active word.

An AND. Let N=160N = 160, so M=5M = 5 and a tail of 5 bits. XX has the bits 70 to 159 set, and YY has the bits 0 to 99 and 157 to 159 set.

  • XX = 0x80000002 (two 0-groups), 0x007FFFFF (bits 62 to 69 are 0, bits 70 to 92 are 1), 0xC0000002 (two 1-groups), active 0x1F.
  • YY = 0xC0000003 (three 1-groups), 0x7F000000 (bits 93 to 99 are 1), 0x80000001 (one 0-group), active 0x07.

WAH-OP with AND takes 4 steps:

  1. Fill 0 of count 2 with fill 1 of count 3: both fills, k=2k = 2, append a 0-fill of 2. XX moves on; YY has 1 group left.
  2. The literal 0x007FFFFF with the rest of the 1-fill: k=1k = 1, append the literal 0x007FFFFF. Both move on.
  3. The 1-fill of count 2 with the literal 0x7F000000: k=1k = 1, append 0x7F000000. YY moves on; XX has 1 group left.
  4. The rest of the 1-fill with the 0-fill of count 1: append a 0-fill of 1. Both lists end.

The active words give 0x1F AND 0x07 = 0x07. The result is 0x80000002, 0x007FFFFF, 0x7F000000, 0x80000001 with active word 0x07: the bits 70 to 99 and 157 to 159, 33 bits in all. OR takes 4 steps too and gives the single fill 0xC0000005 with active word 0x1F.

Sizes. For N=100 000N = 100\,000 bits (M=3225M = 3225 groups), with bits set at random by random.Random(1):

density set bits hh counting groups that are fills GG WAH words
0.001 108 3014 211
0.05 4973 130 3095
0.5 49958 0 3225

The plain bitmap has ⌈100 000/32⌉=3125\lceil 100\,000 / 32 \rceil = 3125 words. At density 0.5, WAH is about 3% larger, because each 32-bit word carries only 31 bits of data.

Correctness

The proofs are in proofs/correctness.md. In short:

  • COMPRESS is lossless. Each full group is written exactly once, as a literal or as part of a fill with its own bit, in order, and the tail is the active word.
  • Theorem 3 of the paper (the word count). A counting group is a pair of consecutive full groups, so a bitmap with MM groups has M−1M - 1 of them. Let GG be the number of counting groups whose two groups are fills of the same bit. If no count overflows, COMPRESS writes exactly M−GM - G regular words. A run of ll fill groups of one bit gives l−1l - 1 such pairs (Lemma 2) and costs one word instead of ll.
  • WAH-OP is exact. The loop keeps the invariant that ZZ is the compressed form of X∘YX \circ Y on all groups consumed so far, and that the words of XX and YY in use start at the same group. Both lists cover MM groups, so they end together.
Proof: COMPRESS is lossless and writes M - G words, and WAH-OP computes the compressed form of X op Y in O(p + q) stepsfull

We use the notation of the page: words of w=32w = 32 bits, groups of 31 bits, M=⌊N/31⌋M = \lfloor N / 31 \rfloor full groups and a tail of N−31MN - 31M bits. For a list of regular words ZZ, let D(Z)D(Z) be the sequence of groups it stands for: a literal stands for its own group, and a fill of bit ff and count kk stands for kk groups of 31 copies of ff. We assume that no count reaches 230−12^{30} - 1; Lemma 1 of the paper shows this for N≤232N \le 2^{32}. A list is canonical if no literal is all 0 or all 1 and no two adjacent fills have the same bit.

Lemma 1 (the append procedures). Let ZZ be canonical. After APPEND-LITERAL(Z,g)(Z, g), D(Z)D(Z) is the old D(Z)D(Z) followed by gg, and ZZ is canonical. After APPEND-FILL(Z,f,k)(Z, f, k), D(Z)D(Z) is the old D(Z)D(Z) followed by kk groups of ff, and ZZ is canonical.

Proof. APPEND-FILL either adds kk to the count of a last fill of bit ff (L12), which appends kk groups of ff to D(Z)D(Z), or appends a new fill (L13), which does the same. In the first case no new word appears. In the second case the last word was not a fill of bit ff, so no two adjacent fills share a bit. APPEND-LITERAL sends an all-0 or all-1 group to APPEND-FILL with k=1k = 1 (L8, L9), and appends any other group as a literal (L10), which is not all 0 or all 1. In every case the claim holds. □\square

Claim 1 (COMPRESS is lossless and canonical). COMPRESS returns a canonical list ZZ with D(Z)=(g0,…,gM−1)D(Z) = (g_0, \ldots, g_{M-1}), the full groups of bb in order, and an active word that holds the last N−31MN - 31M bits.

Proof. By induction on the loop of L3 to L5 with Lemma 1: after round ii, D(Z)=(g0,…,gi)D(Z) = (g_0, \ldots, g_i) and ZZ is canonical. The empty list of L1 is canonical. L6 stores the tail. □\square

Claim 2 (Theorem 3 of the paper). Let GG be the number of indices i<M−1i < M - 1 such that gig_i and gi+1g_{i+1} are both all-0 or both all-1. Then ∣Z∣=M−G|Z| = M - G.

Proof. Split g0,…,gM−1g_0, \ldots, g_{M-1} into maximal runs of groups that are all-0, maximal runs that are all-1, and single mixed groups. By Claim 1 and canonicity, each mixed group is one literal word and each maximal run of ll fill groups is exactly one fill word: the run is merged by L12, and two different maximal runs of the same bit are never adjacent, because something else lies between them. A run of length ll contains l−1l - 1 pairs counted by GG, and no pair counted by GG crosses two runs. So the number of words is the sum over runs of l−(l−1)=1l - (l - 1) = 1, plus one per literal, which is M−GM - G. □\square

Claim 3 (size and set bits). If the full groups contain hh set bits, then ∣Z∣≤2h+1|Z| \le 2h + 1.

Proof. At most hh groups are not all-0. The all-0 groups form at most one more maximal run than there are groups that are not all-0, so at most h+1h + 1 runs. Each group that is not all-0 gives at most one word, and each all-0 run gives one word. □\square

Claim 4 (WAH-OP is exact). Let XX and YY be canonical, both with MM groups. WAH-OP returns a canonical list ZZ with D(Z)=(x0∘y0,…,xM−1∘yM−1)D(Z) = (x_0 \circ y_0, \ldots, x_{M-1} \circ y_{M-1}), where xtx_t and yty_t are the groups of XX and YY, and the active word of X∘YX \circ Y.

Proof. Let tt be the number of groups consumed. The invariant at L16 is: (a) D(Z)=(x0∘y0,…,xt−1∘yt−1)D(Z) = (x_0 \circ y_0, \ldots, x_{t-1} \circ y_{t-1}) and ZZ is canonical; (b) word ii of XX covers the groups t,…,t+nx−1t, \ldots, t + nx - 1 that are still unconsumed, and the value xx is the group xtx_t (and equals each of these groups when word ii is a fill); (c) the same holds for YY, jj, nyny and yy.

It holds before the loop with t=0t = 0 (L14, L15). In one step, k=min⁡(nx,ny)≥1k = \min(nx, ny) \ge 1 (L17). If both words are fills, the kk groups xt,…,xt+k−1x_t, \ldots, x_{t+k-1} all equal xx, and the same holds for yy, so the next kk groups of the result all equal x∘yx \circ y, which is all-0 or all-1. L18 appends them by Lemma 1. Otherwise one of the words is a literal, so its remaining count is 1 and k=1k = 1, and L19 appends xt∘ytx_t \circ y_t by Lemma 1. Now tt grows by kk, and L20 to L22 lower both remaining counts by kk and move to the next word when a count reaches 0, which restores (b) and (c).

Both lists cover exactly MM groups, so by (b) and (c), nx=0nx = 0 and ny=0ny = 0 happen at the same tt when t=Mt = M, and i=∣X∣i = |X| and j=∣Y∣j = |Y| hold together. The loop stops there with (a) for t=Mt = M. The tails are combined bit by bit at L23, and the mask removes any bit above the tail length. □\square

By Claims 1 and 4, the result of WAH-OP is the same list that COMPRESS gives on the bits of X∘YX \circ Y: both are canonical lists for the same group sequence, and a canonical list is determined by its group sequence (its words are the maximal runs and the mixed groups, in order).

Claim 5 (the number of steps). If M≥1M \ge 1, the loop runs ss times with max⁡(∣X∣,∣Y∣)≤s≤min⁡(∣X∣+∣Y∣−1,M)\max(|X|, |Y|) \le s \le \min(|X| + |Y| - 1, M).

Proof. In each step, kk equals the remaining count of at least one of the two words, so at least one of ii and jj grows. In the last step both grow, since both lists end together. So s≤∣X∣+∣Y∣−1s \le |X| + |Y| - 1. Each step consumes k≥1k \ge 1 groups and there are MM, so s≤Ms \le M. Each step moves ii and jj by at most one each, and ii must reach ∣X∣|X| and jj must reach ∣Y∣|Y|, so s≥max⁡(∣X∣,∣Y∣)s \ge \max(|X|, |Y|). □\square

Each step does a constant number of word operations, including the work of Lemma 1, so WAH-OP takes O(∣X∣+∣Y∣)O(|X| + |Y|) time and writes at most ∣X∣+∣Y∣−1|X| + |Y| - 1 regular words. This is Theorem 7 of the paper.

The tests check Claims 1 to 5 on random bitmaps of three shapes and several lengths, the example of Fig. 2 of the paper, and the split of a fill at the largest count.

Complexity

All counts are in the word RAM with ww-bit words.

  • COMPRESS does O(1)O(1) work per group, so O(N/w)O(N / w) word operations if the bitmap is given in words, and the output has at most M+1M + 1 words. The bound M−GM - G of Theorem 3 is exact.
  • Size and set bits. A bitmap with hh set bits in its full groups has at most 2h+12h + 1 regular words: at most hh groups are not all 0, and the all-0 groups form at most h+1h + 1 runs, one word each. Summed over the cc bitmaps of an equality-encoded bitmap index on NN rows, this gives at most 2N+c2N + c regular words and cc active words, which is the bound of at most 4N4N words of Proposition 4 of the paper, and about 2N2N when cc is much smaller than NN.
  • WAH-OP. Each step finishes at least one word of XX or of YY, and the last step finishes both, so the loop runs at most p+q−1p + q - 1 times. Each step covers at least one group, so it also runs at most MM times. Each step finishes at most one word of each operand, so it runs at least max⁡(p,q)\max(p, q) times. These are the bounds of Lemma 5 of the paper, and Theorem 7 follows: WAH-OP takes O(p+q)O(p + q) time, and the result has at most p+qp + q words.
  • Against the plain bitmap. A plain AND takes ⌈N/w⌉\lceil N / w \rceil word operations. WAH-OP is faster when p+qp + q is well below N/wN / w, which is the case for sparse bitmaps and for bitmaps with long runs, such as the bitmaps of a column that is sorted or clustered.

Properties

  • Word-aligned. Every word holds whole groups, so no operation shifts bits across word boundaries. This is the reason WAH is faster than byte-aligned codes, at the cost of some space.
  • Canonical form. COMPRESS and WAH-OP give the same word list for the same bits (when no count overflows). Two compressed bitmaps are equal exactly when their word lists and active words are equal.
  • Streaming. Both procedures read their inputs once from left to right, and an append of new bits touches only the last regular word and the active word.
  • No random access. Testing bit rr needs a scan of the words up to the group of rr, unless an extra table of offsets is kept.

Variants and improvements

  • 64-bit words. With w=64w = 64, groups have 63 bits and the count has 62 bits. Fewer words per bitmap, but a sparse bitmap gains less, because a literal now covers more bits that are mostly 0.
  • In-place OR with a sparse operand. Theorem 8 of the paper: when YY is very sparse, an OR that updates XX in place, with XX held uncompressed, takes time linear in the number of words of YY only. This is how many bitmaps of a range are combined.
  • Range queries. For one-dimensional range conditions on a WAH-compressed bitmap index, Propositions 9 and 10 of the paper argue that an OR of many sparse bitmaps with in-place OR takes time linear in the number of hits, which is optimal up to a constant. The argument assumes that the bitmaps involved are sparse, and the authors call these results propositions, not theorems, for that reason.
  • Byte-aligned codes. The byte-aligned bitmap code (BBC) of Antoshenkov uses bytes instead of words. It compresses better, but its operations decode more cases.
  • Later word-aligned codes. Several later codes keep the word alignment and pack a few literal bits into fill words, or store chunks in other ways. Roaring bitmaps instead split row ids into chunks of 2162^{16} and pick an array, a bitmap or runs per chunk, which also allows fast random access.

When to use it

Use WAH for read-mostly bitmap indexes on columns with long runs or few set bits per bitmap, where queries combine many bitmaps with AND and OR: scientific data, star-schema dimensions and log data. If queries need random access to single bits, or if many bitmaps are dense and random, prefer an uncompressed bit vector or a roaring bitmap.

Pitfalls

  • Bit order. The paper and this page put the first bit of a group in the highest of its 31 bits. The bitmap index page and many libraries put row 0 in the lowest bit. Both work, but the two sides of an operation must use the same order.
  • Forgetting the active word. The tail of N mod 31N \bmod 31 bits is not a regular word. An operation must combine the two active words and mask the result to the tail length, as line L23 does.
  • Operands of different lengths. WAH-OP assumes that both bitmaps cover the same MM groups. Extend the shorter bitmap with a 0-fill first, or the loop stops early and drops the tail of the longer one.
  • Non-canonical output. If APPEND-LITERAL does not turn an all-0 or all-1 group into a fill, or APPEND-FILL does not merge with the last word, the output grows. Equality tests on word lists then fail even when the bits are equal.
  • Dense random data. At density near one half, nothing compresses, and WAH is 32/3132/31 times the size of the plain bitmap and slower to combine.
  • Count overflow. A bitmap of more than 2302^{30} groups needs more than one fill word for a long run. Then Theorem 3 counts one word less than COMPRESS writes for each extra fill word.

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.

word_aligned_hybrid_compression.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/word-aligned-hybrid-compression/. The authors are listed in prov/KZ8EQQ.jsonl.

"""Word-aligned hybrid (WAH) compression of bitmaps, with 32-bit words.

A bitmap is a list of bits (0 or 1). It is cut into groups of 31 bits. The
first bit of a group is the highest of its 31 bits, as in Fig. 2 of Wu, Otoo
and Shoshani (2006). A literal word has top bit 0 and holds one group. A fill
word has top bit 1, then the fill bit, then a 30-bit count of groups. The last
N mod 31 bits stay in the active word.
"""

from typing import Callable, List, Sequence, Tuple

W = 32
GROUP = W - 1                    # 31 bits per group
ALL_ONES = (1 << GROUP) - 1      # a group of 31 ones
FILL_FLAG = 1 << (W - 1)         # the top bit of a fill word
FILL_BIT = 1 << (W - 2)          # the fill bit of a fill word
MAX_COUNT = (1 << (W - 2)) - 1   # the largest count of a fill word


class WAH:
    """A compressed bitmap: regular words, the active word and its length."""

    def __init__(self, words: List[int], active: int, nbits: int):
        self.words = words
        self.active = active
        self.nbits = nbits

    def __eq__(self, other):
        return (self.words, self.active, self.nbits) == (other.words, other.active, other.nbits)

    def __repr__(self):
        return "WAH(%s, active=0x%08X, nbits=%d)" % (
            ", ".join("0x%08X" % x for x in self.words), self.active, self.nbits)

    def size(self) -> int:
        """The number of regular words."""
        return len(self.words)

    def groups(self) -> int:
        """The number of full groups, M."""
        return sum(word_count(x) for x in self.words)


def is_fill(word: int) -> bool:
    return bool(word & FILL_FLAG)


def fill_bit(word: int) -> int:
    return 1 if word & FILL_BIT else 0


def word_count(word: int) -> int:
    """The number of groups that a word covers: the count of a fill, 1 for a literal."""
    return word & MAX_COUNT if is_fill(word) else 1


def append_fill(z: List[int], f: int, k: int) -> None:
    """Append k groups of bit f to z, merging with a last fill of the same bit."""
    while k > 0:
        if z and is_fill(z[-1]) and fill_bit(z[-1]) == f and word_count(z[-1]) < MAX_COUNT:  # @line L11
            add = min(k, MAX_COUNT - word_count(z[-1]))
            z[-1] += add                                                      # @line L12
        else:
            add = min(k, MAX_COUNT)
            z.append(FILL_FLAG | (FILL_BIT if f else 0) | add)               # @line L13
        k -= add


def append_literal(z: List[int], g: int) -> None:
    """Append one group g; an all-zero or all-one group becomes a fill."""
    if g == 0:                                                               # @line L8
        append_fill(z, 0, 1)
    elif g == ALL_ONES:                                                      # @line L9
        append_fill(z, 1, 1)
    else:
        z.append(g)                                                          # @line L10


def bits_to_int(bits: Sequence[int]) -> int:
    """The bits as an integer, the first bit highest."""
    v = 0
    for b in bits:
        v = (v << 1) | (1 if b else 0)
    return v


def int_to_bits(v: int, length: int) -> List[int]:
    return [(v >> (length - 1 - i)) & 1 for i in range(length)]


def compress(bits: Sequence[int]) -> WAH:
    """COMPRESS: the WAH form of a bit sequence."""
    z: List[int] = []                                                        # @line L1
    n = len(bits)
    m = n // GROUP                                                           # @line L2
    for i in range(m):                                                       # @line L3
        g = bits_to_int(bits[GROUP * i: GROUP * i + GROUP])                  # @line L4
        append_literal(z, g)                                                 # @line L5
    nbits = n - GROUP * m                                                    # @line L6
    active = bits_to_int(bits[GROUP * m:])                                   # @line L6
    return WAH(z, active, nbits)                                             # @line L7


def decompress(x: WAH) -> List[int]:
    out: List[int] = []
    for word in x.words:
        if is_fill(word):
            out.extend([fill_bit(word)] * (GROUP * word_count(word)))
        else:
            out.extend(int_to_bits(word, GROUP))
    out.extend(int_to_bits(x.active, x.nbits))
    return out


def _run(words: List[int], i: int) -> Tuple[int, int]:
    """RUN: the 31-bit group value of word i and the number of groups it covers."""
    if i >= len(words):
        return 0, 0
    word = words[i]
    if is_fill(word):
        return (ALL_ONES if fill_bit(word) else 0), word_count(word)
    return word, 1


def wah_op(x: WAH, y: WAH, op: Callable[[int, int], int], stats=None) -> WAH:
    """WAH-OP: a bitwise operation on two compressed bitmaps of the same length.

    op works on 31-bit integers (for example lambda a, b: a & b). If stats is a
    dict, the number of loop steps is stored in stats["steps"].
    """
    if x.nbits != y.nbits or x.groups() != y.groups():
        raise ValueError("operands must cover the same number of bits")
    z: List[int] = []                                                        # @line L14
    i = j = 0                                                                # @line L14
    a, na = _run(x.words, 0)                                                 # @line L15
    b, nb = _run(y.words, 0)                                                 # @line L15
    steps = 0
    while i < len(x.words) and j < len(y.words):                             # @line L16
        steps += 1
        k = min(na, nb)                                                      # @line L17
        r = op(a, b) & ALL_ONES
        if is_fill(x.words[i]) and is_fill(y.words[j]):                      # @line L18
            append_fill(z, 1 if r else 0, k)                                 # @line L18
        else:
            append_literal(z, r)                                             # @line L19
        na -= k                                                              # @line L20
        nb -= k                                                              # @line L20
        if na == 0:                                                          # @line L21
            i += 1                                                           # @line L21
            a, na = _run(x.words, i)                                         # @line L21
        if nb == 0:                                                          # @line L22
            j += 1                                                           # @line L22
            b, nb = _run(y.words, j)                                         # @line L22
    mask = (1 << x.nbits) - 1
    active = op(x.active, y.active) & mask                                   # @line L23
    if stats is not None:
        stats["steps"] = steps
    return WAH(z, active, x.nbits)                                           # @line L24


def wah_and(x: WAH, y: WAH, stats=None) -> WAH:
    return wah_op(x, y, lambda a, b: a & b, stats)


def wah_or(x: WAH, y: WAH, stats=None) -> WAH:
    return wah_op(x, y, lambda a, b: a | b, stats)


def wah_xor(x: WAH, y: WAH, stats=None) -> WAH:
    return wah_op(x, y, lambda a, b: a ^ b, stats)


def counting_group_fills(bits: Sequence[int]) -> int:
    """G of Theorem 3: the pairs of consecutive full groups that are both all 0 or both all 1."""
    m = len(bits) // GROUP
    kinds = []
    for i in range(m):
        g = bits_to_int(bits[GROUP * i: GROUP * i + GROUP])
        kinds.append(0 if g == 0 else (1 if g == ALL_ONES else None))
    return sum(1 for i in range(m - 1) if kinds[i] is not None and kinds[i] == kinds[i + 1])
test_word_aligned_hybrid_compression.py 113 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/word-aligned-hybrid-compression/. The authors are listed in prov/KZ8EQQ.jsonl.

import random
import unittest

from word_aligned_hybrid_compression import (
    ALL_ONES, GROUP, MAX_COUNT, WAH, append_fill, compress, counting_group_fills,
    decompress, wah_and, wah_op, wah_or, wah_xor, word_count,
)


def random_bits(rng, n, kind):
    """Bitmaps of three shapes: uniform, sparse, and long runs."""
    if kind == "uniform":
        return [rng.randrange(2) for _ in range(n)]
    if kind == "sparse":
        return [1 if rng.random() < 0.01 else 0 for _ in range(n)]
    bits, b = [], rng.randrange(2)
    while len(bits) < n:
        bits.extend([b] * rng.randint(1, 200))
        b ^= 1
    return bits[:n]


def cases(seed, count):
    rng = random.Random(seed)
    for _ in range(count):
        n = rng.choice([0, 1, 30, 31, 32, 62, 93, 200, 1000, 3000])
        yield rng, n, rng.choice(["uniform", "sparse", "runs"])


class TestWAH(unittest.TestCase):
    def test_figure_2_of_the_paper(self):
        bits = [1] + [0] * 20 + [1] * 3 + [0] * 79 + [1] * 25
        self.assertEqual(len(bits), 128)
        x = compress(bits)
        self.assertEqual(x.words, [0x40000380, 0x80000002, 0x001FFFFF])
        self.assertEqual((x.active, x.nbits), (0xF, 4))
        self.assertEqual(decompress(x), bits)

    def test_round_trip(self):
        for rng, n, kind in cases(1, 150):
            bits = random_bits(rng, n, kind)
            x = compress(bits)
            self.assertEqual(decompress(x), bits)
            self.assertEqual(x.groups(), n // GROUP)
            for word in x.words:
                self.assertLess(word, 1 << 32)

    def test_theorem_3_word_count(self):
        for rng, n, kind in cases(2, 150):
            bits = random_bits(rng, n, kind)
            m = n // GROUP
            self.assertEqual(compress(bits).size(), m - counting_group_fills(bits))

    def test_size_bound_from_set_bits(self):
        for rng, n, kind in cases(3, 150):
            bits = random_bits(rng, n, kind)
            h = sum(bits[: GROUP * (n // GROUP)])
            self.assertLessEqual(compress(bits).size(), 2 * h + 1)

    def test_operations_against_bitwise_lists(self):
        ops = [(wah_and, lambda a, b: a & b), (wah_or, lambda a, b: a | b),
               (wah_xor, lambda a, b: a ^ b)]
        for rng, n, kind in cases(4, 200):
            xb = random_bits(rng, n, kind)
            yb = random_bits(rng, n, rng.choice(["uniform", "sparse", "runs"]))
            x, y = compress(xb), compress(yb)
            for fn, f in ops:
                stats = {}
                z = fn(x, y, stats)
                expect = [f(a, b) for a, b in zip(xb, yb)]
                self.assertEqual(decompress(z), expect)
                # The result is the same word list that COMPRESS gives.
                self.assertEqual(z, compress(expect))
                mx, my, m = x.size(), y.size(), n // GROUP
                if m > 0:
                    self.assertGreaterEqual(stats["steps"], max(mx, my))
                    self.assertLessEqual(stats["steps"], min(mx + my - 1, m))
                else:
                    self.assertEqual(stats["steps"], 0)

    def test_hand_cases(self):
        zero = compress([0] * 93)
        ones = compress([1] * 93)
        self.assertEqual(zero.words, [0x80000003])
        self.assertEqual(ones.words, [0xC0000003])
        self.assertEqual(wah_and(zero, ones).words, [0x80000003])
        self.assertEqual(wah_or(zero, ones).words, [0xC0000003])
        self.assertEqual(wah_xor(ones, ones).words, [0x80000003])
        empty = compress([])
        self.assertEqual(wah_and(empty, empty), WAH([], 0, 0))
        with self.assertRaises(ValueError):
            wah_and(compress([0] * 31), compress([0] * 62))

    def test_long_fill_splits_at_max_count(self):
        z = []
        append_fill(z, 1, MAX_COUNT + 5)
        self.assertEqual([word_count(w) for w in z], [MAX_COUNT, 5])
        append_fill(z, 1, 2)
        self.assertEqual([word_count(w) for w in z], [MAX_COUNT, 7])
        x = WAH(z, 0, 0)
        y = WAH([0x80000000 | (MAX_COUNT), 0x80000007], 0, 0)
        stats = {}
        r = wah_op(x, y, lambda a, b: a & b, stats)
        self.assertEqual(r.words, y.words)
        self.assertEqual(stats["steps"], 2)
        self.assertEqual(ALL_ONES, (1 << 31) - 1)


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

History

Byte-aligned bitmap compression (BBC), due to Antoshenkov, was the usual code for compressed bitmap indexes in the 1990s. Kesheng Wu, Ekow Otoo and Arie Shoshani at Lawrence Berkeley National Laboratory introduced the word-aligned hybrid code at SSDBM 2002. They measured logical operations about 12 times faster than BBC, for about 60% more space, on their test data. Their TODS paper of 2006 gives the word count theorem, the size bound of a whole index and the linear time of the operations. WAH became the code of the FastBit software of that laboratory, and later codes such as roaring bitmaps were compared against it.

References

  1. Kesheng Wu, Ekow J. Otoo and Arie Shoshani, Optimizing bitmap indices with efficient compression, ACM Transactions on Database Systems 31(1) (2006), pp. 1 to 38: Section 3 (literal and fill words, the active word, Fig. 2), Section 4.1 (Lemmas 1 and 2, Theorem 3 on the number of words), Section 4.3 (Proposition 4 on the size of an index), Section 5.1 (Lemma 5, Theorem 7 on the time of the logical operations, Theorem 8 on in-place OR)
  2. Kesheng Wu, Ekow J. Otoo and Arie Shoshani, Compressing bitmap indexes for faster search operations, Proceedings of the 14th International Conference on Scientific and Statistical Database Management (SSDBM 2002), pp. 99 to 108, the first description of WAH and its measured comparison with BBC

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
  • a scene preset for the example