Algorithm Search⌘K

Algorithmadvanced

Maximal mappable prefix alignment

Also called STAR alignment algorithm.

Align an RNA-seq read by finding, with a suffix array, its longest prefix that occurs in the genome, repeating on the rest of the read, and stitching the seeds across introns.

Time
O(L^2·log n + L·D^2) worst
Space
O(L·D) extra
Where
D = the number of seed diagonals; L = the read length; n = the genome length
Properties
deterministicnot exactonlineiterative
Origin
Alexander Dobin, Carrie A. Davis, Felix Schlesinger, Jorg Drenkow, Chris Zaleski, Sonali Jha, Philippe Batut, Mark Chaisson, Thomas R. Gingeras, 2013

Maximal mappable prefix alignment is the seed search of the STAR aligner of Dobin and colleagues (2013) for spliced read alignment. From the start of a read, it finds the maximal mappable prefix (MMP): the longest prefix of the read that occurs exactly somewhere in the genome. It finds it by binary search in a suffix array of the genome. If the read crosses a splice junction, the MMP stops at the end of the exon or a few bases after it, so the search starts again on the rest of the read and finds the next exon. A mismatch also stops the MMP, and the search goes on after it. Then a dynamic program stitches the seeds into one alignment with introns, mismatches and soft-clipped ends. No list of known junctions is needed. The method is a heuristic: it finds exact unspliced reads with certainty, but a spliced read with a very short overhang into an exon is often soft-clipped instead.

In plain words

Sort every suffix of the genome, so that any piece of text can be looked up like a word in a dictionary.

To place a read, look up the read. The dictionary tells you how far the read matches before it stops fitting anywhere. If the read came from two exons glued together, the match stops near the place where the first exon ends. Note where the match is, skip one letter, and look up the rest of the read in the same way. The rest fits at the start of the next exon, further along the genome.

At the end, put the pieces together. Choose the cut point between them so that the gap starts and ends with the letters that real introns usually have, and count the matches and the differences.

The problem

The input is a genome GG of length nn with its suffix array, and a read RR of length LL from an RNA molecule. The task is a spliced alignment: blocks of the read aligned to the genome in order, with long gaps in the genome between them for the introns, as on the spliced read alignment page. The output is a position and a CIGAR string with M, N and S operations, as in the SAM format, or unmapped.

The algorithm reduces the task to exact matching. The diagonal of a match is its genome position minus its read position. An alignment with mismatches and introns stays on one diagonal inside each block, and moves to a larger diagonal at each intron. So if the seeds give the right diagonals, the stitching only has to choose where to change diagonal.

The algorithm

Positions are 1-based in the text and 0-based in the code.

  1. MMP-ALIGN(read R of length L, genome G with suffix array SA, seed length s_min, place limit n_max, fraction τ)
  2. 1Δ ← an empty set of diagonals; i ← 1
  3. 2while i ≤ L do
  4. 3(ℓ, P) ← the length of the longest prefix of R[i..L] that occurs in G, and the set of its positions, by binary search in SA
  5. 4if ℓ ≥ s_min and |P| ≤ n_max then add p - i to Δ for each p in P
  6. 5i ← i + ℓ + 1
  7. 6A ← STITCH(R, G, Δ), the best alignment that puts each read base on a diagonal of Δ
  8. 7if A exists and score(A) ≥ τ·L then return A
  9. 8return unmapped

Line L3 is the MMP search. The suffixes that share the longest prefix with R[i..L]R[i..L] are next to the place where R[i..L]R[i..L] would be inserted in the sorted order, so one binary search and two comparisons give ℓ\ell, and two more binary searches give the block of the suffix array whose suffixes start with this prefix, that is, all its places. Line L4 keeps a seed only if it is long enough to be meaningful and maps to few places; STAR also limits the number of places of its anchors. Line L5 skips the base after the MMP, which is a mismatch, or the first base after the end of the match on the next exon. The stitching realigns this base.

STITCH is a dynamic program over the read positions xx and the diagonals dd of Δ\Delta. The value F(x,d)F(x, d) is the best score of an alignment that ends with base xx on dd. It adds +1+1 for a match or −1-1 for a mismatch to the best of three cases: start here (soft-clip all bases before), stay on dd from base x−1x - 1, or come from a smaller diagonal d′d' with d−d′d - d' between the minimum and maximum intron length, minus the intron penalty. The penalty is 2 if the intron starts with GT and ends with AG (or CT and AC, the same motif on the other strand), and 8 otherwise. The best cell over all xx and dd gives the end, the bases after it are soft-clipped, and the back pointers give the CIGAR.

