Algorithm Search⌘K

Algorithmcore

EM isoform quantification

Also called RSEM algorithm.

Estimate isoform abundances by EM: share each multi-mapping read among its transcripts in proportion to the current abundances, then re-estimate the abundances from the shares.

Time
O(T·(R+m)) worst
Space
O(m) extra
Where
R = the total size of the equivalence classes, the sum of |e| over all classes; T = the number of iterations; m = the number of transcripts
Properties
deterministicnot exactofflineiterative
Origin
Bo Li, Victor Ruotti, Ron M. Stewart, James A. Thomson, Colin N. Dewey, 2010

EM isoform quantification estimates how much of each transcript is in an RNA sample when many reads fit more than one transcript. The isoforms of a gene share exons, so a read from a shared exon cannot be given to one of them by its sequence alone. The expectation-maximization algorithm solves this with a loop: share each read among the transcripts it fits, in proportion to their current abundances and lengths, then set each abundance to the fraction of reads it received. Each round increases the likelihood of the reads. The likelihood is concave in the abundances, so a fixed point with no zero abundance is a global maximum, but the maximum is not always unique. This is the core of RSEM, and kallisto and Salmon run the same loop on equivalence classes of reads.

In plain words

Two songs share the same chorus. You hear the chorus 40 times on the radio, the verse that only song A has 30 times, and the verse that only song B has 30 times. How many times was each song played?

You cannot tell which song each chorus came from. So you make a guess, for example that both songs were played equally often. With that guess you split the 40 choruses between the two songs. Now each song has a total, and the totals give you a better guess. Split the choruses again with the new guess, and repeat.

The guesses settle down quickly. A short song gives fewer pieces each time it plays, so the split also takes the length of each song into account.

The problem

There are mm transcripts with ids 1,…,m1, \ldots, m and effective lengths ℓt>0\ell_t > 0. The effective length is the number of positions where a fragment can start, often ℓt=lent−μ+1\ell_t = \mathrm{len}_t - \mu + 1 for a mean fragment length μ\mu. Each read was mapped by pseudoalignment, selective alignment or a read mapper to the set of transcripts it is compatible with. Reads with the same set form an equivalence class ee, and cec_e is the number of reads in it. N=∑eceN = \sum_e c_e.

The model: a read comes from transcript tt with probability αt\alpha_t, and then from one of the ℓt\ell_t start positions of tt with equal probability. The probability of a read in class ee is ∑t∈eαt/ℓt\sum_{t \in e} \alpha_t / \ell_t, so

log⁡L(α)=∑ecelog⁡∑t∈eαtℓt.\log L(\alpha) = \sum_e c_e \log \sum_{t \in e} \frac{\alpha_t}{\ell_t}.

The task is to find α\alpha in the simplex that maximizes log⁡L\log L. This is the maximum likelihood estimate of the mixture weights of a mixture whose components are fixed. The transcript fractions are τt=(αt/ℓt)/∑u(αu/ℓu)\tau_t = (\alpha_t / \ell_t) / \sum_u (\alpha_u / \ell_u), and transcripts per million are 106τt10^6 \tau_t.

The algorithm

The pseudocode numbers transcripts from 1; the code numbers them from 0.

  1. EM-ABUNDANCE(classes e with counts c_e, lengths ℓ, iterations T, tolerance ε)
  2. 1α_t ← 1/m for each transcript t
  3. 2for iter ← 1 to T do
  4. 3n_t ← 0 for each t
  5. 4for each class e do
  6. 5s ← Σ_{u in e} α_u / ℓ_u
  7. 6for each t in e: n_t ← n_t + c_e · (α_t / ℓ_t) / s
  8. 7α'_t ← n_t / N for each t
  9. 8if max_t |α'_t - α_t| < ε then return α'
  10. 9α ← α'
  11. 10return α

Lines L5 and L6 are the E step. The share ce(αt/ℓt)/sc_e (\alpha_t / \ell_t) / s is the expected number of reads of class ee that came from tt, given the current α\alpha. Line L7 is the M step: with the expected counts fixed, the best weights are the counts divided by NN. Line L1 starts with every αt>0\alpha_t > 0. This matters, because a zero never becomes positive again in line L6.

