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.
- Solves
- Spliced read alignment
- 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
- Model
- Word RAM
- Properties
- deterministicnot exactonlineiterative
- Evidence
- Proof sketchCode in 1 languages
- 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 of length with its suffix array, and a read of length 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.
MMP-ALIGN(read R of length L, genome G with suffix array SA, seed length s_min, place limit n_max, fraction τ)- 1
Δ ← an empty set of diagonals; i ← 1 - 2
while i ≤ L do - 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 - 4
if ℓ ≥ s_min and |P| ≤ n_max then add p - i to Δ for each p in P - 5
i ← i + ℓ + 1 - 6
A ← STITCH(R, G, Δ), the best alignment that puts each read base on a diagonal of Δ - 7
if A exists and score(A) ≥ τ·L then return A - 8
return unmapped
Line L3 is the MMP search. The suffixes that share the longest prefix with are next to the place where would be inserted in the sorted order, so one binary search and two comparisons give , 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 and the diagonals of . The value is the best score of an alignment that ends with base on . It adds for a match or for a mismatch to the best of three cases: start here (soft-clip all bases before), stay on from base , or come from a smaller diagonal with 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 and 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 : the last 8 bases of the first exon and the first 8 of the second. Use , , introns of 10 to 1000 bases and .
| step | start | MMP | 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 , 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 . A cut after base 9 makes the intron positions 16 to 29, TGGCCGGGAGTAGG, with the motif TG and GG, so the score is . 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 . 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 , 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 M. And an exact read across one intron gets a score at least minus the intron penalty, if the first MMP lies on the true first diagonal and both seeds are at least 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 of length and the read is of length . Positions here are 0-based, as in the code. For a string , the maximal mappable prefix is the longest prefix that occurs in , with if no letter of occurs. A diagonal aligns read base to genome base . The scores are for a match and for a mismatch, and an intron costs a penalty that depends on its first two and last two bases.
1. The seed search
The suffix array lists the starts of the suffixes of in lexicographic order. Write and for the length of the longest common prefix.
Lemma 1. For strings , .
Proof. Let . All three agree on the first letters, so . Suppose , and say (the other case is the same with the roles of and swapped). Then and agree at position , and differs from there or ends there. If ends at , then is a proper prefix of and , against . If then , and if then . Both contradict the order.
Lemma 2. Let be the first index with (in the order where a string is compared with cut to the length of ). Then is attained at or .
Proof. For we have , so by Lemma 1, . For we have , so in the same way . Comparing cut to with gives the same order as comparing with , except that a that has as a prefix counts as equal, which is also . So the lemma holds for the order that the code uses.
Theorem 1 (seed search). MMP returns the length of the maximal mappable prefix of and the sorted list of all positions where occurs in .
Proof. A prefix of of length occurs in if and only if some suffix has . So , which the code computes at the two neighbors of Lemma 2. The suffixes that start with form one contiguous block of , since they are exactly those with cut to equal to , and the cut suffixes are sorted. The two binary searches find the first index with cut suffix and the first with cut suffix , which are the ends of this block.
2. The stitching
Let be a finite set of diagonals. An alignment over chooses a read interval , soft-clips the rest, and gives each a diagonal with , such that for each either , or , which is an intron from to . 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 of the best score, and its CIGAR, read from left to right, spells exactly this alignment. If no alignment over has a positive score, it returns nothing.
Proof. Let be the best score of an alignment over whose last base is on diagonal . The last step of such an alignment is one of three cases: is also its first base, the base is on as well, or the base is on an allowed with an intron in between. So
where the inner maximum runs over the in with in the intron range and a defined . This is the recurrence of the code, by induction on ; the value 0 stands for starting a new alignment at . Every alignment ends at some , so the best of all 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 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.
Each base adds at most and each intron subtracts , so every alignment has score at most , with equality only if every base is aligned, matches, and there is no intron.
3. Exact reads
Theorem 3 (an exact unspliced read). Suppose occurs in at exactly one position , , and . Then the algorithm returns the score , the position and the CIGAR M.
Proof. By Theorem 1, the first search gives and the places , so line L4 adds the diagonal , and line L5 moves past the end of the read. So . The alignment of all of on scores , the most possible, and by the remark after Theorem 2 any alignment of score over is this one. In the code, grows strictly, so the best cell is the last base, and each back pointer goes to the base before, because . So the code returns this alignment, and line L7 accepts it since .
Theorem 4 (an exact read across one intron). Suppose matches on the diagonal and matches on , with in the intron range and penalty for this intron. Let be the length of the maximal mappable prefix of . Suppose , , , and the first two searches find at most places each. Then the returned alignment has score at least .
Proof. The first search gives , because occurs at . Its places hold by the assumption, so . The second search starts at , and occurs in on , so its maximal mappable prefix is all of it, of length , with the place on among its places. So . The true alignment, bases on and then the rest on , is an alignment over of score , and by Theorem 2 the result scores at least this.
4. What is not proved
Theorem 4 does not say that the result is the true alignment. Another alignment over 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 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 , the diagonal is missing. How often reads are still placed exactly is a measurement, which the tests make.
Complexity
The word RAM, with read length , genome length and diagonals in .
- Seed search. Each MMP search is a few binary searches of steps, each step a comparison of up to letters, so . There are at most searches, and usually only one per block, because each search moves past its match. The worst case is .
- Stitching. cells, each looking at up to diagonals, so time and space. is at most times the number of seeds.
- Index. The suffix array has entries and can be built in 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 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 , 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.
# 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
- 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
- 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)
- 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.
| Ladder | Level | What the next level needs |
|---|---|---|
| Human proof | H1 sketch |
|
| Lean | L0 no Lean part |
|
| Code (python) | I0 not checked yet |
|
| Visual | V0 none |
|
| Writing | W2 basic |
|
Tag YWMA4M Edit this page History Report an error Markdown