Algorithm Search⌘K

Data structureadvanced

Positional Burrows-Wheeler transform

Also called PBWT.

Durbin's sorting of haplotypes at each site by their reversed prefixes. It finds all set-maximal matches in O(NM) time for M haplotypes and N sites, which is linear in the input size.

Time
O(N M) buildO(N M + R) long-matches · set-maximal-matches
Space
O(N M) all-arraysO(M) streaming
Where
M = the number of haplotypes; N = the number of sites; R = the number of reported matches
Origin
Richard Durbin, 2014

The positional Burrows-Wheeler transform (PBWT) is a set of arrays that describe, for a panel of MM binary haplotypes over NN sites, the order of the haplotypes sorted by their reversed prefixes at every site kk. A second array at each site gives the start of the match of each haplotype with its neighbor in that order. Durbin (2014) showed that both arrays at site k+1k + 1 come from those at site kk in one stable pass over column kk. So the transform takes O(NM)O(NM) time, and from it all set-maximal matches between haplotypes can be listed in O(NM)O(NM) time, which is linear in the input size. Unlike the Burrows-Wheeler transform and the FM-index, which sort the suffixes of one string, the PBWT sorts many aligned strings by their prefixes read backward from each site.

In plain words

Think of many copies of a chromosome, each written as a row of 0s and 1s, one column per variant. At each column, put the rows in order by what they read just before that column, then the column before that, and so on going back. Rows that share a long stretch ending at that column then sit next to each other.

When you move one column to the right, you do not sort again. You go down the current order once and put each row in one of two piles, by its value in the new column, keeping the order inside each pile. The two piles, one after the other, are the new order. Next to the order, the structure keeps for each row where its shared stretch with the row above begins. That is enough to find all long shared stretches.

The abstract type

Input. Haplotypes x0,…,xM−1∈{0,1}Nx_0, \ldots, x_{M-1} \in \{0, 1\}^N. Write xi[s,e)x_i[s, e) for the sites s,…,e−1s, \ldots, e - 1 of xix_i.

Prefix arrays. For k=0,…,Nk = 0, \ldots, N, aka_k is the permutation of 0,…,M−10, \ldots, M - 1 that sorts the haplotypes by the reversed prefix xi[k−1],xi[k−2],…,xi[0]x_i[k - 1], x_i[k - 2], \ldots, x_i[0] in lexicographic order, with ties broken by the index ii. So a0a_0 is the identity.

Divergence arrays. For k≥0k \ge 0 and 1≤r<M1 \le r < M, dk[r]d_k[r] is the smallest ss such that xak[r][s,k)=xak[r−1][s,k)x_{a_k[r]}[s, k) = x_{a_k[r-1]}[s, k); it is kk if the two haplotypes differ at site k−1k - 1. By convention dk[0]=kd_k[0] = k.

Matches. A match between xix_i and xjx_j is an interval [s,e)[s, e) with s<es < e on which they agree. It is maximal if it cannot grow: s=0s = 0 or xi[s−1]≠xj[s−1]x_i[s - 1] \ne x_j[s - 1], and e=Ne = N or xi[e]≠xj[e]x_i[e] \ne x_j[e]. A maximal match of xix_i to xjx_j on [s,e)[s, e) is set-maximal if no match of xix_i to any haplotype covers [s,e)[s, e) and is longer.

Queries. Report all maximal matches of length at least LL. Report all set-maximal matches. Find the longest matches of a new haplotype zz to the panel.

Representation

At each site, the structure holds aka_k and dkd_k, two integer arrays of length MM. A program that streams over the sites keeps only the current pair, in O(M)O(M) space. To store a panel, Durbin keeps the column yk[r]=xak[r][k]y_k[r] = x_{a_k[r]}[k] in sort order instead of aka_k. Because similar haplotypes are adjacent, yky_k has long runs of equal values and compresses well with run-length coding, and ak+1a_{k+1} can be computed from aka_k and yky_k.

Operations

Building the arrays. Durbin's Algorithm 2 computes (ak+1,dk+1)(a_{k+1}, d_{k+1}) from (ak,dk)(a_k, d_k) and column kk:

  1. PBWT-BUILD(x_0, ..., x_{M-1})
  2. 1a ← (0, 1, ..., M-1); d ← (0, ..., 0)
  3. 2for k = 0 to N-1 do
  4. 3zeros, ones ← empty; p ← k+1; q ← k+1
  5. 4for r = 0 to M-1 do ▷ in the order a
  6. 5p ← max(p, d[r]); q ← max(q, d[r])
  7. 6if x_{a[r]}[k] = 0 then append (a[r], p) to zeros; p ← 0
  8. 7else append (a[r], q) to ones; q ← 0
  9. 8a ← indices of zeros then of ones; d ← their divergences
  10. 9return the arrays a_0..a_N and d_0..d_N