The loop works on classes, not on reads. Reads with the same compatible set get the same share in line L6, so one class with count cec_e does the work of cec_e reads. In practice the number of classes is much smaller than the number of reads (a measurement, not a bound), so each round is fast.

Example

Transcript A has effective length 1000 and transcript B has effective length 500. There are 100 reads: 30 fit only A, 30 fit only B, and 40 fit both. So the classes are {A}\{A\} with 30 reads, {A,B}\{A, B\} with 40 and {B}\{B\} with 30.

round αA\alpha_A αB\alpha_B shared reads given to A log⁡L\log L
0 (start) 0.5000 0.5000 13.33 -695.3513
1 0.4333 0.5667 11.06 -694.1501
2 0.4106 0.5894 10.33 -694.0105
3 0.4033 0.5967 10.10 -693.9961
4 0.4010 0.5990 10.03 -693.9946
5 0.4003 0.5997 10.01 -693.9945

In round 0, line L5 gives s=0.5/1000+0.5/500=0.0015s = 0.5/1000 + 0.5/500 = 0.0015, and line L6 gives A the share 0.0005/0.0015=1/30.0005 / 0.0015 = 1/3 of the 40 shared reads, so nA=30+13.33n_A = 30 + 13.33 and αA=0.4333\alpha_A = 0.4333. B is shorter, so at equal α\alpha each of its positions is twice as likely, and B gets two thirds of the shared reads. The values approach α=(0.4,0.6)\alpha = (0.4, 0.6), and with ε=10−10\varepsilon = 10^{-10} line L8 stops after 19 rounds.

The limit is the maximum. With αB=1−αA\alpha_B = 1 - \alpha_A, log⁡L\log L is 30log⁡αA+40log⁡(2−αA)+30log⁡(1−αA)30 \log \alpha_A + 40 \log(2 - \alpha_A) + 30 \log(1 - \alpha_A) plus a constant, and its derivative 30/αA−40/(2−αA)−30/(1−αA)30/\alpha_A - 40/(2 - \alpha_A) - 30/(1 - \alpha_A) is 75−25−50=075 - 25 - 50 = 0 at αA=0.4\alpha_A = 0.4. In transcript fractions, αA/ℓA=0.0004\alpha_A / \ell_A = 0.0004 and αB/ℓB=0.0012\alpha_B / \ell_B = 0.0012, so the TPM values are 250000 for A and 750000 for B. A has 40% of the reads but only 25% of the molecules, because it is twice as long.

Correctness

The proof shows three facts. Monotonicity (a theorem): each round satisfies log⁡L(α′)−log⁡L(α)≥N⋅KL(α′∥α)≥0\log L(\alpha') - \log L(\alpha) \ge N \cdot \mathrm{KL}(\alpha' \| \alpha) \ge 0, by Jensen's inequality applied to each class, with equality only at a fixed point. Global maximum (a theorem): log⁡L\log L is concave, because each class adds the log of a linear function. At a fixed point with all αt>0\alpha_t > 0, every partial derivative equals NN, so the tangent plane is flat on the simplex and the fixed point is a global maximum. Li, Ruotti, Stewart, Thomson and Dewey (2010) state the concavity and conclude that EM finds the maximum likelihood values. Limits: a fixed point with a zero can be far from the maximum, and two transcripts of the same length in the same classes give a whole segment of maxima, so the answer then depends on the start.

Proof: EM for transcript abundances never lowers the likelihood, and each fixed point with full support is a global maximumfull

We use the pseudocode of the page. There are mm transcripts with effective lengths ℓt>0\ell_t > 0. The reads are grouped into equivalence classes: a class ee is a nonempty set of transcripts and ce>0c_e > 0 is the number of reads in it. N=∑eceN = \sum_e c_e. The parameter α\alpha is in the simplex Δ={α:αt≥0,∑tαt=1}\Delta = \{\alpha : \alpha_t \ge 0, \sum_t \alpha_t = 1\}, and αt\alpha_t is the probability that a read comes from transcript tt. For a class ee let

