Algorithm Search⌘K

Algorithmadvanced

Pseudoalignment

Also called kallisto pseudoalignment, read equivalence classes.

Find the set of transcripts compatible with a read by intersecting the colors of its k-mers in a transcriptome de Bruijn graph, skipping along contigs, with no base-level alignment.

Time
O(L·(k+m)) worst
Space
O(n·(k+m)) extra
Where
L = the read length; k = the k-mer length; m = the number of transcripts; n = the total length of the transcripts
Properties
deterministicnot exactonlineiterative
Origin
Nicolas L. Bray, Harold Pimentel, Páll Melsted, Lior Pachter, 2016

Pseudoalignment finds, for each read, the set of transcripts that the read is compatible with, and nothing more: not the position, not the alignment. In kallisto, introduced by Bray, Pimentel, Melsted and Pachter (2016), the compatible set is the intersection of the colors of the read k-mers, where the color of a k-mer is the set of transcripts that hold it. The k-mers are the nodes of a de Bruijn graph of the transcriptome, and the graph is cut into contigs whose k-mers all have one color, so after one lookup the algorithm can jump to the end of a contig and check only one k-mer there. Reads with the same set form an equivalence class, and the class counts are all that the EM of abundance estimation needs. On reads whose k-mers are all in the index, the skips give exactly the intersection of all the colors; on other reads they give a superset of it.

In plain words

Make a list of every short word of a fixed length that occurs in any transcript, and write next to each word the transcripts that contain it. To place a read, cut it into words and look each one up. A transcript that the read came from must contain all of the words, so keep only the transcripts that are on every list.

Looking up every word is slow. But many words follow each other in long chains, and inside a chain the lists are all the same. So after one word, jump to the end of its chain, check that the read still agrees there, and skip the words in between.

The answer is a set of transcripts, not a place. Reads with the same answer are counted together.

The problem

The input is a set of mm transcripts, a k-mer length kk, and reads. Let KK be the set of k-mers of the transcripts and of their reverse complements, so that reads from both strands are found. The color col(x)\mathrm{col}(x) of x∈Kx \in K is the set of transcripts that hold xx on either strand. For a read RR of length LL, the task is the set

Naive(R)=⋂i : R[i..i+k−1]∈Kcol(R[i..i+k−1]),\mathrm{Naive}(R) = \bigcap_{i \,:\, R[i..i+k-1] \in K} \mathrm{col}(R[i..i+k-1]),

the transcripts that hold every k-mer of the read that is in the index, or the empty set if no k-mer of the read is in the index. Kallisto calls it the k-compatibility class of the read. The reads are then grouped by this set into equivalence classes with counts, which is the input of abundance estimation.

The index joins the k-mers into contigs. There is an edge from xx to yy when the last k−1k - 1 letters of xx are the first k−1k - 1 letters of yy. A contig c=(c1,…,c∣c∣)c = (c_1, \ldots, c_{|c|}) is a maximal run in which each cjc_j has exactly one successor in KK, which is cj+1c_{j+1}, cj+1c_{j+1} has exactly one predecessor, and both have the same color. Contigs are the unitigs of the graph, cut further where the color changes. Each k-mer is stored in a hash table with its contig and its position in the contig.

The algorithm

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

  1. PSEUDOALIGN(read R of length L, an index of k-mers with contig, position and color)
  2. 1E ← undefined
  3. 2i ← 1
  4. 3while i ≤ L - k + 1 do
  5. 4x ← R[i .. i + k - 1]
  6. 5if x is in the index then
  7. 6(c, p) ← the contig and position of x; E ← col(c) if E is undefined, else E ∩ col(c)
  8. 7d ← min(|c| - p, L - k + 1 - i)
  9. 8if d > 0 and R[i + d .. i + d + k - 1] = c_{p+d} then i ← i + d + 1 else i ← i + 1
  10. 9else i ← i + 1
  11. 10return E, or the empty set if E is undefined

Lines L4 to L6 look up one k-mer and intersect its color. Line L7 computes how far the read can still follow the contig: to the end of the contig or to the end of the read, whichever comes first. Line L8 checks the k-mer at that distance. Inside a contig every k-mer has only one successor, so a read whose k-mers are all in the index must follow the contig, and the check passes. Then all the k-mers in between have the color already intersected, and the loop skips them. If the check fails, the read has left the contig or has an error, and the loop goes on one k-mer at a time. Line L9 steps over a k-mer that is not in the index, for example one that holds a sequencing error.

