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
- Model
- Real RAM
- Properties
- deterministicnot exactofflineiterative
- Evidence
- Proof sketchCode in 1 languages
- 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 transcripts with ids and effective lengths . The effective length is the number of positions where a fragment can start, often for a mean fragment length . 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 , and is the number of reads in it. .
The model: a read comes from transcript with probability , and then from one of the start positions of with equal probability. The probability of a read in class is , so
The task is to find in the simplex that maximizes . This is the maximum likelihood estimate of the mixture weights of a mixture whose components are fixed. The transcript fractions are , and transcripts per million are .
The algorithm
The pseudocode numbers transcripts from 1; the code numbers them from 0.
EM-ABUNDANCE(classes e with counts c_e, lengths ℓ, iterations T, tolerance ε)- 1
α_t ← 1/m for each transcript t - 2
for iter ← 1 to T do - 3
n_t ← 0 for each t - 4
for each class e do - 5
s ← Σ_{u in e} α_u / ℓ_u - 6
for each t in e: n_t ← n_t + c_e · (α_t / ℓ_t) / s - 7
α'_t ← n_t / N for each t - 8
if max_t |α'_t - α_t| < ε then return α' - 9
α ← α' - 10
return α
Lines L5 and L6 are the E step. The share is the expected number of reads of class that came from , given the current . Line L7 is the M step: with the expected counts fixed, the best weights are the counts divided by . Line L1 starts with every . 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 does the work of 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 with 30 reads, with 40 and with 30.
| round | shared reads given to A | |||
|---|---|---|---|---|
| 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 , and line L6 gives A the share of the 40 shared reads, so and . B is shorter, so at equal each of its positions is twice as likely, and B gets two thirds of the shared reads. The values approach , and with line L8 stops after 19 rounds.
The limit is the maximum. With , is plus a constant, and its derivative is at . In transcript fractions, and , 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 , by Jensen's inequality applied to each class, with equality only at a fixed point. Global maximum (a theorem): is concave, because each class adds the log of a linear function. At a fixed point with all , every partial derivative equals , 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 transcripts with effective lengths . The reads are grouped into equivalence classes: a class is a nonempty set of transcripts and is the number of reads in it. . The parameter is in the simplex , and is the probability that a read comes from transcript . For a class let
The set is where is finite. One round of lines L3 to L7 maps to with
1. The iterates are well defined
Lemma 1. If , then , and for every transcript that is in some class and has . In particular, the iterates that start at the uniform point of line L1 stay in .
Proof. For each class, by the definition of . So and , and all . If and , then and . The uniform start has for all , 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 for every class, and the next iterate is in .
2. The likelihood never decreases
Lemma 2. For and every with wherever ,
Proof. Fix a class . Only the members with have , and these weights sum to 1. Then
The logarithm is concave, so by Jensen's inequality the log of this weighted mean is at least the weighted mean of the logs:
Multiply by and add over all classes. The coefficient of is .
Theorem 1 (monotonicity). For and ,
with equality only if .
Proof. Put in Lemma 2. Then wherever , and , so the right side is , with . The Kullback-Leibler divergence of two distributions is at least 0 and is 0 only when they are equal (Gibbs' inequality).
Lemma 2 also explains line L7. For fixed counts , the function on is largest at , 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 in lines L5 and L6.
The values form a nondecreasing sequence. They are bounded above, because for all . 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. is concave on . If is a fixed point, , and for every , then for every .
Proof. Each is a linear function of , and is concave and increasing, so each is concave on the convex set , and so is their sum.
The partial derivatives at are
At a fixed point, for all . Where this gives . With full support, for all .
Take . A concave differentiable function lies below its tangent plane, so
For some and .
4. What is not true
Fixed points with a zero can be poor. Take three transcripts of the same length , and the classes and with 10 reads each. At the counts are , so . But and , 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 . 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 and have and are in exactly the same classes, then depends only on . 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.
Complexity
Let 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 arithmetic operations in the real RAM. rounds cost . The extra space is for and , 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 for reads from nowhere. The loop is the same, with the per-read probability in place of .
- 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 , line L6 never gives that transcript a read, and the result can be a poor fixed point. Start with every .
- 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 or the full fragment length distribution.
- Reading as expression. is a fraction of reads, not of molecules. Report or TPM, which divide by 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 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.
# 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
- 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)
- 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)
- 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
- Hui Jiang and Wing Hung Wong, Statistical inferences for isoform expression in RNA-Seq, Bioinformatics 25(8) (2009), pp. 1026 to 1032
- 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)
- 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.
| Ladder | Level | What the next level needs |
|---|---|---|
| Human proof | H1 sketch |
|
| Lean | L0 no Lean part |
|
| Code (python) | I0 not checked yet |
|
| Visual | V0 none |
|
| Writing | W2 basic |
|
Tag QSYASY Edit this page History Report an error Markdown