pe(α)=∑t∈eαtℓt,log⁡L(α)=∑ecelog⁡pe(α).p_e(\alpha) = \sum_{t \in e} \frac{\alpha_t}{\ell_t}, \qquad \log L(\alpha) = \sum_e c_e \log p_e(\alpha).

The set D={α∈Δ:pe(α)>0 for every class e}D = \{\alpha \in \Delta : p_e(\alpha) > 0 \text{ for every class } e\} is where log⁡L\log L is finite. One round of lines L3 to L7 maps α∈D\alpha \in D to α′=M(α)\alpha' = M(\alpha) with

re,t=αt/ℓtpe(α) (t∈e),nt=∑e∋tce re,t,αt′=ntN.r_{e,t} = \frac{\alpha_t / \ell_t}{p_e(\alpha)} \ (t \in e), \qquad n_t = \sum_{e \ni t} c_e\, r_{e,t}, \qquad \alpha'_t = \frac{n_t}{N}.

1. The iterates are well defined

Lemma 1. If α∈D\alpha \in D, then α′∈Δ\alpha' \in \Delta, and αt′>0\alpha'_t > 0 for every transcript tt that is in some class and has αt>0\alpha_t > 0. In particular, the iterates that start at the uniform point of line L1 stay in DD.

Proof. For each class, ∑t∈ere,t=1\sum_{t \in e} r_{e,t} = 1 by the definition of pep_e. So ∑tnt=∑ece=N\sum_t n_t = \sum_e c_e = N and ∑tαt′=1\sum_t \alpha'_t = 1, and all nt≥0n_t \ge 0. If t∈et \in e and αt>0\alpha_t > 0, then re,t>0r_{e,t} > 0 and nt≥cere,t>0n_t \ge c_e r_{e,t} > 0. The uniform start has αt=1/m>0\alpha_t = 1/m > 0 for all tt, so after each round every transcript that is in a class keeps a positive value, by induction. Each class holds at least one transcript, so pe>0p_e > 0 for every class, and the next iterate is in DD. □\square

2. The likelihood never decreases

Lemma 2. For α∈D\alpha \in D and every β∈Δ\beta \in \Delta with βt>0\beta_t > 0 wherever nt>0n_t > 0,

log⁡L(β)−log⁡L(α) ≥ ∑t:nt>0ntlog⁡βtαt.\log L(\beta) - \log L(\alpha) \ \ge\ \sum_{t : n_t > 0} n_t \log \frac{\beta_t}{\alpha_t}.

Proof. Fix a class ee. Only the members t∈et \in e with αt>0\alpha_t > 0 have re,t>0r_{e,t} > 0, and these weights sum to 1. Then

pe(β)pe(α) ≥ ∑t∈e, αt>0βt/ℓtpe(α)=∑t∈e, αt>0re,t βtαt.\frac{p_e(\beta)}{p_e(\alpha)} \ \ge\ \sum_{t \in e,\ \alpha_t > 0} \frac{\beta_t/\ell_t}{p_e(\alpha)} = \sum_{t \in e,\ \alpha_t > 0} r_{e,t}\, \frac{\beta_t}{\alpha_t}.

The logarithm is concave, so by Jensen's inequality the log of this weighted mean is at least the weighted mean of the logs:

log⁡pe(β)−log⁡pe(α) ≥ ∑t∈e, αt>0re,tlog⁡βtαt.\log p_e(\beta) - \log p_e(\alpha) \ \ge\ \sum_{t \in e,\ \alpha_t > 0} r_{e,t} \log \frac{\beta_t}{\alpha_t}.

Multiply by cec_e and add over all classes. The coefficient of log⁡(βt/αt)\log(\beta_t / \alpha_t) is ∑e∋tcere,t=nt\sum_{e \ni t} c_e r_{e,t} = n_t. □\square

