TExcelTAD
Home › Advanced & Succinct Data Structures › The Burrows-Wheeler Transform and the FM-Index

The Burrows-Wheeler Transform and the FM-Index

A suffix array answers pattern queries fast but takes nlg⁡nn \lg n bits, many times the size of the text. The FM-index (Ferragina and Manzini, 2000) is a compressed full-text index: it takes space close to the compressed size of the text, and it can count the occurrences of a pattern PP of length mm with O(m)O(m) rank queries, without the text or the suffix array. It also replaces the text: any substring can be extracted from it. Read aligners in genomics (BWA, Bowtie) index human genomes this way in a few gigabytes.

The Burrows-Wheeler transform

Burrows and Wheeler (1994) defined a reversible permutation of the text. Write all rotations of T$T\$, sort them, and take the last column LL. Equivalently, using the suffix array, L[j]=T[SA[j]−1]L[j] = T[SA[j] - 1]: the character before each suffix in sorted order (with $\$ before the suffix starting at 0).

Sorting groups suffixes that start with the same context, and the characters that precede a common context are often the same ("_th" is usually preceded by space or "e", in "the"), so LL has long runs and compresses well with move-to-front and entropy coding: that is how bzip2 works.

Reversibility: the LF mapping. Let FF be the first column (the sorted characters). The kk-th occurrence of a character cc in LL and the kk-th occurrence of cc in FF are the same character of the text: both orders sort the occurrences of cc by the suffix that follows them. So

LF⁡(j)=C[c]+rank⁡c(L,j),c=L[j]\operatorname{LF}(j) = C[c] + \operatorname{rank}_c(L, j), \qquad c = L[j]

maps row jj to the row of the suffix that starts one position earlier, where C[c]C[c] is the number of characters smaller than cc in TT and rank⁡c(L,j)\operatorname{rank}_c(L, j) counts the cc's in L[0..j−1]L[0..j-1]. Starting at the row of "$\$" and applying LF repeatedly reads the text backwards.

python · try it yourself
def suffix_array(s):
    n = len(s)
    rank, sa, k = [ord(c) for c in s], list(range(n)), 1
    while True:
        key = lambda i: (rank[i], rank[i + k] if i + k < n else -1)
        sa.sort(key=key)
        new = [0] * n
        for j in range(1, n):
            new[sa[j]] = new[sa[j - 1]] + (key(sa[j]) != key(sa[j - 1]))
        rank = new
        if rank[sa[-1]] == n - 1: return sa
        k *= 2

def bwt(s):
    sa = suffix_array(s)
    return "".join(s[i - 1] for i in sa), sa      # s[-1] is the sentinel for i = 0

def inverse_bwt(L):
    """Rebuild the text from its BWT with the LF mapping: LF(j) = C[L[j]] + rank of L[j] in L[0..j-1]."""
    C, total = {}, 0
    for c in sorted(set(L)):
        C[c] = total; total += L.count(c)
    seen, LF = {}, []
    for c in L:
        LF.append(C[c] + seen.get(c, 0)); seen[c] = seen.get(c, 0) + 1
    j, out = 0, []                                 # row 0 is the suffix "
quot; for _ in range(len(L) - 1): out.append(L[j]); j = LF[j] # L[j] is the character before row j's suffix return "".join(reversed(out)) + "
quot; s = "banana
quot; L, sa = bwt(s) print("sorted rotations (the BWT is the last column):") for j, i in enumerate(sa): rot = s[i:] + s[:i] print(f" {rot} SA[{j}] = {i}") print("BWT:", L, " inverse:", inverse_bwt(L)) for text in ["abracadabra
quot;, "the_theme_of_the_thesis_is_these_themes
quot;]: L, _ = bwt(text) runs = 1 + sum(L[i] != L[i - 1] for i in range(1, len(L))) print(f"{text!r}: BWT {L!r}, {runs} runs for {len(text)} characters, inverts: {inverse_bwt(L) == text}")
sorted rotations (the BWT is the last column):
  $banana   SA[0] = 6
  a$banan   SA[1] = 5
  ana$ban   SA[2] = 3
  anana$b   SA[3] = 1
  banana$   SA[4] = 0
  na$bana   SA[5] = 4
  nana$ba   SA[6] = 2
BWT: annb$aa  inverse: banana$
'abracadabra
  

