Simple Algorithm
Algorithms & Data Structures · Optimal · 28 min

The Burrows–Wheeler Transform & FM-Index

Compression and search in one structure, behind genome alignment.

Sort all rotations of a string and keep only the last column. The result looks scrambled, yet it can be inverted exactly, it compresses better than the original, and it can count the occurrences of any pattern without being decompressed. The Burrows–Wheeler transform (1994) does all three; it sits inside bzip2 and inside the read aligners that map short DNA sequences to the human genome.

What you’ll learn

  • Compute the Burrows–Wheeler transform of a short string by sorting rotations, and relate it to the suffix array: BWT[i]=s[sa[i]−1]\mathrm{BWT}[i] = s[\mathrm{sa}[i] - 1].
  • Prove the LF-mapping property and invert the transform in O(n)O(n) time.
  • Explain why the transform helps compression, and trace bzip2's pipeline.
  • Count a pattern's occurrences by backward search with O(m)O(m) rank queries, locate them with a sampled suffix array, and describe the FM-index's space and its use in genome read alignment.

Sort the rotations, keep the last column

Append a unique end marker $, smaller than every character, to ss, and write down all n+1n + 1 rotations of s$s\$. Sort them. The first column FF holds the characters in sorted order; the last column LL is the Burrows–Wheeler transform (BWT) of ss.

RowSorted rotationFFLL
0$banana$a
1a$bananan
2ana$banan
3anana$bab
4banana$b$
5na$banana
6nana$bana
The BWT of banana is annb$aa. Row 4 is the original string, the only rotation that ends with the marker.

Why it compresses. Row ii's last character is the one that precedes the context FF-row ii starts with, and rows with similar contexts sort next to each other. In English, the rows starting with "he " are mostly preceded by t, so the last column grows long runs of t. On the 87-character tongue twister "she sells sea shells by the sea shore and the shells she sells are sea shells for sure", the number of runs of equal characters falls from 82 in the text to 39 in its BWT, and after move-to-front coding (replace each character by its position in a list of recently used characters, then move it to the front) 48 of the 87 values are 0, against 5 for the raw text. A stream dominated by small numbers is easy prey for an entropy coder.

Think first In the sorted rotation matrix of s$s\$, which row holds s$s\$ itself? (Not row 0: that one starts with the marker.)

The row whose last character is $: s$s\$ is the only rotation that ends with the marker, so it is row 4 for banana. Inverting the transform does not need to know this row in advance, because it can start from row 0, the rotation that begins with $.

Inverting with the LF-mapping

DerivationProof
  1. X1c<X2c<⋯⟺X1<X2<⋯X_1 c < X_2 c < \cdots \quad\Longleftrightarrow\quad X_1 < X_2 < \cdots

    The rows ending with cc are rotations of the form XcXc. Their order in the matrix is the order of the strings XX, because rotations are distinct and are decided before the final cc.

  2. cX1<cX2<⋯cX_1 < cX_2 < \cdots

    Rotating each of them by one position gives cXcX, and these are exactly the rows starting with cc. Among themselves they are ordered by XX again, since they share the first character:

  3. LF(i)=C[L[i]]+Occ(L[i],i)\mathrm{LF}(i) = C[L[i]] + \mathrm{Occ}(L[i], i)

    So the kk-th row ending with cc and the kk-th row starting with cc are rotations of each other by one position: the same occurrence of cc in the text. The rows starting with cc occupy the block that begins at C[c]C[c], which gives the formula.

Row ii0123456
L[i]L[i]annb$aa
LF(i)\mathrm{LF}(i)1564023
With C[$]=0C[\$] = 0, C[a]=1C[a] = 1, C[b]=4C[b] = 4 and C[n]=5C[n] = 5 for annb$aa. Inverting walks backward through the text: start at row 0, whose last character a is the last character of banana, and repeat "output L[row]L[\mathit{row}], then move to LF(row)\mathrm{LF}(\mathit{row})": rows 0, 1, 5, 2, 6, 3 give a, n, a, n, a, b, which is banana read backward, and the walk ends at row 4.
python
def bwt(s):                                   # s ends with a unique smallest "$"
    sa = sorted(range(len(s)), key=lambda i: s[i:])
    return ''.join(s[i - 1] for i in sa)      # s[-1] is "$" when i == 0

def lf_tables(L):
    C, total = {}, 0
    for c in sorted(set(L)):                  # C[c]: number of characters smaller than c
        C[c] = total
        total += L.count(c)
    rank, seen = [], {}
    for c in L:                               # rank[i]: occurrences of L[i] in L[0..i)
        rank.append(seen.get(c, 0))
        seen[c] = seen.get(c, 0) + 1
    return C, rank

def inverse_bwt(L):
    C, rank = lf_tables(L)
    row, out = 0, []                          # row 0 starts with "$": its last character ends s
    for _ in range(len(L) - 1):
        out.append(L[row])
        row = C[L[row]] + rank[row]           # LF(row)
    return ''.join(reversed(out)) + '$'