The code builds the contigs from a dictionary of k-mers. It leaves out what kallisto does for speed and space: canonical k-mers that store both strands once, a compact store of contigs and color classes, read pairs, and the EM, which is on the EM page.

Example

The transcripts are t1=XEYt_1 = X E Y and t2=XYt_2 = X Y, with X=CAGAACCX = \texttt{CAGAACC}, E=TGCTGTE = \texttt{TGCTGT} and Y=GACATAAY = \texttt{GACATAA}, and k=5k = 5. All 5-mers are distinct, so KK has 20 k-mers on each strand. The index has 8 contigs, 4 on each strand. The forward ones are:

contig k-mers color
CAGAACC 3 {t1,t2}\{t_1, t_2\}
AACCTGCTGTGACA 10 {t1}\{t_1\}
AACCGACA 4 {t2}\{t_2\}
GACATAA 3 {t1,t2}\{t_1, t_2\}

The contig CAGAACC ends where XX ends, because GAACC has two successors, AACCT into EE and AACCG into YY. The second contig is the end of XX, all of EE and the start of YY, which only t1t_1 has. The third is the junction of XX and YY, which only t2t_2 has.

The read R=AGAACCTGCTGTGACATAR = \texttt{AGAACCTGCTGTGACATA} is t1t_1 without its first and last two bases. It has L=18L = 18 and 14 k-mers.

ii k-mer contig, pp dd checked k-mer E after line L6 next ii
1 AGAAC CAGAACC, 2 min⁡(1,13)=1\min(1, 13) = 1 GAACC at 2, equal to c3c_3 {t1,t2}\{t_1, t_2\} 3
3 AACCT AACCTGCTGTGACA, 1 min⁡(9,11)=9\min(9, 11) = 9 TGACA at 12, equal to c10c_{10} {t1}\{t_1\} 13
13 GACAT GACATAA, 1 min⁡(2,1)=1\min(2, 1) = 1 ACATA at 14, equal to c2c_2 {t1}\{t_1\} 15, stop

Three lookups and three checks replace 14 lookups, and the result is {t1}\{t_1\}. The read t2t_2 itself, of 14 bases, is looked up at positions 1, 4 and 8 and gives {t2}\{t_2\}. The read XX alone gives {t1,t2}\{t_1, t_2\}, and a read of only T bases gives the empty set. The reverse complement of each read gives the same set, through the contigs of the other strand. The test file checks all of these, with the 0-based positions 0, 2 and 12 for the first read.

Correctness

The proof first shows that the contigs split KK, with one color per contig. The key lemma: if R[i..]R[i..] equals cpc_p and the next dd read k-mers are all in KK, they are cp+1,…,cp+dc_{p+1}, \ldots, c_{p+d}, because each of these nodes has only one successor in KK. From this, three theorems follow. The result always contains Naive(R)\mathrm{Naive}(R), because it intersects the colors of a subset of the same k-mers. If every k-mer of the read is in KK, the result equals Naive(R)\mathrm{Naive}(R), and for an error-free read the source transcript is in it. And in that case the number of lookups is the number of contig visits of the read.

Proof: Skipping along contigs gives the k-mer intersection exactly when all read k-mers are indexed, and a superset of it otherwisefull

We use the pseudocode of the page. KK is the set of k-mers of the transcripts and of their reverse complements, and col(x)\mathrm{col}(x) is the set of transcripts that hold xx on either strand. There is an edge from xx to yy in KK when the last k−1k - 1 letters of xx are the first k−1k - 1 letters of yy. A read RR has length L≥kL \ge k and the k-mers Ri=R[i..i+k−1]R_i = R[i..i + k - 1] for i=1,…,L−k+1i = 1, \ldots, L - k + 1. The naive set is

Naive(R)=⋂i:Ri∈Kcol(Ri),\mathrm{Naive}(R) = \bigcap_{i : R_i \in K} \mathrm{col}(R_i),

and the empty set when no RiR_i is in KK. Positions are 1-based, as on the page; the code uses 0-based positions.

1. Contigs