The code chooses these scores; STAR has its own scoring options, which the paper does not list. The code leaves out the search from the read end in the reverse direction, the extra start points, the clustering of seeds into windows around anchors, insertions and deletions in the stitching, the reverse strand of the read, read pairs, chimeric reads and the report of several alignments. The code builds the suffix array by sorting the suffixes, which is simple but slow; see suffix array construction.

Example

The genome has 42 bases: CCCT, an exon CGATTCAAAT at positions 5 to 14, an intron GTGGCCGGGAGTAG at 15 to 28, an exon GACGGCAGCA at 29 to 38, and GAGA. The read is R=ATTCAAATGACGGCAGR = \texttt{ATTCAAATGACGGCAG}: the last 8 bases of the first exon and the first 8 of the second. Use smin⁡=5s_{\min} = 5, nmax⁡=10n_{\max} = 10, introns of 10 to 1000 bases and τ=0.66\tau = 0.66.

step start ii MMP ℓ\ell places diagonal
1 1 ATTCAAATG 9 7 6
2 11 CGGCAG 6 31 20

The first MMP runs one base past the exon: the G at read position 9 also matches the G of the intron start GT. Line L5 then skips read position 10, and the second MMP is the rest of the read, at genome position 31 in the second exon. The search ends, and Δ={6,20}\Delta = \{6, 20\}, which differ by the intron length 14.

The stitching has two cut points with 16 matches. A cut after read base 8 makes the intron positions 15 to 28, GTGGCCGGGAGTAG, with the motif GT and AG, so the score is 16−2=1416 - 2 = 14. A cut after base 9 makes the intron positions 16 to 29, TGGCCGGGAGTAGG, with the motif TG and GG, so the score is 16−8=816 - 8 = 8. Other cut points have a mismatch and a non-canonical motif. The result is position 7 with the CIGAR 8M14N8M and the score 14, which is at least 0.66⋅160.66 \cdot 16. With only the first seed, the best alignment would be 9M7S with the score 9: the read could not cross the intron. The test file checks all of this, with the 0-based positions 6 and 30.

Correctness

The proof shows four theorems. The MMP search returns the true maximal mappable prefix and all its places, because the longest common prefix with a string is reached at its neighbors in the sorted order and the suffixes with a given prefix form one block. The stitching is optimal among all alignments whose bases lie on the diagonals of Δ\Delta, by the usual induction over the read positions. A read that occurs once in the genome with no error is returned with the full score, its position and the CIGAR LLM. And an exact read across one intron gets a score at least LL minus the intron penalty, if the first MMP lies on the true first diagonal and both seeds are at least smin⁡s_{\min} long and map to few enough places. That the result is then the true alignment is not a theorem: the junction can often move by a base with the same matches, and the motif penalty decides.

Proof: The suffix array search returns the maximal mappable prefix with all its places, the stitching is optimal over the seed diagonals, and exact reads are foundfull

We use the pseudocode of the page and the code. The genome is GG of length nn and the read is RR of length LL. Positions here are 0-based, as in the code. For a string ss, the maximal mappable prefix is the longest prefix s[0..ℓ−1]s[0..\ell - 1] that occurs in GG, with ℓ=0\ell = 0 if no letter of ss occurs. A diagonal dd aligns read base xx to genome base x+dx + d. The scores are +1+1 for a match and −1-1 for a mismatch, and an intron costs a penalty π>0\pi > 0 that depends on its first two and last two bases.

The suffix array SASA lists the starts of the suffixes of GG in lexicographic order. Write Tj=G[SA[j]..n−1]T_j = G[SA[j]..n - 1] and lcp(a,b)\mathrm{lcp}(a, b) for the length of the longest common prefix.

Lemma 1. For strings A≤B≤CA \le B \le C, lcp(A,C)=min⁡(lcp(A,B),lcp(B,C))\mathrm{lcp}(A, C) = \min(\mathrm{lcp}(A, B), \mathrm{lcp}(B, C)).

Proof. Let m=min⁡(lcp(A,B),lcp(B,C))m = \min(\mathrm{lcp}(A, B), \mathrm{lcp}(B, C)). All three agree on the first mm letters, so lcp(A,C)≥m\mathrm{lcp}(A, C) \ge m. Suppose lcp(A,C)>m\mathrm{lcp}(A, C) > m, and say m=lcp(A,B)m = \mathrm{lcp}(A, B) (the other case is the same with the roles of AA and CC swapped). Then AA and CC agree at position mm, and BB differs from AA there or ends there. If BB ends at mm, then BB is a proper prefix of AA and B<AB < A, against A≤BA \le B. If B[m]<A[m]=C[m]B[m] < A[m] = C[m] then B<AB < A, and if B[m]>A[m]=C[m]B[m] > A[m] = C[m] then B>CB > C. Both contradict the order. □\square

