Algorithm Search⌘K

Algorithmadvanced

Selective alignment

Also called quasi-mapping, Salmon mapping.

Map reads to transcripts by chaining exact matches, aligning the read around the best chains only, and keeping scores above a threshold, with decoys to catch reads from elsewhere.

Time
O(L·k + h^2 + c·L·(L+b)) worst
Space
O(h + L·(L+b)) extra
Where
L = the read length; b = the band; c = the number of candidates that pass the chain filter; h = the number of k-mer hits of the read; k = the k-mer length
Properties
deterministicnot exactonlineiterative
Origin
Avi Srivastava, Laraib Malik, Hirak Sarkar, Mohsen Zakeri, Fatemeh Almodaresi, Charlotte Soneson, Michael I. Love, Carl Kingsford, Rob Patro, 2020

Selective alignment maps RNA-seq reads to a transcriptome in two steps. First it finds exact matches of the read in an index and chains them, as in minimap2, to find candidate places. Then it computes a real alignment score at each candidate whose chain is close to the best one, and keeps only the places whose score is at least a fixed fraction of the best possible score. Srivastava and colleagues (2020) built it into Salmon, on the pufferfish index, to replace quasi-mapping, which accepted places from exact matches alone. The index can also hold decoys, genome regions that look like transcripts. A read whose best score on a decoy is strictly greater than its best score on a transcript is dropped, so that reads from introns or other non-transcript regions do not inflate the abundance of a transcript.

In plain words

To place a read, first look for short words of the read that occur exactly in the transcripts. Words that fall in a row on the same transcript point to a place where the read may come from.

Next, check the best of these places with a real letter-by-letter comparison. Count the matches and charge for the differences. If the result is not good enough, throw the place away. This removes the places that only share a few words with the read.

Last, add to the index some pieces of the genome that are not transcripts but look like them. If the read fits one of these pieces better than any transcript, it probably came from there, so do not count it at all.

The problem

The input is a set of targets, each a transcript or a decoy, and a read RR of length LL. An alignment of RR (or of its reverse complement) to a target is a semiglobal alignment: all of the read against any substring of the target. With a match score MATCH>0\mathrm{MATCH} > 0 and negative scores for a mismatch and a gap, no alignment scores more than MATCH⋅L\mathrm{MATCH} \cdot L. An alignment is valid when its score is at least τ⋅MATCH⋅L\tau \cdot \mathrm{MATCH} \cdot L. The output is the set of valid alignments on transcripts, or nothing if a decoy has a strictly better valid alignment. These alignments go to the EM, which shares the read among its transcripts.

Aligning the read to every target is too slow. Selective alignment aligns only where the exact matches point, and only where their chain is good, which makes it a heuristic for the problem above.

The algorithm