Line L6 puts a haplotype with 0 at site kk in the zero pile. Its divergence in the new order is the largest dd seen since the previous row with 0 at site kk, because its new neighbor above is that row, and the match between them is the intersection of the matches of the rows in between. The value k+1k + 1 for the first row of each pile records that it has no match ending at site k+1k + 1 with the row above it. Line L7 does the same for the ones.

Long matches. At site kk, cut the order aka_k into blocks at the rows rr with dk[r]>k−Ld_k[r] > k - L. Two rows in the same block share at least LL sites before kk, and two rows in different blocks do not. Within a block, a pair whose values at site kk differ (or any pair when k=Nk = N) is a maximal match of length at least LL ending at kk. Durbin's Algorithm 3 lists these pairs by splitting each block by the value at site kk, in time O(M)O(M) per site plus the size of the output.

Set-maximal matches. At site kk, the longest match of xak[r]x_{a_k[r]} ending at kk is with the row above or the row below, with start min⁡(dk[r],dk[r+1])\min(d_k[r], d_k[r + 1]). Algorithm 4 scans up from rr while the divergences stay at most this start, and down in the same way. If any row in this range has the same value at site kk, the match goes on past kk and none is reported. Otherwise each row in the range gives a set-maximal match ending at kk. Sentinels dk[0]=dk[M]=k+1d_k[0] = d_k[M] = k + 1 stop the scans at the ends.

Matching a new haplotype. Durbin's Algorithm 5 keeps, for a new sequence zz, the interval of rows of aka_k that share the longest suffix with z[0,k)z[0, k), and updates it at each site with rank counts on yky_k, in the way that backward search updates an interval in the FM-index. It reports the set-maximal matches of zz in time O(N)O(N) beyond the precomputed counts.

Example

Five haplotypes over five sites:

site 0 site 1 site 2 site 3 site 4
x0x_0 0 1 0 1 0
x1x_1 1 1 0 0 1
x2x_2 0 1 1 1 0
x3x_3 1 0 0 0 1
x4x_4 0 1 0 1 1

The arrays are

kk aka_k dkd_k
0 0 1 2 3 4 0 0 0 0 0
1 0 2 4 1 3 1 0 0 1 0
2 3 0 2 4 1 2 2 0 0 1
3 3 0 4 1 2 3 2 0 1 3
4 3 1 0 4 2 4 2 4 0 3
5 0 2 3 1 4 5 3 5 2 4

At k=1k = 1, column 0 is (0,1,0,1,0)(0, 1, 0, 1, 0) in the order a0a_0, so the zero pile is 0,2,40, 2, 4 and the one pile is 1,31, 3. At k=5k = 5, the reversed prefixes are 0101001010 for x0x_0, 0111001110 for x2x_2, 1000110001 for x3x_3, 1001110011 for x1x_1 and 1101011010 for x4x_4, which is the order a5a_5. The entry d5=2d_5 = 2 for x1x_1 says that x1x_1 and x3x_3 agree on sites 2 to 4.

With L=3L = 3, the long matches are x0x_0 and x4x_4 on [0,4)[0, 4), found at k=4k = 4, where they are adjacent with d4=0d_4 = 0 and differ at site 4, and x1x_1 and x3x_3 on [2,5)[2, 5), found at k=5k = 5. The set-maximal matches of x0x_0 are to x4x_4 on [0,4)[0, 4) and to x2x_2 on [3,5)[3, 5); its shorter match to x2x_2 on [0,2)[0, 2) is covered by the match to x4x_4 and is not set-maximal for x0x_0.

Correctness