Theorem 1 (monotonicity). For α∈D\alpha \in D and α′=M(α)\alpha' = M(\alpha),

log⁡L(α′)−log⁡L(α) ≥ N⋅KL(α′ ∥ α) ≥ 0,\log L(\alpha') - \log L(\alpha) \ \ge\ N \cdot \mathrm{KL}(\alpha' \,\|\, \alpha) \ \ge\ 0,

with equality only if α′=α\alpha' = \alpha.

Proof. Put β=α′\beta = \alpha' in Lemma 2. Then βt=nt/N>0\beta_t = n_t / N > 0 wherever nt>0n_t > 0, and nt=Nαt′n_t = N \alpha'_t, so the right side is N∑tαt′log⁡(αt′/αt)=N⋅KL(α′∥α)N \sum_t \alpha'_t \log(\alpha'_t / \alpha_t) = N \cdot \mathrm{KL}(\alpha' \| \alpha), with 0log⁡0=00 \log 0 = 0. The Kullback-Leibler divergence of two distributions is at least 0 and is 0 only when they are equal (Gibbs' inequality). □\square

Lemma 2 also explains line L7. For fixed counts ntn_t, the function β↦∑tntlog⁡βt\beta \mapsto \sum_t n_t \log \beta_t on Δ\Delta is largest at βt=nt/N\beta_t = n_t / N, again by Gibbs' inequality. So line L7 maximizes the lower bound of Lemma 2, which is the M step of the EM algorithm, and the E step is the computation of the re,tr_{e,t} in lines L5 and L6.

The values log⁡L(α(k))\log L(\alpha^{(k)}) form a nondecreasing sequence. They are bounded above, because pe(α)≤max⁡t1/ℓtp_e(\alpha) \le \max_t 1/\ell_t for all α∈Δ\alpha \in \Delta. So the sequence of likelihood values converges. This proof does not show that the iterates themselves converge, and line L8 is a practical stopping rule, not part of the theory.

3. A fixed point with full support is a global maximum

Theorem 2. log⁡L\log L is concave on DD. If α∈D\alpha \in D is a fixed point, M(α)=αM(\alpha) = \alpha, and αt>0\alpha_t > 0 for every tt, then log⁡L(α)≥log⁡L(β)\log L(\alpha) \ge \log L(\beta) for every β∈Δ\beta \in \Delta.

Proof. Each pep_e is a linear function of α\alpha, and log⁡\log is concave and increasing, so each celog⁡pec_e \log p_e is concave on the convex set DD, and so is their sum.

The partial derivatives at α∈D\alpha \in D are

gt=∂log⁡L∂αt=∑e∋tceℓt pe(α),soαtgt=∑e∋tcere,t=nt.g_t = \frac{\partial \log L}{\partial \alpha_t} = \sum_{e \ni t} \frac{c_e}{\ell_t\, p_e(\alpha)}, \qquad \text{so} \qquad \alpha_t g_t = \sum_{e \ni t} c_e r_{e,t} = n_t.

At a fixed point, nt=Nαtn_t = N \alpha_t for all tt. Where αt>0\alpha_t > 0 this gives gt=Ng_t = N. With full support, gt=Ng_t = N for all tt.

Take β∈D\beta \in D. A concave differentiable function lies below its tangent plane, so

log⁡L(β) ≤ log⁡L(α)+∑tgt(βt−αt)=log⁡L(α)+N(∑tβt−∑tαt)=log⁡L(α).\log L(\beta) \ \le\ \log L(\alpha) + \sum_t g_t (\beta_t - \alpha_t) = \log L(\alpha) + N \Big(\sum_t \beta_t - \sum_t \alpha_t\Big) = \log L(\alpha).

For β∈Δ∖D\beta \in \Delta \setminus D some pe(β)=0p_e(\beta) = 0 and log⁡L(β)=−∞\log L(\beta) = -\infty. □\square

4. What is not true