The index cuts KK into contigs c=(c1,…,c∣c∣)c = (c_1, \ldots, c_{|c|}). For j<∣c∣j < |c| the code puts cj+1c_{j+1} after cjc_j only if cjc_j has exactly one successor in KK, that successor is cj+1c_{j+1}, cj+1c_{j+1} has exactly one predecessor in KK, and col(cj+1)=col(cj)\mathrm{col}(c_{j+1}) = \mathrm{col}(c_j).

Lemma 1. Every k-mer of KK lies in exactly one contig, at one position. All k-mers of a contig have the same color, the color of the contig.

Proof. Call yy the next node of xx if the four conditions above hold for xx and yy. Each node has at most one next node, and is the next node of at most one node, because a next node has exactly one predecessor. So the relation splits KK into disjoint simple paths and simple cycles. The first loop of the code starts a contig at every node that is not the next node of another node and follows next nodes to the end of its path; this covers every path. The second loop takes each node that is still not placed, which lies on a cycle, and follows the cycle once, so it covers every cycle. No node is placed twice, because a walk enters a node only from its unique predecessor in the relation. The colors are equal along each step, so they are equal on the whole contig. □\square

2. Skipping is safe on indexed k-mers

Lemma 2. Suppose Ri=cpR_i = c_p and d≤∣c∣−pd \le |c| - p, and suppose Ri+1,…,Ri+dR_{i+1}, \ldots, R_{i+d} are all in KK. Then Ri+j=cp+jR_{i+j} = c_{p+j} for 0≤j≤d0 \le j \le d.

Proof. By induction on jj. The case j=0j = 0 is given. Let j<dj < d with Ri+j=cp+jR_{i+j} = c_{p+j}. The k-mers Ri+jR_{i+j} and Ri+j+1R_{i+j+1} overlap in k−1k - 1 letters, and Ri+j+1∈KR_{i+j+1} \in K, so Ri+j+1R_{i+j+1} is a successor of cp+jc_{p+j} in KK. As p+j<∣c∣p + j < |c|, the node cp+jc_{p+j} is not the last of its contig, so it has exactly one successor in KK, namely cp+j+1c_{p+j+1}. Hence Ri+j+1=cp+j+1R_{i+j+1} = c_{p+j+1}. □\square

3. The result

Let HH be the set of positions that the algorithm looks up in line L4 and finds in KK in line L5, and let Fast(R)\mathrm{Fast}(R) be the returned set. Line L6 intersects one color per position in HH, and line L10 returns the empty set when HH is empty.

Lemma 3. The loop stops, and Fast(R)=⋂i∈Hcol(Ri)\mathrm{Fast}(R) = \bigcap_{i \in H} \mathrm{col}(R_i), or the empty set if HH is empty.

Proof. Each round raises ii by at least 1, so there are at most L−k+1L - k + 1 rounds. By Lemma 1, col(Ri)\mathrm{col}(R_i) is the color of the contig of RiR_i, which is what line L6 intersects. □\square

Theorem 1 (superset). Fast(R)⊇Naive(R)\mathrm{Fast}(R) \supseteq \mathrm{Naive}(R) for every read.

Proof. Every position in HH holds a k-mer in KK, so Fast(R)\mathrm{Fast}(R) is an intersection over a subset of the positions of the naive set, which can only be larger. It remains to check the case H=∅H = \emptyset. A skip happens only in line L8, after a hit. If there is no hit, the loop visits every position one by one, so no RiR_i is in KK and Naive(R)\mathrm{Naive}(R) is empty too. □\square

Theorem 2 (exact). If every k-mer of RR is in KK, then Fast(R)=Naive(R)\mathrm{Fast}(R) = \mathrm{Naive}(R). In particular this holds for every error-free read that is a substring of a transcript or of its reverse complement, and then the source transcript is in Fast(R)\mathrm{Fast}(R).

Proof. Take a hit at position ii with Ri=cpR_i = c_p, and the value d=min⁡(∣c∣−p,L−k+1−i)d = \min(|c| - p, L - k + 1 - i) of line L7. All of Ri+1,…,Ri+dR_{i+1}, \ldots, R_{i+d} are in KK, so by Lemma 2 they are cp+1,…,cp+dc_{p+1}, \ldots, c_{p+d}. Their colors equal the color of cc by Lemma 1, which line L6 has already intersected. So skipping them in line L8 does not change the intersection. (The test of line L8 also passes, by the same lemma.) Every position is thus either in HH or skipped with a color already in the intersection, and the two sets are equal. An error-free read from a transcript tt has all its k-mers in tt or in its reverse complement, so they are all in KK, and tt is in every color that is intersected. □\square