Lemma 2. Let pp be the first index with Tp≥sT_p \ge s (in the order where a string is compared with ss cut to the length of ss). Then max⁡jlcp(s,Tj)\max_j \mathrm{lcp}(s, T_j) is attained at j=p−1j = p - 1 or j=pj = p.

Proof. For j<p−1j < p - 1 we have Tj≤Tp−1<sT_j \le T_{p-1} < s, so by Lemma 1, lcp(Tj,s)≤lcp(Tp−1,s)\mathrm{lcp}(T_j, s) \le \mathrm{lcp}(T_{p-1}, s). For j>pj > p we have s≤Tp≤Tjs \le T_p \le T_j, so in the same way lcp(s,Tj)≤lcp(s,Tp)\mathrm{lcp}(s, T_j) \le \mathrm{lcp}(s, T_p). Comparing TjT_j cut to ∣s∣|s| with ss gives the same order as comparing TjT_j with ss, except that a TjT_j that has ss as a prefix counts as equal, which is also ≥s\ge s. So the lemma holds for the order that the code uses. □\square

Theorem 1 (seed search). MMP returns the length ℓ\ell of the maximal mappable prefix of ss and the sorted list of all positions where s[0..ℓ−1]s[0..\ell - 1] occurs in GG.

Proof. A prefix of ss of length mm occurs in GG if and only if some suffix TjT_j has lcp(s,Tj)≥m\mathrm{lcp}(s, T_j) \ge m. So ℓ=max⁡jlcp(s,Tj)\ell = \max_j \mathrm{lcp}(s, T_j), which the code computes at the two neighbors of Lemma 2. The suffixes that start with P=s[0..ℓ−1]P = s[0..\ell - 1] form one contiguous block of SASA, since they are exactly those with TjT_j cut to ℓ\ell equal to PP, and the cut suffixes are sorted. The two binary searches find the first index with cut suffix ≥P\ge P and the first with cut suffix >P> P, which are the ends of this block. □\square

2. The stitching

Let Δ\Delta be a finite set of diagonals. An alignment over Δ\Delta chooses a read interval [s,e][s, e], soft-clips the rest, and gives each x∈[s,e]x \in [s, e] a diagonal dx∈Δd_x \in \Delta with 0≤x+dx<n0 \le x + d_x < n, such that for each x<ex < e either dx+1=dxd_{x+1} = d_x, or dx+1−dx∈[min_intron,max_intron]d_{x+1} - d_x \in [\mathrm{min\_intron}, \mathrm{max\_intron}], which is an intron from G[x+1+dx]G[x + 1 + d_x] to G[x+dx+1]G[x + d_{x+1}]. Its score is the sum of the base scores minus the penalties of its introns.

Theorem 2 (stitching is optimal). STITCH returns an alignment over Δ\Delta of the best score, and its CIGAR, read from left to right, spells exactly this alignment. If no alignment over Δ\Delta has a positive score, it returns nothing.

Proof. Let F(x,d)F(x, d) be the best score of an alignment over Δ\Delta whose last base is xx on diagonal dd. The last step of such an alignment is one of three cases: xx is also its first base, the base x−1x - 1 is on dd as well, or the base x−1x - 1 is on an allowed d′d' with an intron in between. So