Fixed points with a zero can be poor. Take three transcripts of the same length ℓ\ell, and the classes {1,2}\{1, 2\} and {1,3}\{1, 3\} with 10 reads each. At α=(0,12,12)\alpha = (0, \tfrac12, \tfrac12) the counts are n=(0,10,10)n = (0, 10, 10), so M(α)=αM(\alpha) = \alpha. But log⁡L(0,12,12)=20log⁡12ℓ\log L(0, \tfrac12, \tfrac12) = 20 \log \frac{1}{2\ell} and log⁡L(1,0,0)=20log⁡1ℓ\log L(1, 0, 0) = 20 \log \frac1\ell, which is larger. A zero never becomes positive again in line L6, so EM cannot leave this point. This is why line L1 starts with every αt>0\alpha_t > 0. Theorem 2 needs full support at the fixed point, and a limit of EM can still have zeros.

The maximum need not be unique. If two transcripts uu and vv have ℓu=ℓv\ell_u = \ell_v and are in exactly the same classes, then pep_e depends only on αu+αv\alpha_u + \alpha_v. Every split of that sum gives the same likelihood, so the maxima form a segment. The concavity of Theorem 2 is not strict, and EM returns the split that its start point gives. Li, Ruotti, Stewart, Thomson and Dewey (2010) describe this case as a plateau of the likelihood surface. ■\blacksquare

Complexity

Let R=∑e∣e∣R = \sum_e |e| be the total size of the classes. One round reads each class twice, in lines L5 and L6, and touches each transcript in lines L3, L7 and L8, so it costs O(R+m)O(R + m) arithmetic operations in the real RAM. TT rounds cost O(T(R+m))O(T (R + m)). The extra space is O(m)O(m) for nn and α′\alpha', on top of the input.

The number of rounds is the weak part. EM converges linearly, and the rate is slow when two transcripts are nearly indistinguishable, because the likelihood is then almost flat along one direction. Tools stop on a relative change of the abundances, or after a fixed cap of rounds. Building the classes costs one pass over the reads, and a hash table of compatible sets, before the loop starts.

Properties

  • Increases the likelihood every round (a theorem, Section 2 of the proof).
  • Stays in the simplex. Every iterate is a probability vector, with no projection step.
  • Exact at the limit only. The output is an approximation after finitely many rounds; the limit of the likelihood values exists, but this page does not prove that the iterates converge.
  • Deterministic. The uniform start fixes the result, also on a ridge of equal maxima.
  • Works on summaries. Only the classes and their counts are used, not the reads.

Variants and improvements

  • Read-level EM with a noise transcript. Li and others (2010) give each read its own probability for each alignment, from base qualities and positions, and add a transcript θ0\theta_0 for reads from nowhere. The loop is the same, with the per-read probability in place of 1/ℓt1/\ell_t.
  • RSEM. Li and Dewey (2011) add fragment length models, effective lengths, paired-end reads, and credibility intervals: a Gibbs sampler draws read assignments and abundance vectors from the posterior.
  • Equivalence classes. kallisto runs the EM on classes of reads with the same compatible set. Salmon uses rich equivalence classes that also keep, for each transcript of the class, an average conditional probability, so position and bias weights survive the grouping.
  • Online and variational inference. Salmon first updates the abundances while it streams the reads, then runs an offline EM or variational Bayes EM on the classes. Variational Bayes adds a prior on the abundances, and the strength of the prior changes how many small abundances end near zero.
  • Bias models. Salmon corrects the effective lengths for sequence bias at fragment ends and for the GC content of fragments.

When to use it

Use it whenever reads fit more than one transcript, which is the normal case for genes with several isoforms. It is the standard last step after pseudoalignment or selective alignment, and its classes come for free from those mappers. Counting only the reads unique to each transcript throws away the shared exons and biases the result toward transcripts with long unique parts. When you need uncertainty, add bootstrap samples over reads, as kallisto does, or Gibbs sampling, as RSEM and Salmon do; the point estimate alone hides a flat likelihood.