Theorem 3 (what the set means). If every k-mer of RR is in KK, then Fast(R)\mathrm{Fast}(R) is the set of transcripts tt such that every k-mer of RR occurs in tt or in its reverse complement.

Proof. By Theorem 2 and the definition of the colors. □\square

This set contains every transcript that holds RR itself, but it can be larger: a transcript can hold all k-mers of RR in another order, or some on one strand and some on the other. Pseudoalignment does not check the order of the k-mers.

4. The number of lookups

Theorem 4. If every k-mer of RR is in KK, the number of lookups is the number of contig visits of RR: the maximal runs of consecutive read k-mers that lie at consecutive positions of one contig.

Proof. At a hit Ri=cpR_i = c_p, Lemma 2 shows that the read follows cc to position p+dp + d, and the test of line L8 passes when d>0d > 0, so the next lookup is at i+d+1i + d + 1. Either i+d+1>L−k+1i + d + 1 > L - k + 1 and the loop ends, or p+d=∣c∣p + d = |c| and the next k-mer starts a new visit. If d=0d = 0, the visit has one k-mer. So each visit costs exactly one lookup. ■\blacksquare

Complexity

The word RAM, with read length LL, k-mer length kk, mm transcripts of total length nn.

  • Index. O(n)O(n) k-mers, each hashed in O(k)O(k), with a color of up to mm ids. The contigs cost O(k)O(k) per k-mer for the four successor and predecessor lookups. That is O(n(k+m))O(n (k + m)) time and space.
  • One read. At most L−k+1L - k + 1 rounds, each with a lookup and a check of O(k)O(k) and an intersection of O(m)O(m), so O(L(k+m))O(L (k + m)) in the worst case. When every k-mer is in the index, the rounds are as many as the contig visits, which is often 1 to 3 for a short read.

Kallisto reported the quantification of 30 million reads in a few minutes on one ordinary computer, which is a measurement.

Properties

  • Not an alignment. It gives no position, strand or CIGAR. It cannot be used for variant calling or as a SAM file.
  • Exact or a superset. The result equals the k-mer intersection when every read k-mer is indexed, and is a superset of it otherwise, both theorems. The k-mer intersection is itself only an approximation of the set of transcripts that hold the read.
  • Deterministic and online. Each read is handled on its own, so reads can be streamed and the work runs in parallel.
  • Robust to errors in a crude way. A k-mer with an error is usually not in KK and is just skipped, so a read with a few errors still gets a set.

Variants and improvements

  • Canonical k-mers. Kallisto stores each k-mer and its reverse complement once, as the smaller of the two, and keeps the strand in the contig.
  • Read pairs. The set of a pair is the intersection of the sets of its two reads.
  • Quasi-mapping and selective alignment. RapMap and Salmon find the transcripts and the positions of exact matches in an index, and selective alignment adds a score to every candidate, which removes many of the false hits that a pure k-mer intersection allows.
  • Single cells. In single-cell RNA-seq, pseudoalignment of each read with its barcode and molecule identifier gives counts per cell.
  • Uncertainty. Kallisto runs the EM again on bootstrap samples of the class counts to estimate the variance; see bootstrap.

When to use it

Use it to quantify the expression of known transcripts, quickly and with little memory, when the transcriptome is good and the sample is not too far from it. It is the method of choice for large studies and for single-cell data. Do not use it when positions or alignments are needed, when new transcripts or junctions are expected, or when the sample has many reads from outside the transcriptome, such as intron reads; there, selective alignment with decoys, or spliced alignment to the genome, does better. Srivastava and colleagues (2020) measured cases where mapping without alignment scores gave worse abundance estimates than alignment.

Pitfalls

  • Order is not checked. A transcript that holds all the read k-mers in another order, or on mixed strands, is in the set. For small kk this happens often; kallisto uses k=31k = 31.
  • Reads from outside the index. A read from an intron or from an unannotated gene may share a few k-mers with a transcript and get that transcript as its set. The other k-mers are not in KK and are skipped without notice.
  • Skipping over an error. If a read leaves a contig because of an error and comes back to it at the checked position, the k-mers with the error are skipped. If such a k-mer happens to be in KK with another color, the naive set would have been smaller. This is why the result is only a superset in general.
  • An empty intersection. Two read k-mers with disjoint colors, from an error or from a read across an unannotated junction, give the empty set, and the read is not counted. Many such reads are a sign that the index lacks transcripts of the sample.
  • Contigs must end where colors change. A unitig whose k-mers have different colors cannot be skipped as a whole. Forgetting to cut there makes the skip wrong.

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)
pseudoalignment.py 139 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/pseudoalignment/. The authors are listed in prov/6KKBA9.jsonl.