The main claim is that line L8 gives the true ak+1a_{k+1} and dk+1d_{k+1}. For the order: two haplotypes with different values at site kk compare by that value, since it is the first symbol of the reversed prefix of length k+1k + 1, so all zeros come before all ones. Two haplotypes with the same value compare by their reversed prefixes of length kk, which is their order in aka_k, and the pass keeps that order within each pile. Ties remain broken by index because the pass is stable. For the divergence: if rows r′<rr' < r of aka_k are adjacent in the new zero pile, the match between them ending at kk starts at max⁡(dk[r′+1],…,dk[r])\max(d_k[r' + 1], \ldots, d_k[r]), because the common suffix of two rows of a sorted list is the minimum of the common suffixes of the adjacent pairs between them. Adding site kk, where both have 0, keeps the start. This is the value of pp at line L6. The claims for the match reports follow from the same fact: the haplotypes that share at least ℓ\ell sites before kk with a given row form a contiguous range of the order around it. The full proof is below.

Proof: One stable pass per site gives the prefix and divergence arrays, and the block and scan rules list exactly the long and set-maximal matchesfull

Setting. Haplotypes x0,…,xM−1∈{0,1}Nx_0, \ldots, x_{M-1} \in \{0, 1\}^N. For 0≤k≤N0 \le k \le N, let ρk(i)\rho_k(i) be the reversed prefix xi[k−1],…,xi[0]x_i[k - 1], \ldots, x_i[0], a string of length kk. Then aka_k sorts the indices by the key (ρk(i),i)(\rho_k(i), i) in lexicographic order. For u≠vu \ne v, let σk(u,v)\sigma_k(u, v) be the smallest ss with xu[s,k)=xv[s,k)x_u[s, k) = x_v[s, k), so the common suffix of xu[0,k)x_u[0, k) and xv[0,k)x_v[0, k) has length k−σk(u,v)k - \sigma_k(u, v). Then dk[r]=σk(ak[r−1],ak[r])d_k[r] = \sigma_k(a_k[r - 1], a_k[r]) for r≥1r \ge 1, and dk[0]=kd_k[0] = k.