Pitfalls

  • Starting with zeros. If line L1 sets some αt=0\alpha_t = 0, line L6 never gives that transcript a read, and the result can be a poor fixed point. Start with every αt>0\alpha_t > 0.
  • Raw lengths in line L5. Using the full transcript length instead of the effective length overweights long transcripts against short ones, and short transcripts near the fragment length get the largest error. Use ℓt=max⁡(lent−μ+1,1)\ell_t = \max(\mathrm{len}_t - \mu + 1, 1) or the full fragment length distribution.
  • Reading α\alpha as expression. α\alpha is a fraction of reads, not of molecules. Report τ\tau or TPM, which divide by ℓt\ell_t first.
  • Trusting one answer on a ridge. If two transcripts are in the same classes, the split between them is not fixed by the data. Report their sum, or the uncertainty, not the split.
  • A loose stop in line L8. An absolute tolerance on large αt\alpha_t stops too late for small ones. Use a relative change on transcripts above a small floor.

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.

em_isoform_quantification.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/em-isoform-quantification/. The authors are listed in prov/QSYASY.jsonl.

"""EM estimation of transcript abundances from read equivalence classes.

The model is the one of RSEM without the noise transcript and without
sequence or position bias. There are m transcripts with ids 0 to m - 1 and
effective lengths eff_len[t] > 0. A read comes from transcript t with
probability alpha[t], and then from one of its eff_len[t] start positions with
equal probability. A read is summarized by the set of transcripts it is
compatible with (its equivalence class e), and the likelihood of the reads is

    L(alpha) = prod over classes e of (sum over t in e of alpha[t] / eff_len[t]) ** c_e,

where c_e is the number of reads in class e. Classes are lists of
(transcripts, count) pairs, where transcripts is a tuple of distinct ids.
An empty tuple (an unmapped read) is skipped.
"""

from __future__ import annotations

import math
from typing import Dict, Iterable, List, Optional, Sequence, Tuple

Classes = Sequence[Tuple[Tuple[int, ...], float]]


def effective_length(length: int, mean_frag: float) -> float:
    """The number of start positions of a fragment of the mean length, at least 1."""
    return max(length - mean_frag + 1.0, 1.0)


def equivalence_classes(read_sets: Iterable[Iterable[int]]) -> List[Tuple[Tuple[int, ...], int]]:
    """Group reads by their compatible sets: a sorted list of (sorted tuple, count)."""
    counts: Dict[Tuple[int, ...], int] = {}
    for s in read_sets:
        key = tuple(sorted(set(s)))
        counts[key] = counts.get(key, 0) + 1
    return sorted(counts.items())


def log_likelihood(alpha: Sequence[float], classes: Classes, eff_len: Sequence[float]) -> float:
    """log L(alpha); minus infinity if a class with reads gets probability 0."""
    total = 0.0
    for e, c in classes:
        if not e or c == 0:
            continue
        s = sum(alpha[u] / eff_len[u] for u in e)
        if s <= 0.0:
            return -math.inf
        total += c * math.log(s)
    return total


def em(classes: Classes, eff_len: Sequence[float], max_iter: int = 10000,
       eps: float = 1e-10, trace: Optional[List[float]] = None) -> List[float]:
    """Return the read fractions alpha after EM from the uniform start.

    The loop stops when no alpha[t] moves by eps or more, or after max_iter
    rounds. If trace is a list, the log-likelihood of each iterate is appended.
    """
    m = len(eff_len)
    live = [(e, c) for e, c in classes if e and c > 0]
    n_reads = sum(c for _, c in live)
    if m == 0 or n_reads == 0:
        raise ValueError("need at least one transcript and one mapped read")
    alpha = [1.0 / m] * m  # @line L1
    if trace is not None:
        trace.append(log_likelihood(alpha, live, eff_len))
    for _ in range(max_iter):  # @line L2
        n = [0.0] * m  # @line L3
        for e, c in live:  # @line L4
            s = sum(alpha[u] / eff_len[u] for u in e)  # @line L5
            for t in e:
                n[t] += c * (alpha[t] / eff_len[t]) / s  # @line L6
        new = [x / n_reads for x in n]  # @line L7
        if trace is not None:
            trace.append(log_likelihood(new, live, eff_len))
        if max(abs(a - b) for a, b in zip(new, alpha)) < eps:  # @line L8
            return new
        alpha = new  # @line L9
    return alpha  # @line L10