"""Pseudoalignment of reads to a transcriptome, in the style of kallisto.

The index holds every k-mer of every transcript and of its reverse
complement, with its color: the set of transcript ids that contain it. The
k-mers are nodes of a de Bruijn graph, with an edge from x to y when x[1:] ==
y[:-1]. A contig is a maximal run of nodes x_0, ..., x_r in which each x_j
has exactly one successor, x_{j+1}, which has exactly one predecessor, x_j,
and the same color. So all k-mers of a contig have one color.

pseudoalign(read) returns the intersection of the colors of the read k-mers
that are in the index. After a hit at position p of a contig c, it jumps to
the last read k-mer that can still lie in c, and if that k-mer is the one at
the expected place in c, it skips all the k-mers in between.

What this leaves out, compared with kallisto: canonical k-mers (here both
strands are stored), the compact storage of colors and contigs, paired-end
reads, fragment length and the EM, which is on the EM isoform quantification
page. Positions are 0-based.
"""

from __future__ import annotations

from collections import Counter
from typing import Dict, FrozenSet, Iterable, List, Optional, Sequence, Tuple

from bioseq import kmers, revcomp

Color = FrozenSet[int]


class PseudoIndex:
    """The colored de Bruijn graph of a set of transcripts, cut into contigs."""

    def __init__(self, transcripts: Sequence[str], k: int):
        if k <= 0:
            raise ValueError("k must be positive")
        self.k = k
        colors: Dict[str, set] = {}
        for t, seq in enumerate(transcripts):
            for s in (seq, revcomp(seq)):
                for x in kmers(s, k):
                    colors.setdefault(x, set()).add(t)
        self.color: Dict[str, Color] = {x: frozenset(v) for x, v in colors.items()}
        self.contigs: List[List[str]] = []
        self.contig_color: List[Color] = []
        self.where: Dict[str, Tuple[int, int]] = {}
        self._build_contigs()

    def successors(self, x: str) -> List[str]:
        return [y for y in (x[1:] + b for b in "ACGT") if y in self.color]

    def predecessors(self, x: str) -> List[str]:
        return [y for y in (b + x[:-1] for b in "ACGT") if y in self.color]

    def _next(self, x: str) -> Optional[str]:
        """The node that follows x inside its contig, or None if x ends its contig."""
        out = self.successors(x)
        if len(out) != 1:
            return None
        y = out[0]
        if y == x or len(self.predecessors(y)) != 1 or self.color[y] != self.color[x]:
            return None
        return y

    def _add(self, run: List[str]) -> None:
        cid = len(self.contigs)
        self.contigs.append(run)
        self.contig_color.append(self.color[run[0]])
        for p, x in enumerate(run):
            self.where[x] = (cid, p)

    def _build_contigs(self) -> None:
        nodes = sorted(self.color)
        has_prev = {y for y in (self._next(x) for x in nodes) if y is not None}
        for x in nodes:
            if x in has_prev:
                continue
            run = [x]
            while (y := self._next(run[-1])) is not None:
                run.append(y)
            self._add(run)
        for x in nodes:
            if x in self.where:
                continue
            # x lies on a cycle of contig edges: cut the cycle before x.
            run = [x]
            while (y := self._next(run[-1])) is not None and y != x:
                run.append(y)
            self._add(run)

    def kmer_at(self, cid: int, p: int) -> str:
        return self.contigs[cid][p]