bwt uses the slow suffix sort for clarity. The inversion is linear once the ranks are tabulated in one pass (for a constant alphabet): inverse_bwt("annb$aa") returns "banana$".

Predict before you look

Inverting annb$aa, the walk is at row 1, where L[1]=nL[1] = n. Which row does it visit next? (C[n]=5C[n] = 5.)

Show the answer

5

LF(1)=C[n]+Occ(n,1)=5+0=5\mathrm{LF}(1) = C[n] + \mathrm{Occ}(n, 1) = 5 + 0 = 5: this n is the first n in column LL, so it is the first n in column FF, at row 5 (na$bana).

Backward search: the FM-index

The rows of the matrix that start with a string XX form a contiguous range [sp,ep)[\mathit{sp}, \mathit{ep}), exactly like a block of the suffix array. Ferragina and Manzini (2000) noticed that the LF-mapping turns the range for XX into the range for cXcX: of the rows starting with XX, those whose last character is cc are the rotations Xc…Xc\dots, and LF maps them, in order, onto the rows starting with cXcX. So a pattern is matched from its last character to its first, with two rank queries per character: backward search.

DerivationThe update, and its cost
  1. sp′=C[c]+Occ(c,sp),ep′=C[c]+Occ(c,ep)\mathit{sp}' = C[c] + \mathrm{Occ}(c, \mathit{sp}), \qquad \mathit{ep}' = C[c] + \mathrm{Occ}(c, \mathit{ep})

    Start with all rows, the range of the empty string. Within [sp,ep)[\mathit{sp}, \mathit{ep}), the rows ending with cc are its occurrences of cc in column LL, the ranks Occ(c,sp)\mathrm{Occ}(c, \mathit{sp}) to Occ(c,ep)−1\mathrm{Occ}(c, \mathit{ep}) - 1 among all cc's. LF maps them, keeping their order, to consecutive rows of the block that starts at C[c]C[c]:

  2. #occ(p)=ep−sp,using 2m rank queries\#\mathrm{occ}(p) = \mathit{ep} - \mathit{sp}, \qquad \text{using } 2m \text{ rank queries}

    After processing all of pp from right to left, the range holds the rows that start with pp; its size is the number of occurrences, and an empty range means none:

StepCharacterRange of rowsRows start with
start—[0,7)[0, 7)(anything)
1a[1+0, 1+3)=[1,4)[1 + 0,\ 1 + 3) = [1, 4)a
2n[5+0, 5+2)=[5,7)[5 + 0,\ 5 + 2) = [5, 7)na
3a[1+1, 1+3)=[2,4)[1 + 1,\ 1 + 3) = [2, 4)ana
Backward search for "ana" in annb$aa: two rows, so two occurrences. Rows 2 and 3 hold the suffixes starting at sa[2]=3\mathrm{sa}[2] = 3 and sa[3]=1\mathrm{sa}[3] = 1, the positions of "ana" in banana.
python
def count(L, p):                              # backward search: number of occurrences of p
    C, _ = lf_tables(L)
    sp, ep = 0, len(L)                        # rows [sp, ep) start with the part of p read so far
    for c in reversed(p):
        if c not in C:
            return 0
        sp = C[c] + L[:sp].count(c)           # Occ(c, sp): a rank query
        ep = C[c] + L[:ep].count(c)
        if sp >= ep:
            return 0
    return ep - sp

Here each rank query scans a prefix of LL for clarity. An FM-index answers Occ\mathrm{Occ} in O(1)O(1) for small alphabets with stored counts plus rank structures on bit vectors, or in O(log⁡∣Σ∣)O(\log \abs{\Sigma}) with a wavelet tree (Grossi, Gupta & Vitter, 2003), so counting takes O(m)O(m) or O(mlog⁡∣Σ∣)O(m \log \abs{\Sigma}) time, independent of nn.

Locating needs suffix-array values, which the index does not store in full. Keep every Δ\Delta-th text position's suffix-array entry (a sampled suffix array). For a row in the final range, apply LF until reaching a sampled row; after kk steps the answer is that sample plus kk. Each occurrence then costs O(Δ)O(\Delta) steps, with O(n/Δ)O(n / \Delta) samples.

Space. The column LL is as compressible as the text: Ferragina and Manzini showed that their FM-index fits in space bounded in terms of the kk-th order empirical entropy HkH_k of the text, and later refinements surveyed by Navarro and Mäkinen (2007) bring it to about nHknH_k bits plus lower-order terms. A self-index of this kind replaces the text: it can also extract any substring.

Check your understanding

Why does the FM-index match a pattern from its last character to its first?

  1. Because the BWT stores the text reversed
  2. Because LF prepends a character: from the rows starting with XX it reaches the rows starting with cXcX
  3. Because the first column FF is not stored
  4. Because right-to-left matching skips characters, as in Boyer–Moore
Show the answer