def transcript_fractions(alpha: Sequence[float], eff_len: Sequence[float]) -> List[float]:
    """tau[t]: the fraction of transcript molecules, alpha[t] / eff_len[t] normalized to sum 1."""
    rho = [a / l for a, l in zip(alpha, eff_len)]
    s = sum(rho)
    return [r / s for r in rho]


def tpm(alpha: Sequence[float], eff_len: Sequence[float]) -> List[float]:
    """Transcripts per million: 10**6 times the transcript fractions."""
    return [1e6 * x for x in transcript_fractions(alpha, eff_len)]
test_em_isoform_quantification.py 119 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/em-isoform-quantification/. The authors are listed in prov/QSYASY.jsonl.

import random

from em_isoform_quantification import (effective_length, em, equivalence_classes,
                                       log_likelihood, tpm, transcript_fractions)


def random_case(rng: random.Random, m: int, n_classes: int):
    eff_len = [float(rng.randint(50, 2000)) for _ in range(m)]
    classes = []
    for _ in range(n_classes):
        e = tuple(sorted(rng.sample(range(m), rng.randint(1, m))))
        classes.append((e, rng.randint(1, 50)))
    return classes, eff_len


def test_tpm_check_values():
    # Lengths 1000, 2000 and 500 with 100 reads each: alpha is 1/3 each.
    out = tpm([1 / 3, 1 / 3, 1 / 3], [1000, 2000, 500])
    assert [round(x) for x in out] == [285714, 142857, 571429]
    assert abs(sum(out) - 1e6) < 1e-6


def test_unique_reads_give_the_counts():
    # Every read is unique to one transcript: EM returns the read fractions.
    alpha = em([((0,), 30), ((1,), 50), ((2,), 20)], [100.0, 200.0, 300.0])
    assert all(abs(a - b) < 1e-9 for a, b in zip(alpha, [0.3, 0.5, 0.2]))


def test_worked_example():
    # The example of the page: A has length 1000, B has length 500.
    classes = [((0,), 30), ((0, 1), 40), ((1,), 30)]
    trace = []
    alpha = em(classes, [1000.0, 500.0], trace=trace)
    assert abs(alpha[0] - 0.4) < 1e-6 and abs(alpha[1] - 0.6) < 1e-6
    assert [round(x) for x in tpm(alpha, [1000.0, 500.0])] == [250000, 750000]
    assert abs(trace[0] - log_likelihood([0.5, 0.5], classes, [1000.0, 500.0])) < 1e-12


def test_two_transcripts_against_ternary_search():
    rng = random.Random(1)
    for _ in range(300):
        classes, eff_len = random_case(rng, 2, 3)
        alpha = em(classes, eff_len, max_iter=3000)
        f = lambda x: log_likelihood([x, 1 - x], classes, eff_len)
        lo, hi = 0.0, 1.0
        for _ in range(200):
            a, b = lo + (hi - lo) / 3, hi - (hi - lo) / 3
            if f(a) < f(b):
                lo = a
            else:
                hi = b
        best = max(f(lo), f(0.0), f(1.0))
        assert log_likelihood(alpha, classes, eff_len) >= best - 1e-6


def test_three_transcripts_against_a_grid():
    rng = random.Random(2)
    steps = 40
    grid = [(i / steps, j / steps, (steps - i - j) / steps)
            for i in range(steps + 1) for j in range(steps + 1 - i)]
    for _ in range(150):
        classes, eff_len = random_case(rng, 3, 4)
        alpha = em(classes, eff_len, max_iter=3000)
        best = max(log_likelihood(g, classes, eff_len) for g in grid)
        assert log_likelihood(alpha, classes, eff_len) >= best - 1e-6
        assert abs(sum(alpha) - 1.0) < 1e-9 and min(alpha) >= 0.0