: BWT 'ard$rcaaaabb', 8 runs for 12 characters, inverts: True
'the_theme_of_the_thesis_is_these_themes
  

: BWT 'ssefeesemhshhhmhhotttttts_ee_eiiee$_____', 23 runs for 40 characters, inverts: True

The repetitive English-like text has 23 runs in 40 characters; random text would have nearly one run per character. The more repetitive the text, the fewer runs, and the run-length FM-index (Mäkinen and Navarro; Gagie, Navarro and Prezza's r-index, 2018) uses space proportional to the number of runs rr, which for collections of similar genomes is hundreds of times smaller than nn.

Backward search

To count the occurrences of PP, find the interval [sp,ep)[sp, ep) of suffix-array rows whose suffixes start with PP. Process PP from its last character to its first. For the empty suffix of PP the interval is all rows. If [sp,ep)[sp, ep) is the interval of the suffixes starting with XX, then the rows starting with cXcX are the LF images of the rows in [sp,ep)[sp, ep) that have L[j]=cL[j] = c, and LF keeps their order, so

sp′=C[c]+rank⁡c(L,sp),ep′=C[c]+rank⁡c(L,ep)sp' = C[c] + \operatorname{rank}_c(L, sp), \qquad ep' = C[c] + \operatorname{rank}_c(L, ep)
text
BACKWARD-SEARCH(P)                    // returns the number of occurrences
1  sp = 0; ep = n
2  for i = m - 1 down to 0
3      c = P[i]
4      sp = C[c] + RANK(c, L, sp)
5      ep = C[c] + RANK(c, L, ep)
6      if sp >= ep  return 0
7  return ep - sp

That is exactly 2m2m rank queries: with O(1)O(1) rank the count costs O(m)O(m), independent of nn. Locating an occurrence needs its text position SA[j]SA[j]. Store SA[j]SA[j] only for rows whose text position is a multiple of ss (about n/sn/s samples); for another row, apply LF until a sampled row is reached, at most s−1s - 1 steps, and add the number of steps. The program implements counting and locating, with rank answered from stored counts every 32 positions plus a short scan, and samples every 16th text position.

python · try it yourself
import random

def suffix_array(s):
    n = len(s)
    rank, sa, k = [ord(c) for c in s], list(range(n)), 1
    while True:
        key = lambda i: (rank[i], rank[i + k] if i + k < n else -1)
        sa.sort(key=key)
        new = [0] * n
        for j in range(1, n):
            new[sa[j]] = new[sa[j - 1]] + (key(sa[j]) != key(sa[j - 1]))
        rank = new
        if rank[sa[-1]] == n - 1: return sa
        k *= 2

class FMIndex:
    def __init__(self, text, step=32, sample=16):
        sa = suffix_array(text)
        self.L = "".join(text[i - 1] for i in sa)
        self.n, self.step = len(text), step
        alphabet = sorted(set(text))
        self.C, total = {}, 0                       # C[c] = number of characters smaller than c
        for c in alphabet:
            self.C[c] = total; total += self.L.count(c)
        self.checkpoints = {c: [] for c in alphabet}   # rank of c at every multiple of step
        counts = dict.fromkeys(alphabet, 0)
        for j in range(self.n + 1):
            if j % step == 0:
                for a in alphabet: self.checkpoints[a].append(counts[a])
            if j < self.n: counts[self.L[j]] += 1
        self.samples = {j: i for j, i in enumerate(sa) if i % sample == 0}   # sampled SA entries
        self.rank_queries = self.lf_steps = 0
    def rank(self, c, j):                           # occurrences of c in L[0..j-1]
        self.rank_queries += 1
        q = j // self.step                          # a stored count, then a short scan
        return self.checkpoints[c][q] + self.L.count(c, q * self.step, j)
    def count_range(self, p):                       # backward search: the SA interval [sp, ep) of p
        sp, ep = 0, self.n
        for c in reversed(p):
            if c not in self.C: return 0, 0
            sp, ep = self.C[c] + self.rank(c, sp), self.C[c] + self.rank(c, ep)
            if sp >= ep: return 0, 0
        return sp, ep
    def locate(self, j):                            # walk LF until a sampled row
        steps = 0
        while j not in self.samples:
            c = self.L[j]
            j = self.C[c] + self.rank(c, j)
            steps += 1
        self.lf_steps += steps
        return self.samples[j] + steps

rng = random.Random(2000)
text = "".join(rng.choice("ACGT") for _ in range(20000)) + "
quot; fm = FMIndex(text) for p in ["GATTACA", "ACGT", "CAT", "TTTTTTTT"]: fm.rank_queries = fm.lf_steps = 0 sp, ep = fm.count_range(p) count_queries = fm.rank_queries occ = sorted(fm.locate(j) for j in range(sp, ep)) assert occ == [i for i in range(len(text)) if text.startswith(p, i)] print(f"{p:9}: {ep - sp:4} occurrences; counting used {count_queries:2} rank queries (2|P| = {2 * len(p)}), " f"locating {fm.lf_steps / max(1, ep - sp):.1f} LF steps per occurrence") n = len(text) ck = sum(len(v) for v in fm.checkpoints.values()) * 32 print(f"space: BWT {2 * n} bits (2 per character) + rank checkpoints {ck} bits " f"+ SA samples {len(fm.samples) * 32} bits, vs suffix array {32 * n} bits")
GATTACA  :    1 occurrences; counting used 14 rank queries (2|P| = 14), locating 9.0 LF steps per occurrence
ACGT     :   71 occurrences; counting used  8 rank queries (2|P| = 8), locating 7.2 LF steps per occurrence
CAT      :  291 occurrences; counting used  6 rank queries (2|P| = 6), locating 7.7 LF steps per occurrence
TTTTTTTT :    1 occurrences; counting used 16 rank queries (2|P| = 16), locating 14.0 LF steps per occurrence
space: BWT 40002 bits (2 per character) + rank checkpoints 100160 bits + SA samples 40032 bits, vs suffix array 640032 bits

Counting always used exactly 2m2m rank queries. Locating cost about s/2s/2 LF steps per occurrence on average, never more than s−1=15s - 1 = 15. Even with these simple, uncompressed rank counters, the index is about 3.5 times smaller than the suffix array alone; with a compressed rank structure the whole index fits in roughly the size of the 2-bit text.

In C++

An FM-index over bytes with rank counts every 64 positions, counting patterns in "mississippi" and in 200000 random DNA characters, checked against std::string::find.

cpp · try it yourself
#include <algorithm>
#include <array>
#include <cstdio>
#include <numeric>
#include <random>
#include <string>
#include <vector>

std::vector<int> suffix_array(const std::string& s) {
    int n = static_cast<int>(s.size());
    std::vector<int> sa(n), rank(n), tmp(n);
    std::iota(sa.begin(), sa.end(), 0);
    for (int i = 0; i < n; ++i) rank[i] = static_cast<unsigned char>(s[i]);
    for (int k = 1;; k *= 2) {
        auto key = [&](int i) { return std::pair{rank[i], i + k < n ? rank[i + k] : -1}; };
        std::sort(sa.begin(), sa.end(), [&](int a, int b) { return key(a) < key(b); });
        tmp[sa[0]] = 0;
        for (int j = 1; j < n; ++j) tmp[sa[j]] = tmp[sa[j - 1]] + (key(sa[j - 1]) < key(sa[j]));
        rank = tmp;
        if (rank[sa[n - 1]] == n - 1) return sa;
    }
}

// FM-index over bytes: C table + rank checkpoints every 64 positions.
class FMIndex {
    std::string L;
    std::array<int, 256> C{};
    std::vector<std::array<int, 256>> check;
    int rank(unsigned char c, int j) const {               // occurrences of c in L[0..j-1]
        int r = check[j / 64][c];
        for (int i = j / 64 * 64; i < j; ++i) r += static_cast<unsigned char>(L[i]) == c;
        return r;
    }
public:
    explicit FMIndex(const std::string& text) {
        auto sa = suffix_array(text);
        for (int i : sa) L.push_back(text[(i + text.size() - 1) % text.size()]);
        std::array<int, 256> cnt{};
        for (std::size_t j = 0; j <= L.size(); ++j) {
            if (j % 64 == 0) check.push_back(cnt);
            if (j < L.size()) ++cnt[static_cast<unsigned char>(L[j])];
        }
        for (int c = 0, total = 0; c < 256; ++c) { C[c] = total; total += cnt[c]; }
    }
    const std::string& bwt() const { return L; }
    int count(const std::string& p) const {                // backward search
        int sp = 0, ep = static_cast<int>(L.size());
        for (auto it = p.rbegin(); it != p.rend() && sp < ep; ++it) {
            unsigned char c = static_cast<unsigned char>(*it);
            sp = C[c] + rank(c, sp);
            ep = C[c] + rank(c, ep);
        }
        return std::max(0, ep - sp);
    }
};

int main() {
    FMIndex small("mississippi
quot;); std::printf("BWT of mississippi$: %s\n", small.bwt().c_str()); for (const char* p : {"ssi", "issi", "ppi", "sip", "x"}) std::printf("count(%s) = %d\n", p, small.count(p)); std::mt19937 rng(2000); std::string text; for (int i = 0; i < 200000; ++i) text.push_back("ACGT"[rng() % 4]); text.push_back(' ); FMIndex big(text); for (const char* p : {"GATTACA", "ACGTACGT", "CCCCCCCCC"}) { std::string q(p); int naive = 0; for (std::size_t pos = text.find(q); pos != std::string::npos; pos = text.find(q, pos + 1)) ++naive; std::printf("%-10s FM-index count %3d, naive %3d\n", p, big.count(q), naive); } }
BWT of mississippi$: ipssm$pissii
count(ssi) = 2
count(issi) = 2
count(ppi) = 1
count(sip) = 1
count(x) = 0
GATTACA    FM-index count  13, naive  13
ACGTACGT   FM-index count   4, naive   4
CCCCCCCCC  FM-index count   0, naive   0

Space: entropy-compressed

To support rank⁡c\operatorname{rank}_c on LL for a general alphabet, the FM-index stores LL in a wavelet tree (Grossi, Gupta and Vitter, 2003): a binary tree over the alphabet in which each node holds a bit vector saying, for each character in its range, whether it goes left or right. rank⁡c\operatorname{rank}_c is then ⌈lg⁡σ⌉\lceil \lg \sigma \rceil binary rank queries. Compressing those bit vectors, or splitting LL into blocks by context, gives the space bound:

Theorem (Ferragina and Manzini; refined by later work). The FM-index of a text of length nn over an alphabet of size σ\sigma can be stored in nHk(T)+o(nlg⁡σ)n H_k(T) + o(n \lg \sigma) bits, for any k≤αlog⁡σnk \le \alpha \log_\sigma n with constant 0<α<10 < \alpha < 1, where HkH_k is the kk-th order empirical entropy of the text. It counts occurrences in O(mlg⁡σ)O(m \lg \sigma) time with a wavelet tree (O(m)O(m) for small alphabets), locates each occurrence in O(slg⁡σ)O(s \lg \sigma) time with O(nslg⁡n)O(\frac{n}{s} \lg n) extra bits for samples, and extracts any substring of length ℓ\ell in O((s+ℓ)lg⁡σ)O((s + \ell) \lg \sigma) time.

HkH_k is at most lg⁡σ\lg \sigma and usually much less for natural text, so the index can be smaller than the plain text while answering queries the plain text cannot.

Index Space for nn characters Count PP Locate each occurrence
suffix tree 10 to 20 bytes per character O(m)O(m) O(1)O(1)
suffix array nlg⁡nn \lg n bits O(mlg⁡n)O(m \lg n) O(1)O(1)
FM-index nHk+o(nlg⁡σ)n H_k + o(n \lg \sigma) bits O(mlg⁡σ)O(m \lg \sigma) O(slg⁡σ)O(s \lg \sigma)
r-index O(r)O(r) words, rr = runs in the BWT O(mlg⁡lg⁡n)O(m \lg \lg n) roughly O(lg⁡lg⁡n)O(\lg \lg n) roughly

Test yourself

How is the BWT of TT obtained from its suffix array?

  1. L[j]=T[SA[j]]L[j] = T[SA[j]]
  2. L[j]=T[SA[j]−1]L[j] = T[SA[j] - 1], the character before each suffix in sorted order (with the sentinel before position 0)
  3. L[j]=SA[T[j]]L[j] = SA[T[j]]
  4. By sorting the characters of TT

How many rank queries does backward search use to count the occurrences of a pattern of length mm?

  1. mm
  2. 2m2m, two per character of the pattern
  3. mlg⁡nm \lg n
  4. One per occurrence

Why does the LF mapping preserve the order of the rows it maps?

  1. Because LL is sorted
  2. Because the occurrences of a character cc appear in the same relative order in LL and in FF: both are ordered by the suffix that follows them
  3. Because of the sentinel
  4. Because rank is monotone