def pseudoalign(index: PseudoIndex, read: str, trace: Optional[list] = None) -> Color:
    """The set of transcripts compatible with read; empty if no read k-mer is in the index.

    If trace is a list, the read positions that were looked up are appended to it.
    """
    k, L = index.k, len(read)
    E: Optional[Color] = None  # @line L1
    i = 0  # @line L2
    while i <= L - k:  # @line L3
        x = read[i:i + k]  # @line L4
        if trace is not None:
            trace.append(i)
        if x in index.where:  # @line L5
            c, p = index.where[x]  # @line L6
            E = index.contig_color[c] if E is None else E & index.contig_color[c]
            d = min(len(index.contigs[c]) - 1 - p, L - k - i)  # @line L7
            if d > 0 and read[i + d:i + d + k] == index.kmer_at(c, p + d):  # @line L8
                i = i + d + 1
            else:
                i = i + 1
        else:
            i = i + 1  # @line L9
    return E if E is not None else frozenset()  # @line L10


def naive_pseudoalign(index: PseudoIndex, read: str) -> Color:
    """The same set computed by looking up every k-mer of the read."""
    E: Optional[Color] = None
    for x in kmers(read, index.k):
        if x in index.color:
            E = index.color[x] if E is None else E & index.color[x]
    return E if E is not None else frozenset()


def equivalence_classes(index: PseudoIndex, reads: Iterable[str]) -> List[Tuple[Tuple[int, ...], int]]:
    """Count the reads by their compatible set. Reads with an empty set are left out."""
    counts: Counter = Counter()
    for r in reads:
        e = pseudoalign(index, r)
        if e:
            counts[tuple(sorted(e))] += 1
    return sorted(counts.items())
test_pseudoalignment.py 146 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/pseudoalignment/. The authors are listed in prov/6KKBA9.jsonl.

import random

from bioseq import mutate, random_dna, revcomp, simulate_reads
from pseudoalignment import PseudoIndex, equivalence_classes, naive_pseudoalign, pseudoalign

X, E, Y = "CAGAACC", "TGCTGT", "GACATAA"


def spell(run):
    return run[0] + "".join(x[-1] for x in run[1:])


def test_worked_example():
    t = [X + E + Y, X + Y]
    idx = PseudoIndex(t, 5)
    forward = {spell(c): sorted(col) for c, col in zip(idx.contigs, idx.contig_color)}
    assert forward["CAGAACC"] == [0, 1]
    assert forward["AACCTGCTGTGACA"] == [0]
    assert forward["AACCGACA"] == [1]
    assert forward["GACATAA"] == [0, 1]
    assert len(idx.contigs) == 8
    read = t[0][1:19]
    assert read == "AGAACCTGCTGTGACATA"
    trace = []
    assert pseudoalign(idx, read, trace) == {0}
    assert trace == [0, 2, 12]
    trace = []
    assert pseudoalign(idx, t[1], trace) == {1}
    assert trace == [0, 3, 7]
    # The reverse strand gives the same set.
    assert pseudoalign(idx, revcomp(read)) == {0}
    # A read that holds only shared k-mers fits both.
    assert pseudoalign(idx, X) == {0, 1}
    # A read with no k-mer in the index is not mapped.
    assert pseudoalign(idx, "TTTTTTTTTT") == frozenset()


def random_transcripts(rng):
    exons = [random_dna(rng, rng.randint(8, 30)) for _ in range(rng.randint(3, 6))]
    out = []
    for _ in range(rng.randint(2, 5)):
        pick = [e for e in exons if rng.random() < 0.6] or [exons[0]]
        out.append("".join(pick))
    return out


def check_contigs(idx):
    seen = set()
    for c, col in zip(idx.contigs, idx.contig_color):
        for a, b in zip(c, c[1:]):
            assert a[1:] == b[:-1]
            assert idx.successors(a) == [b] and idx.predecessors(b) == [a]
        for x in c:
            assert idx.color[x] == col and x not in seen
            seen.add(x)
    assert seen == set(idx.color)


def test_contigs_partition_the_kmers():
    rng = random.Random(1)
    for _ in range(150):
        t = random_transcripts(rng)
        check_contigs(PseudoIndex(t, rng.choice([3, 4, 5, 7])))


def test_error_free_reads_equal_naive_and_hold_the_source():
    rng = random.Random(2)
    for _ in range(80):
        t = random_transcripts(rng)
        k = rng.choice([5, 7, 9])
        idx = PseudoIndex(t, k)
        for src, seq in enumerate(t):
            if len(seq) < 12:
                continue
            for r in simulate_reads(rng, seq, 10, min(len(seq), 25), 0.0):
                got = pseudoalign(idx, r.read)
                assert got == naive_pseudoalign(idx, r.read)
                assert src in got