def test_likelihood_never_decreases():
    rng = random.Random(3)
    for _ in range(200):
        classes, eff_len = random_case(rng, rng.randint(2, 6), rng.randint(1, 8))
        trace = []
        em(classes, eff_len, max_iter=200, trace=trace)
        for a, b in zip(trace, trace[1:]):
            assert b >= a - 1e-9 * max(1.0, abs(a))


def test_ridge_when_classes_do_not_separate():
    # Every read fits both transcripts and the lengths are equal: every split is a maximum.
    classes = [((0, 1), 100)]
    alpha = em(classes, [500.0, 500.0])
    assert alpha == [0.5, 0.5]
    assert abs(log_likelihood([0.2, 0.8], classes, [500.0, 500.0])
               - log_likelihood(alpha, classes, [500.0, 500.0])) < 1e-9


def test_simulated_reads():
    # Segments of the genome and the transcripts that contain each of them.
    segments = [(300, (0, 1)), (200, (0,)), (400, (1, 2)), (100, (2,))]
    lengths = [sum(n for n, ts in segments if t in ts) for t in range(3)]
    true_alpha = [0.5, 0.2, 0.3]
    rng = random.Random(4)
    reads = []
    for _ in range(20000):
        u, t = rng.random(), 0
        while u >= sum(true_alpha[:t + 1]):
            t += 1
        x = rng.random() * lengths[t]
        for n, ts in segments:
            if t in ts:
                if x < n:
                    reads.append(ts)
                    break
                x -= n
    classes = equivalence_classes(reads)
    assert [e for e, _ in classes] == [(0,), (0, 1), (1, 2), (2,)]
    alpha = em(classes, [float(x) for x in lengths])
    assert all(abs(a - b) < 0.02 for a, b in zip(alpha, true_alpha))


def test_helpers():
    assert effective_length(1000, 200) == 801.0
    assert effective_length(150, 200) == 1.0
    assert equivalence_classes([[1, 0], [0, 1], [2], []]) == [((), 1), ((0, 1), 2), ((2,), 1)]
    assert abs(sum(transcript_fractions([0.2, 0.8], [10.0, 40.0])) - 1.0) < 1e-12

History

Dempster, Laird and Rubin (1977) gave the EM algorithm in general form. Jiang and Wong (2009) wrote the likelihood of isoform abundances under a Poisson model of reads. Li, Ruotti, Stewart, Thomson and Dewey (2010) gave the read-level EM with multi-mapping reads and a noise isoform, and noted that the likelihood is concave. Trapnell and others (2010) maximized a similar likelihood in Cufflinks. Li and Dewey (2011) released RSEM with effective lengths, TPM and credibility intervals. Bray, Pimentel, Melsted and Pachter (2016) ran the EM on equivalence classes from pseudoalignment in kallisto, and Patro, Duggal, Love, Irizarry and Kingsford (2017) added online inference and bias models in Salmon.

References

  1. Bo Li, Victor Ruotti, Ron M. Stewart, James A. Thomson and Colin N. Dewey, RNA-Seq gene expression estimation with read mapping uncertainty, Bioinformatics 26(4) (2010), pp. 493 to 500, Section 2.2 (inference with the EM algorithm; the likelihood is concave; the plateau when isoforms cannot be told apart)
  2. Bo Li and Colin N. Dewey, RSEM, accurate transcript quantification from RNA-Seq data with or without a reference genome, BMC Bioinformatics 12 (2011), Article 323, Methods (the model, effective length, TPM and credibility intervals by Gibbs sampling)
  3. A. P. Dempster, N. M. Laird and D. B. Rubin, Maximum likelihood from incomplete data via the EM algorithm, Journal of the Royal Statistical Society Series B 39(1) (1977), pp. 1 to 22
  4. Hui Jiang and Wing Hung Wong, Statistical inferences for isoform expression in RNA-Seq, Bioinformatics 25(8) (2009), pp. 1026 to 1032
  5. 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 (the EM on equivalence classes)
  6. 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, Online Methods (online inference, then offline EM or variational Bayes on rich equivalence classes)

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