Lemma 1 (range minimum of common prefixes). For rows r′<rr' < r of aka_k, σk(ak[r′],ak[r])=max⁡(dk[r′+1],…,dk[r])\sigma_k(a_k[r'], a_k[r]) = \max(d_k[r' + 1], \ldots, d_k[r]).

Proof. The length of the common prefix of ρk(u)\rho_k(u) and ρk(v)\rho_k(v) is k−σk(u,v)k - \sigma_k(u, v). In a list of strings in lexicographic order, the common prefix of two entries is the shortest common prefix of the adjacent pairs between them. If the strings wr′,…,wrw_{r'}, \ldots, w_r are sorted and all adjacent pairs share the first ℓ\ell symbols, then all of them share the first ℓ\ell symbols, so the common prefix of wr′w_{r'} and wrw_r has length at least ℓ\ell. Conversely, suppose wr′w_{r'} and wrw_r share the first ℓ+1\ell + 1 symbols. Every wtw_t with r′≤t≤rr' \le t \le r lies between them in lexicographic order, so it also has those ℓ+1\ell + 1 symbols, and every adjacent pair between them shares at least ℓ+1\ell + 1 symbols. So the two lengths are equal, and the claim follows by taking kk minus each side. Ties in the key, which are equal strings, have common prefix kk and fit the same argument. □\square

Lemma 2 (the order). The list of zeros followed by the list of ones at line L8 is ak+1a_{k+1}.

Proof. ρk+1(i)\rho_{k+1}(i) is xi[k]x_i[k] followed by ρk(i)\rho_k(i). If xu[k]<xv[k]x_u[k] < x_v[k], then uu comes before vv in ak+1a_{k+1} by the first symbol, and the pass puts uu in the zero list and vv in the one list, which comes later. If xu[k]=xv[k]x_u[k] = x_v[k], the keys (ρk+1(u),u)(\rho_{k+1}(u), u) and (ρk+1(v),v)(\rho_{k+1}(v), v) compare as (ρk(u),u)(\rho_k(u), u) and (ρk(v),v)(\rho_k(v), v), that is, in the order of aka_k. The pass visits the rows in the order aka_k and appends to each list at the end, so the relative order in each list is that of aka_k. □\square

Lemma 3 (the divergence). The value appended with each index at lines L6 and L7 is its entry of dk+1d_{k+1}.

Proof. Take the zero list; the ones are the same with qq in place of pp. Let row rr of aka_k have xak[r][k]=0x_{a_k[r]}[k] = 0.

Case 1: some earlier row has value 0, and r′r' is the last such row. Then ak[r′]a_k[r'] is the neighbor above ak[r]a_k[r] in ak+1a_{k+1}, by Lemma 2. Line L6 set p=0p = 0 after row r′r', and lines L5 at rows r′+1,…,rr' + 1, \ldots, r raised it to max⁡(dk[r′+1],…,dk[r])\max(d_k[r' + 1], \ldots, d_k[r]), since all these values are at least 0. By Lemma 1 this is σk(ak[r′],ak[r])\sigma_k(a_k[r'], a_k[r]). Both haplotypes have 0 at site kk, so the common suffix grows by one site and the start does not change: σk+1=σk\sigma_{k+1} = \sigma_k. This is the correct entry of dk+1d_{k+1}.

Case 2: row rr is the first with value 0. The zero list comes first, so ak[r]a_k[r] is row 0 of ak+1a_{k+1}, whose entry is k+1k + 1 by convention. The value of pp is max⁡(k+1,dk[0],…,dk[r])\max(k + 1, d_k[0], \ldots, d_k[r]), and every dk[t]≤kd_k[t] \le k, so p=k+1p = k + 1.

For the first row of the one list, the row above it in ak+1a_{k+1} is the last row of the zero list. The two differ at site kk, so the correct entry is k+1k + 1. The value of qq is max⁡(k+1,…)=k+1\max(k + 1, \ldots) = k + 1 for the same reason as in Case 2. For later rows of the one list, Case 1 applies. □\square

Theorem 1 (the arrays). build returns aka_k and dkd_k for all k=0,…,Nk = 0, \ldots, N.

Proof. Line L1 gives a0=(0,…,M−1)a_0 = (0, \ldots, M - 1), which sorts the empty prefixes by index, and d0=(0,…,0)d_0 = (0, \ldots, 0), which is correct since every σ0=0\sigma_0 = 0 and d0[0]=0=kd_0[0] = 0 = k. By induction on kk, Lemmas 2 and 3 give ak+1a_{k+1} and dk+1d_{k+1} from aka_k and dkd_k. □\square

Lemma 4 (ranges). For a row rr of aka_k and s≤ks \le k, the rows tt with σk(ak[r],ak[t])≤s\sigma_k(a_k[r], a_k[t]) \le s form a contiguous range of rows that contains rr.

Proof. By Lemma 1, for t>rt > r the condition is max⁡(dk[r+1],…,dk[t])≤s\max(d_k[r + 1], \ldots, d_k[t]) \le s, which holds for t=r+1,…t = r + 1, \ldots up to the first row with dk>sd_k > s and fails beyond it. The same holds for t<rt < r going up. □\square

Theorem 2 (long matches). long_matches returns the pairs i<ji < j and intervals [s,e)[s, e) that are maximal matches with e−s≥Le - s \ge L.

Proof. A maximal match of xix_i and xjx_j on [s,e)[s, e) ends at ee, and at site k=ek = e it is the common suffix of xi[0,k)x_i[0, k) and xj[0,k)x_j[0, k), so s=σk(i,j)s = \sigma_k(i, j), and maximality at the right end means k=Nk = N or xi[k]≠xj[k]x_i[k] \ne x_j[k]. Maximality at the left end holds for s=σk(i,j)s = \sigma_k(i, j) by the definition of σ\sigma. So the maximal matches ending at kk are the pairs with k=Nk = N or xi[k]≠xj[k]x_i[k] \ne x_j[k], with s=σk(i,j)s = \sigma_k(i, j). The code cuts aka_k into blocks at the rows with dk[r]>k−Ld_k[r] > k - L. By Lemma 1, two rows are in the same block exactly when σk≤k−L\sigma_k \le k - L, that is, when the match ending at kk has length at least LL. Within each block the code tests every pair for the right end and computes ss with Lemma 1. Every maximal match has one end ee, so each is found once, at k=ek = e. □\square

Theorem 3 (set-maximal matches). set_maximal_matches returns exactly the set-maximal matches.

Proof. Fix kk and row rr, with i=ak[r]i = a_k[r]. The code sets the sentinels d[0]=d[M]=k+1d[0] = d[M] = k + 1, so the scans stop at the ends. By Lemma 1, the longest common suffix of xi[0,k)x_i[0, k) with any other haplotype has start s∗=min⁡(dk[r],dk[r+1])s^* = \min(d_k[r], d_k[r + 1]), reached by the row above if dk[r]=s∗d_k[r] = s^* and by the row below if dk[r+1]=s∗d_k[r + 1] = s^*. If s∗≥ks^* \ge k, no match of positive length ends at kk for xix_i, and the code skips the row.

A set-maximal match of xix_i that ends at kk must be a longest match of xix_i ending at kk: if a match [s,k)[s, k) of xix_i to xjx_j is maximal but some match of xix_i ending at kk starts before ss, that match covers [s,k)[s, k) and is longer. So it starts at s∗s^*. By Lemma 4, the haplotypes jj with σk(i,j)=s∗\sigma_k(i, j) = s^* are the rows of a contiguous range around rr, and the scans find this range: up while d≤dk[r]=s∗d \le d_k[r] = s^* and down while d≤dk[r+1]=s∗d \le d_k[r + 1] = s^*, each scan done only on the side that reaches s∗s^*.

Now the match [s∗,k)[s^*, k) of xix_i to such a jj is maximal if and only if k=Nk = N or xi[k]≠xj[k]x_i[k] \ne x_j[k]. If some jj in the range has xj[k]=xi[k]x_j[k] = x_i[k], then xix_i has a match to jj on [s∗,k+1)[s^*, k + 1) or longer, which covers [s∗,k)[s^*, k) for every j′j' in the range and is longer, so none of them is set-maximal. The code then reports nothing. If no jj in the range has xj[k]=xi[k]x_j[k] = x_i[k], then each match [s∗,k)[s^*, k) is maximal. No match of xix_i covers [s∗,k)[s^*, k) and is longer: such a match would start at or before s∗s^* and end after kk, or start before s∗s^* and end at kk. The second kind does not exist by the choice of s∗s^*. The first kind would be to some jj with σk(i,j)≤s∗\sigma_k(i, j) \le s^*, so σk(i,j)=s∗\sigma_k(i, j) = s^* and jj is in the range, with xj[k]=xi[k]x_j[k] = x_i[k], which we excluded. So the code reports exactly the set-maximal matches of xix_i ending at kk, and taking all kk and rr gives all of them. □\square

Complexity. Each call of step visits the MM rows once with O(1)O(1) work, so build costs O(NM)O(NM). In set_maximal_matches, each scan step either stops or adds a reported pair, except for at most two steps per row, so the cost is O(NM)O(NM) plus the number of reported pairs. The reference functions sort, compare and test all pairs, and serve only to check these results.

Complexity

  • Building. Each site costs O(M)O(M), so all arrays take O(NM)O(NM) time. Space is O(M)O(M) when streaming and O(NM)O(NM) to keep all arrays.
  • Long matches. O(NM)O(NM) time plus the number of reported pairs.
  • Set-maximal matches. O(NM)O(NM) time plus the output. Durbin shows that the number of set-maximal matches is at most a fixed multiple of NMNM, provided there are no large groups of haplotypes identical over all NN sites, so the total is O(NM)O(NM).
  • Storage. With run-length coding of the columns yky_k, panels of real haplotypes take far less than NMNM bits, since adjacent rows tend to agree.
  • New haplotype. O(N)O(N) time per query with Algorithm 5, given count arrays over the stored columns.

Variants

  • Bidirectional and dynamic PBWT. Later work supports insertion and deletion of haplotypes, and runs the transform in both directions along the genome.
  • Multi-allelic sites and missing data. A site with cc alleles splits the order into cc piles in the same stable pass. Missing values need a rule for where to place the row.
  • Uses in methods. Phasing and imputation programs use the PBWT to pick a small set of haplotypes that match a target well over a region, and then run a Li-Stephens hidden Markov model on that set. Searches for segments shared identical by descent list long matches across large panels.
  • Relation to other transforms. The update is one pass of a stable counting sort by one symbol, the step of LSD radix sort that sorts from the last character. Running it over all sites sorts the reversed prefixes, while the suffix array and the BWT sort the suffixes of one text.

When to use it

Use it when you have many aligned haplotypes over the same sites and need long exact matches between them, or between a new haplotype and the panel, for phasing, imputation, the search for shared segments, or compressed storage. For matches between unaligned sequences, use a suffix array or an FM-index. For approximate matches with errors, the PBWT gives exact matches only, which methods then join or extend.

Pitfalls

  • Exact matches only. One genotype error splits a long match in two. Methods that need tolerance to errors combine matches or use the PBWT only to choose candidates.
  • Divergence convention. dk[r]d_k[r] is a start position, not a length; the length of the match is k−dk[r]k - d_k[r]. Mixing the two conventions is a common bug.
  • The first row and the sentinels. The value k+1k + 1 for the first row of each pile, and the sentinels in Algorithm 4, keep matches from running across the pile boundary or off the ends of the order.
  • Identical haplotypes. Many identical haplotypes make the number of set-maximal matches large, as in Durbin's caveat, and the output can then exceed O(NM)O(NM).
  • Sites must be aligned. All haplotypes must have the same sites in the same order. Indels and different variant sets break the model.

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.

positional_burrows_wheeler_transform.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/positional-burrows-wheeler-transform/. The authors are listed in prov/39NYBT.jsonl.
"""The positional Burrows-Wheeler transform (PBWT) of Durbin (2014).

X is a list of M binary haplotypes, each of length N. For k = 0..N:

  a_k  is the permutation of 0..M-1 that sorts the haplotypes by their
       reversed prefixes x[0..k-1] (read from site k-1 back to site 0),
       with ties broken by index.
  d_k  is the divergence array: d_k[i] is the smallest s such that the
       haplotypes a_k[i] and a_k[i-1] agree on sites s..k-1. d_k[0] = k.

a_{k+1} and d_{k+1} come from a_k, d_k and column k in one stable pass
(Durbin's Algorithm 2), so the whole transform costs O(NM). From the
arrays one can list all long matches (Algorithm 3) and all set-maximal
matches (Algorithm 4).

A match between haplotypes i and j is an interval [s, e) of sites on
which they agree. It is maximal if it cannot be extended to the left or to
the right. For haplotype i, a maximal match [s, e) to j is set-maximal if
no other match of i to any haplotype covers [s, e) and is longer.
"""

from __future__ import annotations

from typing import Sequence


def check_haplotypes(x: Sequence[Sequence[int]]) -> tuple[int, int]:
    m = len(x)
    if m == 0:
        raise ValueError("need at least one haplotype")
    n = len(x[0])
    for h in x:
        if len(h) != n or any(v not in (0, 1) for v in h):
            raise ValueError("haplotypes must be 0/1 rows of equal length")
    return m, n


def step(a: list[int], d: list[int], column: Sequence[int], k: int) -> tuple[list[int], list[int]]:
    """Durbin's Algorithm 2: from (a_k, d_k) and column k, compute (a_{k+1}, d_{k+1})."""
    a0, d0, a1, d1 = [], [], [], []
    p = q = k + 1  # @line L3
    for idx, div in zip(a, d):  # @line L4
        if div > p:  # @line L5
            p = div
        if div > q:
            q = div
        if column[idx] == 0:  # @line L6
            a0.append(idx)
            d0.append(p)
            p = 0
        else:  # @line L7
            a1.append(idx)
            d1.append(q)
            q = 0
    return a0 + a1, d0 + d1  # @line L8


def build(x: Sequence[Sequence[int]]) -> tuple[list[list[int]], list[list[int]]]:
    """All arrays a_0..a_N and d_0..d_N. Keeping them all costs O(NM) space;
    a streaming use keeps only the current pair, in O(M) space."""
    m, n = check_haplotypes(x)
    a = list(range(m))  # @line L1
    d = [0] * m
    arrays_a, arrays_d = [a], [d]
    for k in range(n):  # @line L2
        column = [h[k] for h in x]
        a, d = step(a, d, column, k)
        arrays_a.append(a)
        arrays_d.append(d)
    return arrays_a, arrays_d  # @line L9


def _start(d: list[int], lo: int, hi: int) -> int:
    """Start of the match between positions lo < hi of the sort order: max of d[lo+1..hi]."""
    return max(d[lo + 1:hi + 1])


def long_matches(x: Sequence[Sequence[int]], length: int) -> set[tuple[int, int, int, int]]:
    """All maximal matches of at least `length` sites, as (i, j, s, e) with i < j (Algorithm 3)."""
    if length < 1:
        raise ValueError("length must be at least 1")
    m, n = check_haplotypes(x)
    arrays_a, arrays_d = build(x)
    out = set()
    for k in range(n + 1):
        a, d = arrays_a[k], arrays_d[k]
        block: list[int] = []  # positions in the sort order

        def flush():
            for u in range(len(block)):
                for v in range(u + 1, len(block)):
                    pu, pv = block[u], block[v]
                    i, j = a[pu], a[pv]
                    if k < n and x[i][k] == x[j][k]:
                        continue  # the match goes on past k
                    s = _start(d, pu, pv)
                    if k - s >= length:
                        out.add((min(i, j), max(i, j), s, k))

        for pos in range(m):
            if d[pos] > k - length:
                flush()
                block = []
            block.append(pos)
        flush()
    return out


def set_maximal_matches(x: Sequence[Sequence[int]]) -> set[tuple[int, int, int, int]]:
    """All set-maximal matches, as (i, j, s, e): a match of haplotype i to j on [s, e) (Algorithm 4)."""
    m, n = check_haplotypes(x)
    arrays_a, arrays_d = build(x)
    out = set()
    for k in range(n + 1):
        a = arrays_a[k]
        d = arrays_d[k] + [k + 1]  # sentinel below the last row; d[0] = k already blocks the top
        d[0] = k + 1

        def same(i: int, j: int) -> bool:
            return k < n and x[i][k] == x[j][k]

        for pos in range(m):
            top, bottom = pos - 1, pos + 1
            s = min(d[pos], d[pos + 1])  # start of the longest match ending at k
            if s >= k:
                continue  # no match of positive length ends here
            extends = False
            if d[pos] <= d[pos + 1]:
                while d[top + 1] <= d[pos]:
                    if same(a[top], a[pos]):
                        extends = True
                        break
                    top -= 1
            if not extends and d[pos] >= d[pos + 1]:
                while d[bottom] <= d[pos + 1]:
                    if same(a[bottom], a[pos]):
                        extends = True
                        break
                    bottom += 1
            if extends:
                continue
            i = a[pos]
            for t in range(top + 1, pos):
                out.add((i, a[t], d[pos], k))
            for t in range(pos + 1, bottom):
                out.add((i, a[t], d[pos + 1], k))
    return out


# Reference versions by brute force, for the tests.

def naive_sort(x: Sequence[Sequence[int]], k: int) -> list[int]:
    return sorted(range(len(x)), key=lambda i: (list(reversed(x[i][:k])), i))


def naive_divergence(x: Sequence[Sequence[int]], order: list[int], k: int) -> list[int]:
    out = [k]
    for pos in range(1, len(order)):
        i, j = order[pos], order[pos - 1]
        s = k
        while s > 0 and x[i][s - 1] == x[j][s - 1]:
            s -= 1
        out.append(s)
    return out


def naive_maximal_matches(x: Sequence[Sequence[int]]) -> set[tuple[int, int, int, int]]:
    """All maximal matches of positive length, as (i, j, s, e) with i != j (both orders)."""
    m, n = check_haplotypes(x)
    out = set()
    for i in range(m):
        for j in range(m):
            if i == j:
                continue
            s = 0
            while s < n:
                if x[i][s] != x[j][s]:
                    s += 1
                    continue
                e = s
                while e < n and x[i][e] == x[j][e]:
                    e += 1
                out.add((i, j, s, e))
                s = e
    return out


def naive_set_maximal(x: Sequence[Sequence[int]]) -> set[tuple[int, int, int, int]]:
    matches = naive_maximal_matches(x)
    by_i: dict[int, list[tuple[int, int, int]]] = {}
    for i, j, s, e in matches:
        by_i.setdefault(i, []).append((j, s, e))
    out = set()
    for i, lst in by_i.items():
        for j, s, e in lst:
            covered = any(s2 <= s and e <= e2 and e2 - s2 > e - s for _, s2, e2 in lst)
            if not covered:
                out.add((i, j, s, e))
    return out
test_positional_burrows_wheeler_transform.py 117 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/positional-burrows-wheeler-transform/. The authors are listed in prov/39NYBT.jsonl.

import random

import pytest

from positional_burrows_wheeler_transform import (build, long_matches, naive_divergence, naive_maximal_matches,
                                                  naive_set_maximal, naive_sort, set_maximal_matches, step)

EXAMPLE = [
    [0, 1, 0, 1, 0, 1],
    [1, 1, 0, 0, 0, 1],
    [1, 1, 1, 1, 1, 1],
    [0, 1, 1, 1, 1, 0],
    [0, 0, 0, 0, 0, 0],
    [1, 0, 0, 0, 1, 0],
    [1, 1, 0, 0, 0, 1],
    [0, 1, 0, 1, 1, 0],
]


def random_haplotypes(rng, m, n, p=0.4):
    """Haplotypes copied in pieces from a few founders, with some mutation, so that long matches occur."""
    founders = [[int(rng.random() < p) for _ in range(n)] for _ in range(3)]
    out = []
    for _ in range(m):
        src = rng.randrange(3)
        h = []
        for k in range(n):
            if rng.random() < 0.15:
                src = rng.randrange(3)
            v = founders[src][k]
            if rng.random() < 0.05:
                v = 1 - v
            h.append(v)
        out.append(h)
    return out


def test_example_arrays():
    a, d = build(EXAMPLE)
    for k in range(7):
        assert a[k] == naive_sort(EXAMPLE, k)
        assert d[k] == naive_divergence(EXAMPLE, a[k], k)
    # Haplotypes 1 and 6 are identical, so they end next to each other with divergence 0.
    pos = a[6].index(1)
    assert a[6][pos + 1] == 6 and d[6][pos + 1] == 0


def test_one_step_by_hand():
    a, d = step([0, 1, 2, 3], [0, 0, 0, 0], [1, 0, 1, 0], 0)
    assert a == [1, 3, 0, 2]
    assert d == [1, 0, 1, 0]


def test_arrays_against_naive_sort():
    rng = random.Random(1)
    for _ in range(30):
        m, n = rng.randint(1, 12), rng.randint(0, 15)
        x = random_haplotypes(rng, m, n)
        a, d = build(x)
        assert len(a) == n + 1
        for k in range(n + 1):
            assert a[k] == naive_sort(x, k)
            assert d[k] == naive_divergence(x, a[k], k)


def test_set_maximal_against_brute_force():
    rng = random.Random(2)
    assert set_maximal_matches(EXAMPLE) == naive_set_maximal(EXAMPLE)
    for _ in range(60):
        m, n = rng.randint(2, 10), rng.randint(1, 14)
        x = random_haplotypes(rng, m, n)
        assert set_maximal_matches(x) == naive_set_maximal(x)


def test_long_matches_against_brute_force():
    rng = random.Random(3)
    for _ in range(40):
        m, n = rng.randint(2, 10), rng.randint(1, 14)
        x = random_haplotypes(rng, m, n)
        all_max = naive_maximal_matches(x)
        for length in (1, 2, 4, 7):
            want = {(i, j, s, e) for i, j, s, e in all_max if i < j and e - s >= length}
            assert long_matches(x, length) == want


def test_set_maximal_are_maximal_and_cover_each_haplotype():
    rng = random.Random(4)
    x = random_haplotypes(rng, 12, 40)
    sm = set_maximal_matches(x)
    maximal = naive_maximal_matches(x)
    assert sm <= maximal
    # Every haplotype has a set-maximal match that covers each site where it matches anyone.
    for i in range(12):
        mine = [(s, e) for a, _, s, e in sm if a == i]
        for k in range(40):
            if any(x[i][k] == x[j][k] for j in range(12) if j != i):
                assert any(s <= k < e for s, e in mine)


def test_identical_haplotypes():
    x = [[0, 1, 1], [0, 1, 1], [1, 0, 0]]
    assert set_maximal_matches(x) == {(0, 1, 0, 3), (1, 0, 0, 3)}
    assert long_matches(x, 3) == {(0, 1, 0, 3)}


def test_bad_input():
    with pytest.raises(ValueError):
        build([])
    with pytest.raises(ValueError):
        build([[0, 1], [1]])
    with pytest.raises(ValueError):
        build([[0, 2]])
    with pytest.raises(ValueError):
        long_matches([[0, 1]], 0)

History

Burrows and Wheeler (1994) sorted the rotations of a string for compression, and the FM-index of Ferragina and Manzini made the result searchable. Durbin (2014) adapted the idea to a panel of aligned haplotypes: instead of sorting the suffixes of one text, sort all haplotypes by their reversed prefixes at each site. The paper gave the algorithms for the prefix and divergence arrays, the reports of long and set-maximal matches, the matching of a new sequence, and a compressed storage of large haplotype panels. The PBWT then became a part of several phasing, imputation and shared-segment programs.

References

  1. Richard Durbin, Efficient haplotype matching and storage using the positional Burrows-Wheeler transform (PBWT), Bioinformatics 30(9), 2014, pp. 1266-1272 (Algorithms 1 and 2 for the prefix and divergence arrays, Algorithm 3 for long matches, Algorithm 4 for set-maximal matches, Algorithm 5 for matches of a new sequence, and the bound on the number of set-maximal matches)
  2. Burrows and Wheeler 1994, the transform that sorts the rotations of one string, which the PBWT adapts to many aligned strings

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.build
  • a full proof of time.long-matches
  • a full proof of time.set-maximal-matches
  • a full proof of space.all-arrays
  • a full proof of space.streaming
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