def test_reads_with_errors_give_a_superset_of_naive():
    rng = random.Random(3)
    for _ in range(80):
        t = random_transcripts(rng)
        idx = PseudoIndex(t, rng.choice([3, 4, 5]))
        for seq in t:
            if len(seq) < 12:
                continue
            for r in simulate_reads(rng, seq, 10, min(len(seq), 25), 0.08):
                assert pseudoalign(idx, r.read) >= naive_pseudoalign(idx, r.read)


def test_naive_set_holds_exactly_the_transcripts_with_all_kmers():
    rng = random.Random(4)
    for _ in range(60):
        t = random_transcripts(rng)
        k = 6
        idx = PseudoIndex(t, k)
        for _ in range(10):
            src = rng.randrange(len(t))
            seq = t[src]
            if len(seq) < 15:
                continue
            a = rng.randrange(len(seq) - 14)
            read = seq[a:a + 15]
            want = {j for j, s in enumerate(t)
                    if all(x in s or x in revcomp(s) for x in (read[i:i + k] for i in range(15 - k + 1)))}
            assert naive_pseudoalign(idx, read) == want == pseudoalign(idx, read)


def test_skipping_saves_lookups():
    rng = random.Random(5)
    t = [random_dna(rng, 300) for _ in range(3)]
    t.append(t[0][:150] + t[1][150:])
    idx = PseudoIndex(t, 21)
    total = lookups = 0
    for seq in t:
        for r in simulate_reads(rng, seq, 50, 100, 0.0):
            trace = []
            pseudoalign(idx, r.read, trace)
            lookups += len(trace)
            total += 100 - 21 + 1
    assert lookups * 5 < total


def test_equivalence_classes():
    t = [X + E + Y, X + Y]
    idx = PseudoIndex(t, 5)
    reads = [X + E + Y, X + Y, X, Y, "TTTTTTTT", revcomp(X + Y)]
    assert equivalence_classes(idx, reads) == [((0,), 1), ((0, 1), 2), ((1,), 2)]


def test_cycles_are_cut():
    # A transcript made of a repeated unit gives a cycle of k-mers with no branch.
    idx = PseudoIndex(["ACGTTACGTTACGTT"], 4)
    check_contigs(idx)
    rng = random.Random(6)
    for _ in range(50):
        unit = random_dna(rng, rng.randint(5, 9))
        idx = PseudoIndex([unit * 4], 4)
        check_contigs(idx)
        read = mutate(rng, (unit * 4)[2:2 + 2 * len(unit)], 0.0)
        assert pseudoalign(idx, read) == naive_pseudoalign(idx, read) == {0}

History

Iqbal, Caccamo, Turner, Flicek and McVean (2012) introduced the colored de Bruijn graph, which labels each k-mer with the samples that contain it, for variant calling. Patro, Mount and Kingsford (2014) quantified transcripts from k-mer counts in Sailfish, without alignment. Bray, Pimentel, Melsted and Pachter (2016) defined pseudoalignment in kallisto: the colored de Bruijn graph of the transcriptome, the intersection of k-compatibility classes, the skip to the end of a contig, and the EM on equivalence classes. Srivastava, Sarkar, Gupta and Patro (2016) gave quasi-mapping in RapMap, and later work in Salmon moved to selective alignment.

References

  1. Nicolas L. Bray, Harold Pimentel, Páll Melsted and Lior Pachter, Near-optimal probabilistic RNA-seq quantification, Nature Biotechnology 34(5) (2016), pp. 525 to 527 and Online Methods (the transcriptome de Bruijn graph, k-compatibility classes, skipping along contigs, and the EM on equivalence classes)
  2. Zamin Iqbal, Mario Caccamo, Isaac Turner, Paul Flicek and Gil McVean, De novo assembly and genotyping of variants using colored de Bruijn graphs, Nature Genetics 44(2) (2012), pp. 226 to 232 (the colored de Bruijn graph)
  3. Rob Patro, Stephen M. Mount and Carl Kingsford, Sailfish enables alignment-free isoform quantification from RNA-seq reads using lightweight algorithms, Nature Biotechnology 32(5) (2014), pp. 462 to 464 (quantification from k-mer counts without alignment)
  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 (equivalence classes in a lightweight mapping method)
  5. 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 (where reads mapped without alignment go wrong)

Where this leads

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