The anchors of the read on a target tt are the pairs (x,y)(x, y) with q[x..x+k−1]=t[y..y+k−1]q[x..x + k - 1] = t[y..y + k - 1]. An anchor jj may follow ii in a chain when xi<xjx_i < x_j, yi<yjy_i < y_j and their diagonals y−xy - x differ by gij≤bg_{ij} \le b. A chain gets kk for its first anchor and min⁡(xj−xi,yj−yi,k)−gij\min(x_j - x_i, y_j - y_i, k) - g_{ij} for each step. This is a simple form of the chaining score of minimap2, with a linear gap cost, and CHAIN finds the best chain by dynamic programming over the anchors sorted by yy.

  1. SELECTIVE-ALIGN(read R of length L, targets, decoy flags, k-mer index, band b, fractions τ' and τ)
  2. 1C ← an empty list of candidates
  3. 2for each strand s, with q = R or q = the reverse complement of R do
  4. 3for each target t that has a k-mer hit of q do
  5. 4add (CHAIN(the anchors of q on t), t, s) to C
  6. 5S ← the best chain score in C
  7. 6keep in C only the candidates with chain score at least τ'·S
  8. 7for each candidate, A ← the best semiglobal score of q in the window of t around its chain, widened by b on each side
  9. 8V ← the candidates with A ≥ τ·MATCH·L
  10. 9if the best score in V on a decoy is strictly greater than the best score in V on a transcript then return nothing
  11. 10return the candidates in V on transcripts

Lines L2 to L4 collect, for each strand and each target, the best chain of exact k-mer matches. Line L5 takes the best chain score of the read over all targets and strands. Line L6 is the post-chaining filter: a candidate whose chain is far below the best one is not aligned at all. Line L7 aligns the read in a window that covers the chain, extended to the read ends and by the band on both sides. Line L8 keeps the alignments whose score is at least the fraction τ\tau of the top score. Line L9 is the decoy rule, and line L10 returns what is left, all of it, so a read that fits several transcripts equally well keeps all of them.

Salmon sets both fractions to 0.65 by default, as the paper states; the code uses the same values. The paper does not give the match, mismatch and gap scores in its text. The code uses 2, -4 and -4, with a linear gap cost. It leaves out the pufferfish index and its uni-MEMs (here a plain k-mer index), the limits of the chaining, affine gaps and the ksw2 library, soft-clipping, the alignment cache, read pairs and the quantification. Positions are 1-based in the text and 0-based in the code.

Example

Take A=TTCCTAAGAAA = \texttt{TTCCTAAGAA}, B=ACGGATTAGGB = \texttt{ACGGATTAGG} and C=CCGGGTAACCC = \texttt{CCGGGTAACC}. The transcripts are t1=ABCt_1 = ABC and t2=ACt_2 = AC, which skips the exon BB. The decoy is D=GCAT TTCCTACGAACCGTGTAACC ACTTD = \texttt{GCAT}\,\texttt{TTCCTACGAACCGTGTAACC}\,\texttt{ACTT}: a copy of ACAC with two substitutions, at positions 7 and 14 of the copy, and 4 more bases at each end. Use k=5k = 5, b=8b = 8 and the fractions 0.65. The reads have L=20L = 20, so the top score is 40, the validity threshold is 0.65⋅40=260.65 \cdot 40 = 26, and a chain of the top score 20 keeps the candidates with a chain score of at least 13.

The read r1r_1 is the first 20 bases of t1t_1, that is ABAB.

candidate chain passes L6 alignment score valid
t1t_1, forward 20 yes 40 yes
t2t_2, forward 10 no
DD, forward 6 no
t1t_1, reverse 10 no
t2t_2, reverse 5 no

The read r1r_1 maps to t1t_1 only, with score 40. On t2t_2 only the k-mers of AA match, and the chain stops where BB starts.

The read r2=ACr_2 = AC is t2t_2 itself.

candidate chain passes L6 alignment score valid
t1t_1, forward 10 no
t2t_2, forward 20 yes 40 yes
DD, forward 18 yes 28 yes
t1t_1, reverse 5 no

On t1t_1 the k-mers of AA and of CC are on two diagonals 10 apart, more than the band, so the chain holds only AA. The decoy alignment has two mismatches, so it scores 40−2⋅6=2840 - 2 \cdot 6 = 28. That is less than 40, so the read is kept and maps to t2t_2.

The read r3=TTCCTACGAACCGTGTAACCr_3 = \texttt{TTCCTACGAACCGTGTAACC} comes from the decoy. On t1t_1 it has a chain of 6, which fails line L6. On t2t_2 it has a chain of 18 and a valid alignment of score 28. On DD it has a chain of 20 and a score of 40. The decoy score is strictly greater, so line L9 drops the read. Without the decoy in the index, the read would map to t2t_2 with score 28 and add to its count. The test file checks all three reads, the reverse complement of r1r_1, and the case without the decoy.

Correctness

The proof shows four facts. The chain DP finds a chain of the best score, because a predecessor always comes earlier in the order by target position. Every returned alignment is real and has a score of at least τ⋅MATCH⋅L\tau \cdot \mathrm{MATCH} \cdot L, and none is on a decoy. A chain scores at most LL, and a chain of score LL means that the read occurs in the target with no error. So a read with no error always gets the top chain score, survives the filter, scores MATCH⋅L\mathrm{MATCH} \cdot L in its window, and no decoy can beat it: it is always returned with its source. These are theorems. The filter of line L6 is a heuristic: for a read with errors, the true place can have a lower chain score than a false one and then is not aligned.

Proof: The chain DP is optimal, every returned alignment is real and above the threshold, and an exact read is always returned with the top scorefull

We use the pseudocode of the page. A read RR has length L≥kL \ge k. For a strand, qq is RR or its reverse complement. An anchor (x,y)(x, y) on a target tt means q[x..x+k−1]=t[y..y+k−1]q[x..x + k - 1] = t[y..y + k - 1], an exact k-mer match. Its diagonal is y−xy - x. The scores are MATCH>0\mathrm{MATCH} > 0 for a match and negative values for a mismatch and a gap. The band is b≥0b \ge 0, and the two fractions are τ′,τ∈[0,1]\tau', \tau \in [0, 1]. Positions here are 0-based, as in the code.

1. The chain DP

An anchor jj may follow ii when xi<xjx_i < x_j, yi<yjy_i < y_j and gij=∣(yj−xj)−(yi−xi)∣≤bg_{ij} = |(y_j - x_j) - (y_i - x_i)| \le b. A chain is a sequence of anchors in which each one may follow the one before it. Its score is

σ(a1,…,am)=k+∑j=1m−1(min⁡(xj+1−xj, yj+1−yj, k)−gj,j+1).\sigma(a_1, \ldots, a_m) = k + \sum_{j=1}^{m-1} \bigl(\min(x_{j+1} - x_j,\ y_{j+1} - y_j,\ k) - g_{j,j+1}\bigr).

The function CHAIN sorts the distinct anchors by (y,x)(y, x) and computes f(j)=max⁡(k, max⁡i<j, i→jf(i)+min⁡(xj−xi,yj−yi,k)−gij)f(j) = \max\bigl(k,\ \max_{i < j,\ i \to j} f(i) + \min(x_j - x_i, y_j - y_i, k) - g_{ij}\bigr).

Lemma 1. f(j)f(j) is the best score of a chain that ends at anchor jj, and CHAIN returns a chain of the best score over all chains.

Proof. By induction on jj in the sorted order. If ii may precede jj then yi<yjy_i < y_j, so ii comes before jj in the order, and f(i)f(i) is already final. A chain that ends at jj is either jj alone, with score kk, or a chain that ends at some ii that may precede jj, followed by jj. Its score is the score of that prefix plus the step term, and the step term depends only on ii and jj. So the best score is the larger of kk and the best value of f(i)f(i) plus the step term, which is the formula. The back pointers record the ii that gives the maximum, so following them from the best jj spells a chain of score f(j)f(j). □\square

Lemma 2. Every chain has σ≤L\sigma \le L. A chain has σ=L\sigma = L only if qq occurs in tt at position y1−x1y_1 - x_1 with no error.

Proof. Each step term is at most xj+1−xjx_{j+1} - x_j, as the minimum is at most this value and g≥0g \ge 0. So σ≤k+xm−x1≤k+(L−k)−0=L\sigma \le k + x_m - x_1 \le k + (L - k) - 0 = L. Equality needs x1=0x_1 = 0, xm=L−kx_m = L - k, and in every step g=0g = 0 and min⁡(xj+1−xj,yj+1−yj,k)=xj+1−xj\min(x_{j+1} - x_j, y_{j+1} - y_j, k) = x_{j+1} - x_j. Then every anchor is on one diagonal d=y1−x1=y1d = y_1 - x_1 = y_1, and xj+1−xj≤kx_{j+1} - x_j \le k, so the read intervals [xj,xj+k)[x_j, x_j + k) cover [0,L)[0, L) with no hole. Each position pp of the read is in some anchor, so q[p]=t[d+p]q[p] = t[d + p]. Hence q=t[d..d+L−1]q = t[d..d + L - 1]. □\square

2. Soundness

Theorem 1 (soundness). Every hit that the algorithm returns is on a transcript, not on a decoy. Its score is the score of a real semiglobal alignment of qq to a substring of the target that starts at the reported position, so it is at most the best semiglobal score of qq against the whole target. And the score is at least τ⋅MATCH⋅L\tau \cdot \mathrm{MATCH} \cdot L.

Proof. Line L10 returns only hits on non-decoy targets. Each hit comes from line L7, which runs the semiglobal alignment of qq against the window t[lo..hi−1]t[lo..hi - 1] and adds lolo to the start, so the score is that of an alignment of all of qq to a substring of tt. An alignment to a substring of tt is also a semiglobal alignment to tt, because the ends of tt are free, so the score is at most the best one on tt. Line L8 keeps only the hits with score at least τ⋅MATCH⋅L\tau \cdot \mathrm{MATCH} \cdot L. □\square

Theorem 2 (decoy rule). If the best valid score on a decoy is strictly greater than every valid score on a transcript, the read gets no hit. Otherwise the decoy hits are dropped and all the valid transcript hits are returned.

Proof. This is line L9, then line L10. □\square

3. Completeness for exact reads

Theorem 3. Suppose τ′≤1\tau' \le 1, τ≤1\tau \le 1, and RR or its reverse complement occurs with no error in a transcript tt. Then the algorithm returns a hit on tt with the top score MATCH⋅L\mathrm{MATCH} \cdot L.

Proof. Let qq be the strand that occurs in tt at position dd. All L−k+1L - k + 1 k-mers of qq are in the index, at the anchors (x,d+x)(x, d + x), so tt has hits and gets a candidate in line L4. The chain of the anchors with x=0,k,2k,…x = 0, k, 2k, \ldots and then x=L−kx = L - k has all anchors on the diagonal dd, steps of at most kk and no gap, so its score is LL. By Lemma 1 the chain of tt has score at least LL, and by Lemma 2 at most LL, so it is exactly LL. By Lemma 2 again, no chain anywhere has a higher score, so the best chain score SS of line L5 is LL, and the candidate of tt passes line L6 because L≥τ′LL \ge \tau' L.

The chain that CHAIN returns for tt may be another chain of score LL. By Lemma 2 it shows an exact occurrence of qq at its diagonal d′=y1−x1d' = y_1 - x_1. The window of line L7 is [max⁡(0,d′−b),min⁡(∣t∣,d′+L+b))[\max(0, d' - b), \min(|t|, d' + L + b)), since x1=0x_1 = 0 and xm=L−kx_m = L - k give ym+(L−xm)=d′+Ly_m + (L - x_m) = d' + L. The occurrence [d′,d′+L)[d', d' + L) lies in tt, so it lies in the window. Each letter of qq adds at most MATCH\mathrm{MATCH} to a semiglobal score and gaps only subtract, so the best score is at most MATCH⋅L\mathrm{MATCH} \cdot L, and the exact occurrence reaches it. So the score of line L7 is MATCH⋅L\mathrm{MATCH} \cdot L, which passes line L8 because τ≤1\tau \le 1.

No target can score more than MATCH⋅L\mathrm{MATCH} \cdot L, so no decoy score is strictly greater than this transcript score, and line L9 does not discard the read. Line L10 returns the hit. □\square

4. What is not proved

The chain filter of line L6 is a heuristic. A read with errors can have its true location chained with a lower score than a false one, and then the true location is not aligned. Theorem 3 rules this out only for reads without errors. The tests measure that most reads with 2 percent errors are still found, which is a measurement and not a theorem. ■\blacksquare

Complexity

The word RAM, with read length LL, k-mer length kk, hh k-mer hits of the read, cc candidates after the chain filter and band bb.

  • Index. The plain k-mer index of the code takes O(nk)O(n k) time and O(n)O(n) entries for targets of total length nn. Pufferfish stores the compacted colored de Bruijn graph of the targets instead, with each k-mer found through its unitig.
  • Lookups. 2(L−k+1)2(L - k + 1) lookups of O(k)O(k) each, so O(Lk)O(L k).
  • Chaining. The DP compares each pair of anchors on a target, which is O(h2)O(h^2) in the worst case. Minimap2 limits the number of predecessors that it tries, which makes this close to linear in practice, a heuristic.
  • Alignment. A window has length at most L+2bL + 2b plus the span of the chain, which is O(L+b)O(L + b) when the chain is on one diagonal band, so each candidate costs O(L(L+b))O(L (L + b)). This is the main cost, and it is why line L6 matters.

Properties

  • Heuristic. It finds every place where the read occurs with no error (a theorem), but for reads with errors it can miss a place whose chain is weak.
  • Sound. Every place it reports has a real alignment above the threshold. This is the difference from quasi-mapping and from pseudoalignment, which accept a place on exact matches alone.
  • Multi-mapping. All valid places are reported, not only the best, and the EM shares the read among them.
  • Deterministic and online. Each read is handled alone, so reads can be streamed and run in parallel.

Variants and improvements

  • Quasi-mapping. RapMap (2016) found the transcripts and positions of a read from exact matches in an index, without an alignment score. Selective alignment adds the score.
  • Pseudoalignment. Kallisto keeps only the set of transcripts, with no position or score; see pseudoalignment.
  • The whole genome as a decoy. Srivastava and colleagues also tested an index that holds the full genome as decoys, so that a read from any part of the genome can be caught, at the cost of a much larger index. Their smaller decoy set holds only the genome regions similar to transcripts, found with MashMap at a minimum identity of 80 percent with the exons masked.
  • An alignment cache. Salmon keeps a cache per read of the target substrings it has already aligned to, so that the same window is not aligned twice.
  • Score only. Salmon computes the alignment score and not the CIGAR, which is enough to decide validity.
  • Minimizers. The exact matches can come from minimizers instead of all k-mers, as in minimap2, or from maximal matches in an FM-index.

When to use it

Use it to quantify known transcripts when the accuracy of the abundances matters more than a small factor in speed, in particular when the sample has many reads from introns, unannotated genes or repeats. Include decoys for such samples. When the transcriptome is complete and speed is all that matters, pseudoalignment is simpler. When new junctions or transcripts are expected, or the alignments themselves are needed, use spliced alignment to the genome. Srivastava and colleagues measured that quasi-mapping gave the lowest agreement with alignment-based estimates on experimental data, which is a measurement and not a proof.

Pitfalls

  • No decoys, no protection. Without decoys, a read from a region that is not a transcript maps to the most similar transcript if the score passes the threshold, as r3r_3 does in the example.
  • Ties keep the read. The decoy rule needs a strictly greater decoy score. A read that fits a transcript and a decoy equally well is kept for the transcript.
  • The threshold is relative to the read length. With τ=0.65\tau = 0.65, a short read tolerates fewer differences than a long one in absolute terms.
  • Reads that run off a transcript end. Without soft-clipping, the overhanging bases are scored as gaps, and a correct read near an end can fall below the threshold. The code has no soft-clipping.
  • The chain filter can drop the truth. With many errors, the chain of the true place can be weaker than the chain of a repeat. Lowering τ′\tau' aligns more candidates and costs time.
  • Band too small. Indels shift the diagonal, and a band smaller than the indel splits the chain, as the exon skip splits the chain of r2r_2 on t1t_1.

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.

bioseq.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Shared helper of the biology pages of https://algorithm.tamnd.com/. The authors are listed in prov/.
"""Small DNA utilities shared by the biology pages.

Conventions:
- DNA is a str over "ACGT", written 5' to 3'. Positions are 0-based.
- Random draws use a random.Random object that the caller passes in, and the
  order of the draws is fixed and written in each docstring, so that a seed
  gives the same output on every run.
- Alignment scores are added: pass match as a positive number and mismatch and
  gap as negative numbers. A CIGAR string uses M (a column with a base of both
  strings, equal or not), I (a base of a, the query, against a gap) and D (a
  base of b, the reference, against a gap).

This module holds no algorithm of a page: no ORF finder, no motif finder and
no caller. The functions are building blocks for the page code and its tests.
"""

from __future__ import annotations

import math
import random
from collections import namedtuple
from typing import Dict, List, Sequence, Tuple, Union

DNA = "ACGT"

_COMPLEMENT = {"A": "T", "C": "G", "G": "C", "T": "A", "N": "N",
               "a": "t", "c": "g", "g": "c", "t": "a", "n": "n"}


def revcomp(seq: str) -> str:
    """The reverse complement of seq. N maps to N; other letters raise KeyError."""
    return "".join(_COMPLEMENT[c] for c in reversed(seq))


# NCBI genetic code table 1 (the standard code), in the TCAG order of the NCBI
# listing: the first base changes slowest and the third base fastest.
_AAS = "FFLLSSSSYY**CC*WLLLLPPPPHHQQRRRRIIIMTTTTNNKKSSRRVVVVAAAADDEEGGGG"
_ORDER = "TCAG"
CODON_TABLE: Dict[str, str] = {
    a + b + c: _AAS[16 * i + 4 * j + k]
    for i, a in enumerate(_ORDER)
    for j, b in enumerate(_ORDER)
    for k, c in enumerate(_ORDER)
}
STOPS = frozenset(c for c, aa in CODON_TABLE.items() if aa == "*")


def translate(seq: str, frame: int = 0) -> str:
    """Translate seq[frame:] codon by codon with CODON_TABLE.

    frame is 0, 1 or 2. A stop codon gives "*", a codon with a letter other than
    A, C, G or T gives "X", and a last part shorter than three bases is dropped.
    The function does not look for start or stop codons.
    """
    if frame not in (0, 1, 2):
        raise ValueError("frame must be 0, 1 or 2")
    s = seq.upper()
    out = []
    for i in range(frame, len(s) - 2, 3):
        out.append(CODON_TABLE.get(s[i:i + 3], "X"))
    return "".join(out)


def random_dna(rng: random.Random, n: int, gc: float = 0.5) -> str:
    """n random bases, independent, with P(G) = P(C) = gc/2 and P(A) = P(T) = (1 - gc)/2.

    Draw order: one rng.random() per base, from left to right.
    """
    if not 0.0 <= gc <= 1.0:
        raise ValueError("gc must be in [0, 1]")
    half_gc, cut = gc / 2.0, gc + (1.0 - gc) / 2.0
    out = []
    for _ in range(n):
        u = rng.random()
        if u < half_gc:
            out.append("C")
        elif u < gc:
            out.append("G")
        elif u < cut:
            out.append("A")
        else:
            out.append("T")
    return "".join(out)


def _other_base(rng: random.Random, base: str) -> str:
    """A base other than base, uniform among the other three (one rng.choice)."""
    return rng.choice([b for b in DNA if b != base])


def mutate(rng: random.Random, seq: str, rate: float) -> str:
    """Substitute each base with probability rate, uniformly by one of the other three.

    Draw order: for each position from left to right, one rng.random(); if it is
    below rate, one rng.choice for the new base. Letters other than A, C, G and T
    are kept and use no draw. No insertions or deletions.
    """
    out = []
    for c in seq:
        if c in DNA and rng.random() < rate:
            out.append(_other_base(rng, c))
        else:
            out.append(c)
    return "".join(out)


SimRead = namedtuple("SimRead", ["read", "pos", "strand", "true_seq"])


def simulate_reads(rng: random.Random, genome: str, n: int, length: int,
                   error_rate: float) -> List[SimRead]:
    """n single-end reads of the given length from both strands of genome.

    Each item is SimRead(read, pos, strand, true_seq): pos is the 0-based start
    of the read on the forward strand of genome, strand is "+" or "-", true_seq
    is the error-free read (genome[pos:pos + length], or its reverse complement
    for "-"), and read is true_seq with substitution errors at rate error_rate.

    Draw order for each read: rng.randrange(len(genome) - length + 1) for pos,
    then rng.random() < 0.5 for the "+" strand, then the draws of mutate on
    true_seq.
    """
    if length > len(genome) or length <= 0:
        raise ValueError("need 0 < length <= len(genome)")
    reads = []
    for _ in range(n):
        pos = rng.randrange(len(genome) - length + 1)
        strand = "+" if rng.random() < 0.5 else "-"
        frag = genome[pos:pos + length]
        true_seq = frag if strand == "+" else revcomp(frag)
        reads.append(SimRead(mutate(rng, true_seq, error_rate), pos, strand, true_seq))
    return reads


def phred_to_prob(q: float) -> float:
    """Error probability of the Phred score q: p = 10^(-q/10)."""
    return 10.0 ** (-q / 10.0)


def prob_to_phred(p: float) -> float:
    """Phred score of the error probability p in (0, 1]: Q = -10 log10(p)."""
    if not 0.0 < p <= 1.0:
        raise ValueError("p must be in (0, 1]")
    return -10.0 * math.log10(p)


def hamming(a: Sequence, b: Sequence) -> int:
    """The number of positions where a and b differ; they must have the same length."""
    if len(a) != len(b):
        raise ValueError("hamming needs sequences of equal length")
    return sum(1 for x, y in zip(a, b) if x != y)


def kmers(seq: str, k: int) -> List[str]:
    """All len(seq) - k + 1 substrings of length k, from left to right (with repeats)."""
    if k <= 0:
        raise ValueError("k must be positive")
    return [seq[i:i + k] for i in range(len(seq) - k + 1)]


def gc_content(seq: str) -> float:
    """The fraction of G and C letters in seq (upper or lower case); 0.0 for an empty seq."""
    if not seq:
        return 0.0
    s = seq.upper()
    return (s.count("G") + s.count("C")) / len(s)


Number = Union[int, float]


def _cigar(ops: List[str]) -> str:
    """Run-length code a list of single-letter operations, for example MMMID to 3M1I1D."""
    out = []
    i = 0
    while i < len(ops):
        j = i
        while j < len(ops) and ops[j] == ops[i]:
            j += 1
        out.append(f"{j - i}{ops[i]}")
        i = j
    return "".join(out)


def _fill(a: str, b: str, match: Number, mismatch: Number, gap: Number, free_b_ends: bool):
    """The dynamic programming table of a linear gap alignment of a and b."""
    n, m = len(a), len(b)
    S = [[0] * (m + 1) for _ in range(n + 1)]
    for i in range(1, n + 1):
        S[i][0] = i * gap
    for j in range(1, m + 1):
        S[0][j] = 0 if free_b_ends else j * gap
    for i in range(1, n + 1):
        ai = a[i - 1]
        row, up = S[i], S[i - 1]
        for j in range(1, m + 1):
            diag = up[j - 1] + (match if ai == b[j - 1] else mismatch)
            row[j] = max(diag, up[j] + gap, row[j - 1] + gap)
    return S


def _trace(S, a: str, b: str, i: int, j: int, match: Number, mismatch: Number,
           gap: Number, free_b_ends: bool) -> Tuple[List[str], int]:
    """Trace back from cell (i, j); prefer M, then I, then D. Returns the ops and the start in b."""
    ops: List[str] = []
    while i > 0 or (j > 0 and not free_b_ends):
        if i > 0 and j > 0 and S[i][j] == S[i - 1][j - 1] + (match if a[i - 1] == b[j - 1] else mismatch):
            ops.append("M")
            i, j = i - 1, j - 1
        elif i > 0 and S[i][j] == S[i - 1][j] + gap:
            ops.append("I")
            i -= 1
        else:
            ops.append("D")
            j -= 1
    ops.reverse()
    return ops, j


def global_align(a: str, b: str, match: Number = 1, mismatch: Number = -1,
                 gap: Number = -1) -> Tuple[Number, str]:
    """Needleman-Wunsch alignment of all of a with all of b, with linear gaps.

    Returns (score, cigar). The cigar uses M, I (a base of a only) and D (a base of
    b only); an empty alignment gives "".
    """
    S = _fill(a, b, match, mismatch, gap, False)
    ops, _ = _trace(S, a, b, len(a), len(b), match, mismatch, gap, False)
    return S[len(a)][len(b)], _cigar(ops)


def semiglobal_align(a: str, b: str, match: Number = 1, mismatch: Number = -1,
                     gap: Number = -1, with_start: bool = False):
    """Align all of a (the query) to a substring of b (the reference), with linear gaps.

    Bases of b before and after the aligned part cost nothing and are not in the
    cigar, as in SAM. Returns (score, cigar), or (score, cigar, start) with
    with_start=True, where start is the 0-based position in b of the first
    reference base of the alignment. Among best end columns the leftmost wins.
    """
    S = _fill(a, b, match, mismatch, gap, True)
    n = len(a)
    best_j = max(range(len(b) + 1), key=lambda j: (S[n][j], -j))
    ops, start = _trace(S, a, b, n, best_j, match, mismatch, gap, True)
    if with_start:
        return S[n][best_j], _cigar(ops), start
    return S[n][best_j], _cigar(ops)
selective_alignment.py 106 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/selective-alignment/. The authors are listed in prov/1P4EX1.jsonl.

"""Selective alignment of reads to a transcriptome with decoys, in the style of Salmon.

The targets are transcripts and decoys (for example genome regions that look
like transcripts). For each orientation of the read, the exact k-mer hits on
each target are chained by dynamic programming, the chains far below the best
one are dropped, and every remaining chain is checked by a real alignment of
the read in a window of the target around the chain. An alignment is valid
when its score is at least tau times the best possible score. If the best
valid score on a decoy is strictly greater than the best valid score on a
transcript, the read is discarded; otherwise the valid transcript alignments
are returned.

What this leaves out, compared with Salmon: the pufferfish index and its
uni-MEMs (here a plain k-mer hash), the limits on the number of chaining
predecessors, affine gaps and the ksw2 extension alignment (here a linear gap
semiglobal alignment from bioseq), soft-clipping, the alignment cache, read
pairs and the quantification. Positions are 0-based.
"""

from __future__ import annotations

from typing import Dict, List, NamedTuple, Sequence, Tuple

from bioseq import revcomp, semiglobal_align

MATCH, MISMATCH, GAP = 2, -4, -4


class Hit(NamedTuple):
    target: int
    strand: str
    score: int
    start: int


def build_index(targets: Sequence[str], k: int) -> Dict[str, List[Tuple[int, int]]]:
    """Map each k-mer to the list of (target id, position) where it occurs."""
    index: Dict[str, List[Tuple[int, int]]] = {}
    for t, seq in enumerate(targets):
        for r in range(len(seq) - k + 1):
            index.setdefault(seq[r:r + k], []).append((t, r))
    return index


def chain(anchors: Sequence[Tuple[int, int]], k: int, band: int) -> Tuple[int, List[Tuple[int, int]]]:
    """The best chain of anchors (q, r), each an exact k-mer match of read q to target r.

    An anchor j can follow i if q_i < q_j, r_i < r_j and the diagonals differ by at
    most band. The step gains min(q_j - q_i, r_j - r_i, k) and loses the difference
    of the diagonals. Returns (score, chain); the score of one anchor is k.
    """
    a = sorted(set(anchors), key=lambda x: (x[1], x[0]))
    if not a:
        return 0, []
    f = [k] * len(a)
    back = [-1] * len(a)
    for j, (qj, rj) in enumerate(a):
        for i in range(j):
            qi, ri = a[i]
            gap = abs((rj - qj) - (ri - qi))
            if qi < qj and ri < rj and gap <= band:
                s = f[i] + min(qj - qi, rj - ri, k) - gap
                if s > f[j]:
                    f[j], back[j] = s, i
    j = max(range(len(a)), key=lambda x: (f[x], -x))
    best, out = f[j], []
    while j >= 0:
        out.append(a[j])
        j = back[j]
    return best, out[::-1]


def selective_align(read: str, targets: Sequence[str], is_decoy: Sequence[bool],
                    index: Dict[str, List[Tuple[int, int]]], k: int, band: int = 8,
                    chain_frac: float = 0.65, score_frac: float = 0.65) -> List[Hit]:
    """Return the valid alignments of read to transcripts, or [] if the read is discarded."""
    L = len(read)
    cands = []  # @line L1
    for strand, q in (("+", read), ("-", revcomp(read))):  # @line L2
        hits: Dict[int, List[Tuple[int, int]]] = {}
        for i in range(L - k + 1):
            for t, r in index.get(q[i:i + k], ()):
                hits.setdefault(t, []).append((i, r))
        for t in sorted(hits):  # @line L3
            s, c = chain(hits[t], k, band)
            cands.append((s, t, strand, q, c))  # @line L4
    if not cands:
        return []
    best_chain = max(c[0] for c in cands)  # @line L5
    cands = [c for c in cands if c[0] >= chain_frac * best_chain]  # @line L6
    valid: List[Hit] = []
    for s, t, strand, q, c in cands:
        (q1, r1), (q2, r2) = c[0], c[-1]
        lo = max(0, r1 - q1 - band)
        hi = min(len(targets[t]), r2 + (L - q2) + band)
        score, _, start = semiglobal_align(q, targets[t][lo:hi], MATCH, MISMATCH, GAP, with_start=True)  # @line L7
        if score >= score_frac * MATCH * L:  # @line L8
            valid.append(Hit(t, strand, score, lo + start))
    best_decoy = max((h.score for h in valid if is_decoy[h.target]), default=None)
    best_tx = max((h.score for h in valid if not is_decoy[h.target]), default=None)
    if best_decoy is not None and (best_tx is None or best_decoy > best_tx):  # @line L9
        return []
    return sorted(h for h in valid if not is_decoy[h.target])  # @line L10
test_selective_alignment.py 143 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/selective-alignment/. The authors are listed in prov/1P4EX1.jsonl.

import random
from itertools import combinations

from bioseq import mutate, random_dna, revcomp, semiglobal_align, simulate_reads
from selective_alignment import MATCH, MISMATCH, GAP, Hit, build_index, chain, selective_align

A, B, C = "TTCCTAAGAA", "ACGGATTAGG", "CCGGGTAACC"
DECOY = "GCAT" + "TTCCTACGAACCGTGTAACC" + "ACTT"


def test_worked_example():
    targets = [A + B + C, A + C, DECOY]
    decoy = [False, False, True]
    idx = build_index(targets, 5)
    r1, r2, r3 = (A + B)[:20], A + C, DECOY[4:24]
    assert selective_align(r1, targets, decoy, idx, 5) == [Hit(0, "+", 40, 0)]
    assert selective_align(r2, targets, decoy, idx, 5) == [Hit(1, "+", 40, 0)]
    assert selective_align(r3, targets, decoy, idx, 5) == []
    # The decoy copy differs from A + C at two places, so each scores 40 - 2 * 6 = 28 against the other.
    assert semiglobal_align(r2, DECOY, MATCH, MISMATCH, GAP)[0] == 28
    assert semiglobal_align(r3, A + C, MATCH, MISMATCH, GAP)[0] == 28
    # Without the decoy the read from the decoy is mapped to t2.
    idx2 = build_index(targets[:2], 5)
    assert selective_align(r3, targets[:2], decoy[:2], idx2, 5) == [Hit(1, "+", 28, 0)]
    # The reverse strand of r1 maps the same way.
    assert selective_align(revcomp(r1), targets, decoy, idx, 5) == [Hit(0, "-", 40, 0)]


def brute_chain(anchors, k, band):
    a = sorted(set(anchors), key=lambda x: (x[1], x[0]))
    best = 0
    for size in range(1, len(a) + 1):
        for sub in combinations(a, size):
            s, ok = k, True
            for (qi, ri), (qj, rj) in zip(sub, sub[1:]):
                gap = abs((rj - qj) - (ri - qi))
                if not (qi < qj and ri < rj and gap <= band):
                    ok = False
                    break
                s += min(qj - qi, rj - ri, k) - gap
            if ok:
                best = max(best, s)
    return best


def test_chain_against_brute_force():
    rng = random.Random(1)
    for _ in range(300):
        k = rng.randint(3, 6)
        anchors = [(rng.randrange(20), rng.randrange(25)) for _ in range(rng.randint(1, 8))]
        band = rng.randint(0, 5)
        s, c = chain(anchors, k, band)
        assert s == brute_chain(anchors, k, band)
        total = k
        for (qi, ri), (qj, rj) in zip(c, c[1:]):
            gap = abs((rj - qj) - (ri - qi))
            assert qi < qj and ri < rj and gap <= band
            total += min(qj - qi, rj - ri, k) - gap
        assert total == s


def random_targets(rng):
    exons = [random_dna(rng, rng.randint(20, 60)) for _ in range(5)]
    tx = ["".join(e for e in exons if rng.random() < 0.6) or exons[0] for _ in range(3)]
    decoys = [mutate(rng, random_dna(rng, 10) + rng.choice(tx) + random_dna(rng, 10), 0.05)]
    return tx + decoys, [False] * len(tx) + [True]


def test_exact_reads_are_always_found_with_the_top_score():
    rng = random.Random(2)
    for _ in range(25):
        targets, decoy = random_targets(rng)
        idx = build_index(targets, 9)
        for src in range(3):
            seq = targets[src]
            if len(seq) < 30:
                continue
            for r in simulate_reads(rng, seq, 6, 30, 0.0):
                out = selective_align(r.read, targets, decoy, idx, 9)
                assert Hit(src, r.strand, 60, r.pos) in out or any(
                    h.target == src and h.score == 60 for h in out)


def test_returned_alignments_are_real_and_above_the_threshold():
    rng = random.Random(3)
    for _ in range(25):
        targets, decoy = random_targets(rng)
        idx = build_index(targets, 9)
        for src in range(3):
            seq = targets[src]
            if len(seq) < 30:
                continue
            for r in simulate_reads(rng, seq, 6, 30, 0.04):
                for h in selective_align(r.read, targets, decoy, idx, 9):
                    q = r.read if h.strand == "+" else revcomp(r.read)
                    assert not decoy[h.target]
                    assert h.score >= 0.65 * MATCH * len(q)
                    assert h.score <= semiglobal_align(q, targets[h.target], MATCH, MISMATCH, GAP)[0]
                    window = targets[h.target][h.start:h.start + len(q) + 8]
                    assert semiglobal_align(q, window, MATCH, MISMATCH, GAP)[0] >= h.score


def test_decoy_rule():
    rng = random.Random(4)
    for _ in range(40):
        tx = random_dna(rng, 60)
        copy = mutate(rng, tx, 0.04)
        targets, decoy = [tx, "GG" + copy + "CC"], [False, True]
        idx = build_index(targets, 7)
        read = copy[10:40]
        out = selective_align(read, targets, decoy, idx, 7)
        d = semiglobal_align(read, targets[1], MATCH, MISMATCH, GAP)[0]
        t = semiglobal_align(read, targets[0], MATCH, MISMATCH, GAP)[0]
        if d > t:
            assert out == []
        else:
            assert all(h.target == 0 for h in out)
        # A read that is the same in both is kept.
        if tx[40:60] == copy[40:60]:
            assert selective_align(tx[40:60], targets, decoy, idx, 7)


def test_random_reads_do_not_map():
    rng = random.Random(5)
    targets = [random_dna(rng, 500) for _ in range(4)]
    idx = build_index(targets, 11)
    for _ in range(100):
        assert selective_align(random_dna(rng, 50), targets, [False] * 4, idx, 11) == []


def test_reads_with_errors_are_mostly_found():
    rng = random.Random(6)
    found = total = 0
    targets = [random_dna(rng, 400) for _ in range(3)]
    idx = build_index(targets, 11)
    for src, seq in enumerate(targets):
        for r in simulate_reads(rng, seq, 40, 60, 0.02):
            total += 1
            found += any(h.target == src for h in selective_align(r.read, targets, [False] * 3, idx, 11))
    assert found >= 0.95 * total

History

Patro, Mount and Kingsford (2014) quantified transcripts without alignment in Sailfish, from k-mer counts. Srivastava, Sarkar, Gupta and Patro (2016) introduced quasi-mapping in RapMap, which found the transcripts and positions of a read from exact matches in a generalized suffix array of the transcriptome, with a hash table from each k-mer to its suffix array interval, and computed no base-level alignment. Patro and colleagues (2017) used such mappings in Salmon. Almodaresi, Sarkar, Srivastava and Patro (2018) gave pufferfish, an index of the compacted colored de Bruijn graph. Srivastava and colleagues (2020) showed that mapping without an alignment score can distort abundance estimates, and gave selective alignment with chaining, a score threshold and decoys, on the pufferfish index.

References

  1. Avi Srivastava, Laraib Malik, Hirak Sarkar, Mohsen Zakeri, Fatemeh Almodaresi, Charlotte Soneson, Michael I. Love, Carl Kingsford and Rob Patro, Alignment and mapping methodology influence transcript abundance estimation, Genome Biology 21 (2020), Article 239, Materials and methods (the sections on selective alignment and on decoy sequences)
  2. Avi Srivastava, Hirak Sarkar, Nitish Gupta and Rob Patro, RapMap, a rapid, sensitive and accurate tool for mapping RNA-seq reads to transcriptomes, Bioinformatics 32(12) (2016), pp. i192 to i200 (quasi-mapping)
  3. Fatemeh Almodaresi, Hirak Sarkar, Avi Srivastava and Rob Patro, A space and time-efficient index for the compacted colored de Bruijn graph, Bioinformatics 34(13) (2018), pp. i169 to i177 (the pufferfish index)
  4. Rob Patro, Geet Duggal, Michael I. Love, Rafael A. Irizarry and Carl Kingsford, Salmon provides fast and bias-aware quantification of transcript expression, Nature Methods 14(4) (2017), pp. 417 to 419 (the quantification that uses the mappings)
  5. Heng Li, Minimap2, pairwise alignment for nucleotide sequences, Bioinformatics 34(18) (2018), pp. 3094 to 3100 (the chaining score)

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