F(x,d)=σ(x,d)+max⁡(0, F(x−1,d), max⁡d′F(x−1,d′)−π(x,d′,d)),F(x, d) = \sigma(x, d) + \max\bigl(0,\ F(x - 1, d),\ \max_{d'} F(x - 1, d') - \pi(x, d', d)\bigr),

where the inner maximum runs over the d′d' in Δ\Delta with d−d′d - d' in the intron range and a defined F(x−1,d′)F(x - 1, d'). This is the recurrence of the code, by induction on xx; the value 0 stands for starting a new alignment at xx. Every alignment ends at some (x,d)(x, d), so the best of all F(x,d)F(x, d) is the best score. The back pointers record which case gave each value, so following them from the best cell spells an alignment with that score. The CIGAR starts with the soft-clip of the bases before the start, gives one M block per run of equal diagonals, an N block of length dx+1−dxd_{x+1} - d_x between runs, and a final soft-clip, so it spells the same alignment. The code returns nothing when the best value is at most 0. □\square

Each base adds at most +1+1 and each intron subtracts π>0\pi > 0, so every alignment has score at most LL, with equality only if every base is aligned, matches, and there is no intron.

3. Exact reads

Theorem 3 (an exact unspliced read). Suppose RR occurs in GG at exactly one position pp, L≥smin⁡L \ge s_{\min}, nmax⁡≥1n_{\max} \ge 1 and min_frac≤1\mathrm{min\_frac} \le 1. Then the algorithm returns the score LL, the position pp and the CIGAR LLM.

Proof. By Theorem 1, the first search gives ℓ=L\ell = L and the places {p}\{p\}, so line L4 adds the diagonal pp, and line L5 moves past the end of the read. So Δ={p}\Delta = \{p\}. The alignment of all of RR on pp scores LL, the most possible, and by the remark after Theorem 2 any alignment of score LL over Δ\Delta is this one. In the code, F(x,p)=x+1F(x, p) = x + 1 grows strictly, so the best cell is the last base, and each back pointer goes to the base before, because F(x−1,p)=x>0F(x - 1, p) = x > 0. So the code returns this alignment, and line L7 accepts it since L≥min_frac⋅LL \ge \mathrm{min\_frac} \cdot L. □\square

Theorem 4 (an exact read across one intron). Suppose R[0..j−1]R[0..j - 1] matches GG on the diagonal d1d_1 and R[j..L−1]R[j..L - 1] matches on d2d_2, with d2−d1d_2 - d_1 in the intron range and penalty π\pi for this intron. Let ℓ\ell be the length of the maximal mappable prefix of RR. Suppose G[d1..d1+ℓ−1]=R[0..ℓ−1]G[d_1 .. d_1 + \ell - 1] = R[0..\ell - 1], ℓ≥smin⁡\ell \ge s_{\min}, L−ℓ−1≥smin⁡L - \ell - 1 \ge s_{\min}, and the first two searches find at most nmax⁡n_{\max} places each. Then the returned alignment has score at least L−πL - \pi.

Proof. The first search gives ℓ≥j\ell \ge j, because R[0..j−1]R[0..j - 1] occurs at d1d_1. Its places hold d1d_1 by the assumption, so d1∈Δd_1 \in \Delta. The second search starts at ℓ+1>j\ell + 1 > j, and R[ℓ+1..L−1]R[\ell + 1..L - 1] occurs in GG on d2d_2, so its maximal mappable prefix is all of it, of length L−ℓ−1≥smin⁡L - \ell - 1 \ge s_{\min}, with the place on d2d_2 among its places. So d2∈Δd_2 \in \Delta. The true alignment, jj bases on d1d_1 and then the rest on d2d_2, is an alignment over Δ\Delta of score L−πL - \pi, and by Theorem 2 the result scores at least this. □\square

4. What is not proved

Theorem 4 does not say that the result is the true alignment. Another alignment over Δ\Delta can have the same score: for example the junction can often move by a base when the end of one exon equals the end of the intron, and then the penalty of the motif decides. The conditions of Theorem 4 can also fail. When one side of the junction has fewer than about smin⁡s_{\min} bases, the second seed is not found and the short end is soft-clipped, and when the first MMP runs past the junction on another place than d1d_1, the diagonal d1d_1 is missing. How often reads are still placed exactly is a measurement, which the tests make. ■\blacksquare

Complexity

The word RAM, with read length LL, genome length nn and DD diagonals in Δ\Delta.

  • Seed search. Each MMP search is a few binary searches of O(log⁡n)O(\log n) steps, each step a comparison of up to LL letters, so O(Llog⁡n)O(L \log n). There are at most LL searches, and usually only one per block, because each search moves ii past its match. The worst case is O(L2log⁡n)O(L^2 \log n).
  • Stitching. L⋅DL \cdot D cells, each looking at up to DD diagonals, so O(LD2)O(L D^2) time and O(LD)O(L D) space. DD is at most nmax⁡n_{\max} times the number of seeds.
  • Index. The suffix array has nn entries and can be built in O(nlog⁡n)O(n \log n) time or faster. STAR keeps it uncompressed, which makes the search fast and the memory large: the paper reports about 27 GB of RAM for the human genome, and less than 16 GB with a sparse suffix array, at a cost in speed. It reports about 550 million paired-end reads of 2 × 76 bases per hour on 12 threads. These are measurements.

Properties

  • No junction database. The seeds find new junctions as easily as known ones.
  • Heuristic. Exact unspliced reads are found with certainty, and exact reads across one junction under the conditions of Theorem 4. Short overhangs and repeats can make it miss the true alignment.
  • Exact matching first. All the work with mismatches and introns happens on the few diagonals that the seeds give, which is what makes the method fast.
  • Deterministic and online. Each read is handled alone, so reads run in parallel.

Variants and improvements

  • Search in both directions. STAR runs the MMP search in both the forward and the reverse direction of the read, which gives a second set of seeds when the forward search misses a block.
  • Extra start points. The search can start at points spread over the read, so that one error does not hide a whole block.
  • Windows around anchors. STAR clusters the seeds into windows around anchors that map to few places; the window size sets the largest intron. Seeds of the two mates of a pair are stitched together, and a read that needs two windows is reported as chimeric.
  • Multimappers. STAR reports all alignments whose score is within a set range below the best one.
  • Compressed indexes. HISAT replaces the uncompressed suffix array with an FM-index and small local indexes, which uses much less memory; see spliced read alignment.
  • Reads to transcripts. For quantification only, selective alignment or pseudoalignment to a transcriptome avoids the genome and the introns.

When to use it

Use it to align short RNA-seq reads to a genome when splice junctions must be found, including new ones, and when memory is available: an index of tens of gigabytes for a mammalian genome. When memory is short, an aligner with an FM-index is the better choice. For long reads with many errors, exact seeds of maximal length are too rare, and chaining of minimizers, as in minimap2, works better. For counts of known transcripts alone, a mapping to the transcriptome is faster.

Pitfalls

  • Short overhangs. When a read crosses a junction with only a few bases on one side, the second MMP is shorter than smin⁡s_{\min} and is dropped, and the short end is soft-clipped. In the tests, every read whose blocks all had at least 12 bases was placed exactly (183 of 183), but only 16 of 57 reads with a shorter block were, a measurement. A search from the other end of the read can find the short block from its other side.
  • Overshoot at the junction. The MMP often runs a few bases past the end of the exon, because the start of the intron can match the start of the next exon by chance. The stitching must be free to move the cut point back, as in the example.
  • The junction is ambiguous. When the end of an exon equals the end of the intron, several cut points have the same matches, and only the motif penalty chooses. Two non-canonical cut points with the same score are a tie, and the result depends on the order of the search.
  • Repeats. An MMP in a repeat has many places. If it has more than nmax⁡n_{\max}, it gives no diagonal, and a read made mostly of repeats can be unmapped.
  • Memory. The uncompressed suffix array of a large genome needs much RAM, as the measurements above show.

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.

maximal_mappable_prefix_alignment.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/maximal-mappable-prefix-alignment/. The authors are listed in prov/YWMA4M.jsonl.

"""Spliced alignment of a read to a genome by maximal mappable prefixes, in the style of STAR.

Seed search: from read position i, the maximal mappable prefix (MMP) is the
longest prefix of read[i:] that occurs in the genome. It is found by binary
search in the suffix array, with all its genome positions. Seeds that are long
enough and map to few enough places give candidate diagonals (genome position
minus read position). The search goes on from the base after the MMP.

Stitching: a dynamic program over read positions and the candidate diagonals
finds the best alignment in which each read base sits on one diagonal, the
diagonal can jump forward by an intron length, and both ends can be
soft-clipped. Matches score +1, mismatches -1, and an intron costs 2 if its
motif is GT-AG or CT-AC and 8 otherwise.

What this leaves out, compared with STAR: the search in the reverse direction
and from extra start points, the pre-index of L-mers, the clustering of seeds
into windows around anchors, insertions and deletions, the reverse strand of
the read, read pairs, chimeric alignments, the annotated junctions and the
report of several alignments. The scores are choices of this code, not the
defaults of STAR. Positions are 0-based.
"""

from __future__ import annotations

from typing import Iterable, List, NamedTuple, Optional, Sequence, Tuple

MATCH, MISMATCH = 1, -1
CANONICAL_PENALTY, NONCANONICAL_PENALTY = 2, 8
CANONICAL = {("GT", "AG"), ("CT", "AC")}


class Alignment(NamedTuple):
    score: int
    pos: int
    cigar: str


def suffix_array(g: str) -> List[int]:
    """The start positions of the suffixes of g in lexicographic order (a simple O(n^2 log n) build)."""
    return sorted(range(len(g)), key=lambda i: g[i:])


def _lcp(a: str, b: str) -> int:
    n = min(len(a), len(b))
    i = 0
    while i < n and a[i] == b[i]:
        i += 1
    return i


def _lower(g: str, sa: Sequence[int], p: str, strict: bool) -> int:
    """First index of sa whose suffix, cut to len(p), is >= p (or > p if strict)."""
    lo, hi = 0, len(sa)
    m = len(p)
    while lo < hi:
        mid = (lo + hi) // 2
        s = g[sa[mid]:sa[mid] + m]
        if s < p or (strict and s == p):
            lo = mid + 1
        else:
            hi = mid
    return lo


def mmp(g: str, sa: Sequence[int], s: str) -> Tuple[int, List[int]]:
    """Return (l, positions): the longest prefix of s that occurs in g, and all its start positions in g."""
    pos = _lower(g, sa, s, False)
    best = 0
    for j in (pos - 1, pos):
        if 0 <= j < len(sa):
            best = max(best, _lcp(s, g[sa[j]:sa[j] + len(s)]))
    if best == 0:
        return 0, []
    p = s[:best]
    return best, sorted(sa[_lower(g, sa, p, False):_lower(g, sa, p, True)])


def junction_penalty(g: str, start: int, end: int) -> int:
    """The cost of the intron g[start:end], by its first two and last two bases."""
    if (g[start:start + 2], g[end - 2:end]) in CANONICAL:
        return CANONICAL_PENALTY
    return NONCANONICAL_PENALTY


def stitch(read: str, g: str, diagonals: Iterable[int], min_intron: int = 20,
           max_intron: int = 1000) -> Optional[Alignment]:
    """The best alignment of a substring of read that puts each base on one of the diagonals.

    Read base x on diagonal d is aligned to g[x + d]. From one base to the next the
    diagonal stays the same, or grows by an intron length in [min_intron, max_intron].
    Bases before the start and after the end are soft-clipped.
    """
    D = sorted(set(diagonals))
    L, n = len(read), len(g)
    F: List[List[Optional[int]]] = [[None] * len(D) for _ in range(L)]
    back: List[List[Optional[int]]] = [[None] * len(D) for _ in range(L)]
    best: Optional[Tuple[int, int, int]] = None
    for x in range(L):
        for a, d in enumerate(D):
            if not 0 <= x + d < n:
                continue
            here, from_ = 0, None
            if x > 0:
                for b, e in enumerate(D):
                    prev = F[x - 1][b]
                    if prev is None:
                        continue
                    if b == a:
                        v = prev
                    elif min_intron <= d - e <= max_intron:
                        v = prev - junction_penalty(g, x + e, x + d)
                    else:
                        continue
                    if v > here:
                        here, from_ = v, b
            F[x][a] = here + (MATCH if read[x] == g[x + d] else MISMATCH)
            back[x][a] = from_
            if best is None or F[x][a] > best[0]:
                best = (F[x][a], x, a)
    if best is None or best[0] <= 0:
        return None
    score, x, a = best
    end = x
    path = []
    while True:
        path.append(D[a])
        b = back[x][a]
        if b is None:
            break
        x, a = x - 1, b
    start = x
    path.reverse()
    ops = [f"{start}S"] if start else []
    run = 1
    for prev, cur in zip(path, path[1:]):
        if cur == prev:
            run += 1
        else:
            ops += [f"{run}M", f"{cur - prev}N"]
            run = 1
    ops.append(f"{run}M")
    if end < L - 1:
        ops.append(f"{L - 1 - end}S")
    return Alignment(score, start + path[0], "".join(ops))


def mmp_align(read: str, g: str, sa: Sequence[int], s_min: int = 8, n_max: int = 10,
              min_intron: int = 20, max_intron: int = 1000, min_frac: float = 0.66,
              trace: Optional[list] = None) -> Optional[Alignment]:
    """Align read to g: seeds by maximal mappable prefixes, then stitching. None if unmapped."""
    L = len(read)
    diagonals = set()  # @line L1
    i = 0
    while i < L:  # @line L2
        l, places = mmp(g, sa, read[i:])  # @line L3
        if trace is not None:
            trace.append((i, l, len(places)))
        if l >= s_min and len(places) <= n_max:  # @line L4
            diagonals.update(p - i for p in places)
        i += l + 1  # @line L5
    aln = stitch(read, g, diagonals, min_intron, max_intron)  # @line L6
    if aln is not None and aln.score >= min_frac * L:  # @line L7
        return aln
    return None  # @line L8
test_maximal_mappable_prefix_alignment.py 197 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/maximal-mappable-prefix-alignment/. The authors are listed in prov/YWMA4M.jsonl.

import random
import re
from itertools import product

from maximal_mappable_prefix_alignment import (MATCH, MISMATCH, Alignment, junction_penalty, mmp,
                                               mmp_align, stitch, suffix_array)

G = "CCCT" + "CGATTCAAAT" + "GTGGCCGGGAGTAG" + "GACGGCAGCA" + "GAGA"


def dna(rng, n, alphabet="ACGT"):
    return "".join(rng.choice(alphabet) for _ in range(n))


def occurrences(g, p):
    return [i for i in range(len(g) - len(p) + 1) if g.startswith(p, i)]


def cigar_score(read, g, pos, cigar):
    """Score an alignment from its CIGAR, and check that it uses the whole read."""
    x, y, score, last_m = 0, pos, 0, None
    for n, op in re.findall(r"(\d+)([MNS])", cigar):
        n = int(n)
        if op == "S":
            x += n
        elif op == "M":
            score += sum(MATCH if read[x + j] == g[y + j] else MISMATCH for j in range(n))
            x, y = x + n, y + n
        else:
            score -= junction_penalty(g, y, y + n)
            y += n
    assert x == len(read)
    return score


def test_worked_example():
    read = "ATTCAAAT" + "GACGGCAG"
    sa = suffix_array(G)
    trace = []
    aln = mmp_align(read, G, sa, s_min=5, min_intron=10, trace=trace)
    assert trace == [(0, 9, 1), (10, 6, 1)]
    assert mmp(G, sa, read) == (9, [6])
    assert mmp(G, sa, read[10:]) == (6, [30])
    assert aln == Alignment(14, 6, "8M14N8M")
    # The other place for the junction, one base later, also has 16 matches but a TG-GG motif.
    assert G[14:28].startswith("GT") and G[14:28].endswith("AG")
    assert junction_penalty(G, 15, 29) == 8
    assert cigar_score(read, G, 6, "9M14N7M") == 8
    # Without the second seed the read cannot cross the intron and is soft-clipped.
    assert stitch(read, G, [6], 10) == Alignment(9, 6, "9M7S")


def test_mmp_against_brute_force():
    rng = random.Random(1)
    for _ in range(400):
        g = dna(rng, rng.randint(1, 60), rng.choice(["AC", "ACGT"]))
        s = dna(rng, rng.randint(1, 15), "ACGT")
        sa = suffix_array(g)
        l = max((m for m in range(len(s) + 1) if s[:m] in g), default=0)
        want = (l, occurrences(g, s[:l])) if l else (0, [])
        assert mmp(g, sa, s) == want


def brute_stitch(read, g, D, lo, hi):
    best = None
    L = len(read)
    for s in range(L):
        for e in range(s, L):
            for ds in product(D, repeat=e - s + 1):
                if any(not 0 <= s + j + d < len(g) for j, d in enumerate(ds)):
                    continue
                sc, ok = 0, True
                for j, d in enumerate(ds):
                    x = s + j
                    sc += MATCH if read[x] == g[x + d] else MISMATCH
                    if j and d != ds[j - 1]:
                        if not lo <= d - ds[j - 1] <= hi:
                            ok = False
                            break
                        sc -= junction_penalty(g, x + ds[j - 1], x + d)
                if ok and (best is None or sc > best):
                    best = sc
    return best


def test_stitch_against_brute_force():
    rng = random.Random(2)
    for _ in range(80):
        g = dna(rng, 30, rng.choice(["ACGT", "AGT"]))
        read = dna(rng, rng.randint(1, 6), "AGT")
        D = sorted(rng.sample(range(-3, 25), rng.randint(1, 3)))
        want = brute_stitch(read, g, D, 3, 15)
        got = stitch(read, g, D, 3, 15)
        if want is None or want <= 0:
            assert got is None
        else:
            assert got.score == want
            assert cigar_score(read, g, got.pos, got.cigar) == want


def gene(rng, n_exons):
    """A genome with one gene: the genome, the exon intervals and the transcript."""
    parts, exons, pos = [dna(rng, 200)], [], 200
    for e in range(n_exons):
        ex = dna(rng, rng.randint(60, 120))
        exons.append((pos, pos + len(ex)))
        parts.append(ex)
        pos += len(ex)
        if e < n_exons - 1:
            intron = "GT" + dna(rng, rng.randint(50, 300)) + "AG"
            parts.append(intron)
            pos += len(intron)
    parts.append(dna(rng, 200))
    g = "".join(parts)
    return g, exons, "".join(g[a:b] for a, b in exons)


def truth(exons, start, L):
    """The genome position and CIGAR of the transcript substring [start, start + L)."""
    ops, t, pos, prev_end = [], 0, None, None
    for a, b in exons:
        lo = max(start, t)
        hi = min(start + L, t + b - a)
        if lo < hi:
            g0 = a + lo - t
            if pos is None:
                pos = g0
            else:
                ops.append(f"{g0 - prev_end}N")
            ops.append(f"{hi - lo}M")
            prev_end = a + hi - t
        t += b - a
    return pos, "".join(ops)


def test_exact_unspliced_reads_get_the_full_score():
    rng = random.Random(3)
    g = dna(rng, 3000)
    sa = suffix_array(g)
    for _ in range(100):
        p = rng.randrange(len(g) - 50)
        read = g[p:p + 50]
        if len(occurrences(g, read)) != 1:
            continue
        assert mmp_align(read, g, sa) == Alignment(50, p, "50M")


def test_spliced_reads_are_placed_exactly_unless_an_overhang_is_short():
    rng = random.Random(4)
    long_ok = long_total = short_ok = short_total = 0
    for _ in range(6):
        g, exons, tx = gene(rng, 4)
        sa = suffix_array(g)
        for _ in range(40):
            start = rng.randrange(len(tx) - 50)
            read = tx[start:start + 50]
            aln = mmp_align(read, g, sa, min_intron=20, max_intron=1000)
            assert aln is not None
            assert aln.score == cigar_score(read, g, aln.pos, aln.cigar)
            want = truth(exons, start, 50)
            ok = (aln.pos, aln.cigar) == want
            if min(int(m) for m in re.findall(r"(\d+)M", want[1])) >= 12:
                long_ok, long_total = long_ok + ok, long_total + 1
            else:
                short_ok, short_total = short_ok + ok, short_total + 1
    # Measured with this seed: 183 of 183 reads whose blocks all have 12 bases or more,
    # and 16 of 57 reads with a shorter block, are placed exactly.
    assert (long_ok, long_total, short_ok, short_total) == (183, 183, 16, 57)


def test_reads_with_mismatches_are_found():
    rng = random.Random(5)
    found = total = 0
    for _ in range(6):
        g, exons, tx = gene(rng, 3)
        sa = suffix_array(g)
        for _ in range(30):
            start = rng.randrange(len(tx) - 50)
            read = list(tx[start:start + 50])
            for x in rng.sample(range(50), 2):
                read[x] = rng.choice([c for c in "ACGT" if c != read[x]])
            read = "".join(read)
            total += 1
            aln = mmp_align(read, g, sa)
            found += aln is not None and aln.pos == truth(exons, start, 50)[0]
    assert found >= 0.85 * total


def test_random_reads_are_unmapped():
    rng = random.Random(6)
    g = dna(rng, 3000)
    sa = suffix_array(g)
    for _ in range(100):
        assert mmp_align(dna(rng, 50), g, sa) is None

History

Manber and Myers (1993) gave the suffix array and its search by binary search. Trapnell, Pachter and Salzberg (2009) found junctions in TopHat by first mapping reads without splicing and then looking for junctions between islands of coverage. Dobin and colleagues (2013) gave STAR, which searched maximal mappable prefixes in an uncompressed suffix array of the genome, so that the first exon and the next one were found by the same exact search, and stitched the seeds with a dynamic program. They traded memory for speed.

References

  1. Alexander Dobin, Carrie A. Davis, Felix Schlesinger, Jorg Drenkow, Chris Zaleski, Sonali Jha, Philippe Batut, Mark Chaisson and Thomas R. Gingeras, STAR, ultrafast universal RNA-seq aligner, Bioinformatics 29(1) (2013), pp. 15 to 21, Sections 2.1 (seed search) and 2.2 (clustering, stitching and scoring), Section 3.3 (speed and memory), Figure 1
  2. Udi Manber and Gene Myers, Suffix arrays, a new method for on-line string searches, SIAM Journal on Computing 22(5) (1993), pp. 935 to 948 (the suffix array and the search by binary search)
  3. Cole Trapnell, Lior Pachter and Steven L. Salzberg, TopHat, discovering splice junctions with RNA-Seq, Bioinformatics 25(9) (2009), pp. 1105 to 1111 (the earlier approach, with unspliced mapping first)

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