B. Because LF prepends a character: from the rows starting with XX it reaches the rows starting with cXcX

LF moves from a row to the row of the rotation that starts one character earlier in the text, so ranges grow by one character on the left. Matching pp therefore starts with its last character and prepends the others.

Genomes, and the frontier

A sequencing machine produces millions of short DNA reads, each to be placed where it best matches a reference genome of about 3 billion bases. Bowtie (Langmead, Trapnell, Pop & Salzberg, 2009) and BWA (Li & Durbin, 2009) index the genome with an FM-index small enough for an ordinary computer's memory, a few gigabytes instead of the tens of gigabytes a suffix tree would need, and match each read by backward search. Mismatches are handled by backtracking: at a position of the read, try the other three bases as well, extending each surviving range to the left, with limits on how many such branches a read may take.

Key takeaways

  • The BWT is the last column of the sorted rotations of s$s\$, equivalently L[i]=s[sa[i]−1]L[i] = s[\mathrm{sa}[i] - 1], so a linear-time suffix array gives a linear-time BWT.
  • Characters are grouped by the context that follows them, so the BWT has long runs that move-to-front and entropy coding exploit, as in bzip2.
  • The LF-mapping, LF(i)=C[L[i]]+Occ(L[i],i)\mathrm{LF}(i) = C[L[i]] + \mathrm{Occ}(L[i], i), follows the text backward and inverts the transform in O(n)O(n).
  • Backward search counts a pattern with 2m2m rank queries, independent of nn; a sampled suffix array locates occurrences, and the whole FM-index fits in about nHknH_k bits plus lower-order terms.
  • FM-indexes run genome read aligners such as Bowtie and BWA; run-length variants (the r-index) index highly repetitive collections in space proportional to the number of BWT runs.

Check yourself

In the interactive lesson these are scored with your confidence, and what you miss comes back for review.

Question 1

The suffix array of banana$ is [6,5,3,1,0,4,2][6, 5, 3, 1, 0, 4, 2]. What is the BWT character at row 2?

  1. a
  2. b
  3. $
  4. n
Show the answer

D. n

L[2]=s[sa[2]−1]=s[2]=L[2] = s[\mathrm{sa}[2] - 1] = s[2] = n: the suffix at row 2, ana$, starts at position 3 and is preceded by the n at position 2.

Question 2

What makes the Burrows–Wheeler transform invertible?

  1. It stores the original string's row and the sorted first column
  2. The kk-th occurrence of a character in the last column and its kk-th occurrence in the first column are the same character of the text
  3. Each character's frequency is preserved, so the text can be reassembled by counting
  4. Sorting is a permutation, and every permutation of a string is invertible
Show the answer

B. The kk-th occurrence of a character in the last column and its kk-th occurrence in the first column are the same character of the text

The LF property links each character to the one before it in the text, so walking LF from the row that starts with the marker spells the text backward. The first column needs no storage: it is LL sorted.

Question 3

An FM-index of a 3-billion-character genome counts the occurrences of a 100-character read. How many rank queries does backward search make, at most?

  1. About log⁡2(3×109)≈32\log_2 (3 \times 10^9) \approx 32
  2. About 100×32100 \times 32
  3. 200
  4. 3×1093 \times 10^9
Show the answer

C. 200

Two rank queries, Occ(c,sp)\mathrm{Occ}(c, \mathit{sp}) and Occ(c,ep)\mathrm{Occ}(c, \mathit{ep}), per character of the read: at most 200, and fewer if the range empties early. The length of the genome does not appear, which is the point of the index.

Question 4

Why is the BWT of an English text more compressible than the text itself?

  1. It removes repeated characters
  2. It sorts the characters, like column FF
  3. Characters followed by similar contexts become adjacent, so the last column has long runs of a few characters
  4. It replaces frequent words by short codes
Show the answer

C. Characters followed by similar contexts become adjacent, so the last column has long runs of a few characters

Row ii ends with the character that precedes the context the row starts with. Sorting groups similar contexts, and similar contexts tend to be preceded by the same characters (t before "he "), so runs appear, which move-to-front turns into small numbers for an entropy coder.

Further reading

  • M. Burrows & D. J. Wheeler, "A block-sorting lossless data compression algorithm," SRC Research Report 124, Digital Equipment Corporation (1994).
  • P. Ferragina & G. Manzini, "Indexing compressed text," Journal of the ACM 52(4) (2005), 552–581; first presented as "Opportunistic data structures with applications," FOCS 2000.
  • G. Navarro & V. Mäkinen, "Compressed full-text indexes," ACM Computing Surveys 39(1) (2007), article 2.
  • B. Langmead, C. Trapnell, M. Pop & S. L. Salzberg, "Ultrafast and memory-efficient alignment of short DNA sequences to the human genome," Genome Biology 10(3) (2009), R25.
  • H. Li & R. Durbin, "Fast and accurate short read alignment with Burrows–Wheeler transform," Bioinformatics 25(14) (2009), 1754–1760.