Algorithmadvanced
Minimum path cover transcript assembly
Also called Cufflinks assembly.
Assemble the fewest transcripts that explain all fragments: order the compatible fragments, find a maximum bipartite matching, and merge each chain into one transcript, by Dilworth's theorem.
- Solves
- Transcript assembly
- Time
- O(F^3 + F^2·λ + (F+n)·(n+E)) worst
- Space
- O(F^2 + n^2) extra
- Where
- E = the number of edges; F = the number of fragments after line L1; n = the number of nodes of the graph; λ = the largest number of nodes in a fragment
- Model
- Word RAM
- Properties
- deterministicexactofflineiterative
- Evidence
- Proof sketchCode in 1 languages
- Origin
- Cole Trapnell, Brian A. Williams, Geo Pertea, Ali Mortazavi, Gordon Kwan, Marijke J. van Baren, Steven L. Salzberg, Barbara J. Wold, Lior Pachter, 2010
Minimum path cover transcript assembly finds the smallest set of transcripts that explains every read of a gene locus. Each read, or each read pair with a known gap, is a fragment: a path through the splice graph of the locus. Two fragments are compatible when one transcript can hold both. The method orders the compatible fragments, finds a maximum matching in a bipartite graph of that order, and merges each chain of matched fragments into one transcript. By Dilworth's theorem the number of transcripts is the least possible and equals the largest set of fragments of which no two fit on one transcript. This is the assembly step of Cufflinks. The optimum is exact for the stated problem, but the choice of the fewest transcripts is a parsimony heuristic: nothing forces the cell to use the fewest isoforms.
In plain words
Each read is a short piece of some message. Two pieces can belong to the same message when they agree where they overlap, or when one can be followed by the other along the gene.
Line up the pieces so that every piece points to a piece that can come after it on the same message. Each line of pieces becomes one message. We want as few lines as possible, so that we invent no more messages than the reads need.
A matching finds the best way to link pieces in pairs, and the number of messages is the number of pieces minus the number of links. Two pieces that can never be on one message must be in different lines, so the answer can never be smaller than the largest group of such pieces.
The problem
The input is a DAG on the nodes , numbered so that each edge has ; the nodes of a splice graph in coordinate order have this property. A fragment is a path of : the node path of a read, or of a read pair whose two mates and the part between them are known. A path holds a fragment if is a contiguous part of . The task is to find the fewest paths of that together hold every fragment.
This is the minimum path cover problem with subpath constraints, where each fragment is one constraint. Rizzi, Tomescu and Mäkinen (2014) show that this version is solvable in polynomial time. The pseudocode numbers nodes from 1; the code numbers them from 0.
The algorithm
For a fragment , is its first node and its last node.
MIN-PATH-COVER-ASSEMBLY(G, fragments)- 1
F ← the distinct fragments that are not a contiguous part of another fragment - 2
for each pair x, y in F with f(x) < f(y) do - 3
if f(y) is in x at index i then x ≺ y iff x[i..] = y[..|x| - i] - 4
else x ≺ y iff l(x) < f(y) and f(y) can be reached from l(x) - 5
H ← the bipartite graph with a left copy and a right copy of F and an edge (x, y) for each x ≺ y - 6
M ← a maximum matching of H - 7
for each fragment that is not matched on the right, follow its matched successors to get a chain - 8
merge each chain into one path: append the rest of y, or a connecting path and then y - 9
return the paths; there are |F| - |M| of them
Line L1 is safe, because a path that holds a fragment holds every part of it. Lines L3 and L4 test whether one path can hold and then : either starts inside and they agree on the overlap, or starts after ends and the graph has a way from one to the other. Reachability comes from a transitive closure of , computed once. Line L6 is any maximum bipartite matching algorithm; the code uses augmenting paths, and Hopcroft-Karp is faster. Line L7 starts a chain at each fragment that is no one's successor, and line L8 walks the chain and appends each fragment to the path. The connecting path in line L8 is any path from to , found by breadth-first search.
This is the path cover by bipartite matching construction applied to the order on fragments. Cufflinks calls the graph of fragments and their compatibility the overlap graph.
Example
Use the splice graph of the splice graph page: nodes , , , , and edges , , , , . The reads give seven fragments: twice, , , , , and alone.
Line L1 drops the second copy of and the fragment , which is part of . Lines L2 to L4 give this order:
| pair | test | result |
|---|---|---|
| is in at index 1; | ||
| is not in ; and is reachable | ||
| is in at index 1, and they agree | ||
| is in at index 1, and they agree | ||
| is not in , and is not before | no | |
| the same first node | no | |
| and | jumps from to | no |
has the four edges , , , . The code matches first, then ; then tries , which is taken by , and has no other edge, so stays unmatched. and line L9 returns paths: merged into , merged into , and .
Three is the least possible: , and are pairwise incompatible, so no two of them share a path. The output is still not the true set of transcripts. The gene has , and , and the cover gave to the second path, so the first path ends at . The other maximum matching, and , gives , and . Both are minimum covers. Cufflinks breaks such ties with the read abundances.
Correctness
The proof has four steps. Line L1 does not change the set of covers. For fragments that are not parts of each other, holds exactly when some path holds and then , and is a strict partial order. The fragments on one path form a chain, and line L8 turns any chain into one path that holds all its fragments, with the invariant that the merged path ends with the last fragment added. So the fewest paths equals the fewest chains, which is by the matching argument, and by Dilworth's theorem also the size of the largest antichain. Every statement is a theorem about the model; that the model picks the right transcripts is not claimed.
Proof: The matching method returns the fewest paths that hold every fragment, and their number is the largest set of pairwise incompatible fragmentsfull
We use the pseudocode of the page. is a DAG whose nodes are numbered so that every edge has . A path is a sequence of nodes with an edge between each consecutive pair, so every path is increasing. A fragment is a path. A path holds a fragment if is a contiguous part of . A cover is a set of paths that together hold every fragment. We write and for the first and the last node of .
1. Line L1 does not change the covers
A path that holds holds every contiguous part of . So if is a contiguous part of another fragment , a set of paths is a cover of the fragments if and only if it is a cover of the fragments without . Duplicates are the same. After line L1, no fragment of is a contiguous part of another.
Lemma 1. Two distinct fragments of have different first nodes, or they are not held by a common path.
Proof. If a path holds and and , then both start at the same position of , because visits each node once. Then the shorter one is a prefix of the longer one, which line L1 removed.
2. The order
For , lines L2 to L4 define when and either is in , at index , and , or is not in , , and can be reached from .
Lemma 2. For with : if and only if some path of holds both and .
Proof. Suppose a path holds both, with and . Then , because is increasing and . If , then is in at index , and , with . If , then is not in (the nodes of are and all are smaller than ), , and is a path from to . In both cases .
Conversely, suppose . In the first case, is not a contiguous part of , so , and followed by is a walk: its parts are paths, and they join at . In the second case, , then a path from to without its ends, then , is a walk. In a DAG every walk is a path, and holds and .
Lemma 3. is a strict partial order on .
Proof. It is irreflexive, because is false. Let and . By Lemma 2 there is a path with and ; by the construction in its proof we may take to end with . Merging with in the same way, which works because the end of is and , gives a path that starts with and ends with . Since , Lemma 2 gives .
3. Covers and chains
A chain is a set of fragments that are pairwise comparable under .
Lemma 4. The fragments held by one path form a chain.
Proof. By Lemma 1, two distinct fragments held by the path have different first nodes; the one that starts first precedes the other by Lemma 2.
Lemma 5 (merging, line L8). Let . Line L8 builds a path that holds , and the part of that starts at is exactly , for each .
Proof. By induction on . . Suppose the claim holds for . Since and ends with , the step of line L8 is the construction in the proof of Lemma 2 applied to the end of . In the overlap case it appends , and in the other case a connecting path and then minus its first node. The result is a path, by the same argument as in Lemma 2, its part from is , and the earlier fragments are still held, because line L8 only appends.
Theorem 1. The least number of paths in a cover equals the least number of chains that cover .
Proof. Given a cover by paths, give each fragment to one path that holds it. By Lemma 4 the fragments given to one path form a chain, so there are at most chains. Conversely, the elements of a chain are totally ordered by (Lemma 3), and Lemma 5 turns each chain into one path that holds all of its elements.
4. Chains and matchings
Line L5 builds the bipartite graph with a left copy and a right copy of each fragment and an edge for each . Line L6 finds a maximum matching of , and line L7 follows the matched edges.
Theorem 2. The least number of chains that cover is , and lines L7 and L8 return that many paths, which form a cover.
Proof. In a matching, each fragment has at most one matched successor and at most one matched predecessor, and following successors increases , so the matched edges form disjoint sequences that together contain every fragment. Each sequence starts at a fragment with no matched predecessor, which is what line L7 looks for. There are sequences, because each matched edge joins two fragments into one sequence. Each sequence is a chain, by the transitivity of Lemma 3.
Conversely, a cover by disjoint chains gives a matching of size : in each chain, sorted by , match each element to the next one. A cover by chains that are not disjoint can be made disjoint by dropping repeated elements, and a subset of a chain is a chain. So the least number of chains is minus the largest matching. By Lemma 5 each sequence becomes a path that holds its fragments, so the output is a cover with paths, which is the least possible by Theorem 1.
Corollary (Dilworth). The number of paths returned equals the largest number of fragments of which no two are held by a common path.
Proof. Two fragments are held by a common path if and only if they are comparable (Lemma 2 and Lemma 1). By Dilworth's theorem, the least number of chains that cover a finite partial order equals the size of its largest antichain.
Complexity
The word RAM, with fragments after line L1, at most nodes in each, and a graph with nodes and edges.
- Line L1: each pair of fragments is compared in , because a path visits a node once, so one lookup finds where could start in . Total .
- Lines L2 to L4: the reachability bit sets cost word operations once, and each of the pairs costs .
- Line L6: augmenting paths cost . Hopcroft-Karp costs .
- Line L8: at most connecting searches of each.
The total is time, and space for and the bit sets. In practice is the number of distinct fragments of one locus, often a few hundred after duplicates and contained fragments are removed.
Properties
- Exact for its model. The number of paths is the least possible, a theorem (Theorem 2 of the proof).
- Parsimony is a heuristic. The true transcript set may have more transcripts than the minimum, and the minimum cover need not be unique.
- Abundance-blind. The cover uses only which fragments exist, not how many reads each has. Cufflinks estimates abundances in a separate maximum likelihood step.
- Paths may be truncated. A path starts and ends where its first and last fragments do, and a fragment that two transcripts share goes to only one of them.
- Deterministic. The order of the fragments and of the edges fixes the matching.
Variants and improvements
- Cufflinks. It also marks pairs of fragments as incompatible when they disagree on splicing, which is the same as failing in both directions. Among the maximum matchings it takes one of least cost, with a cost on each edge that is small when the two fragments have similar estimated splicing ratios, so that fragments of the same abundance end up on the same transcript.
- Paired fragments. When a read pair is two separate subpaths with an unknown part between them, each constraint is a pair of subpaths. Rizzi, Tomescu and Mäkinen (2014) show that the minimum path cover with pairs of subpaths is NP-hard, and Beerenwinkel, Beretta, Bonizzoni, Dondi and Pirola (2015) show that already deciding whether three paths are enough is NP-hard. The simple method then needs a heuristic, such as filling the gap when it is unique.
- Faster matching. Hopcroft-Karp or a flow algorithm in place of augmenting paths one at a time.
- Weighted covers. Methods that also use the read counts replace the path cover by a flow decomposition of the coverage, as in flow-based assembly.
When to use it
Use it when you want the smallest transcript set that is consistent with every read, for example to avoid reporting false isoforms from noise, and when the reads or the read pairs are single subpaths of the splice graph. It is not a good choice when the expression levels of the isoforms are very different, because it ignores the counts, or when many pairs leave a gap with several possible fillings. Then a flow-based method such as StringTie, which uses the coverage, is usually more accurate (a measurement on benchmarks, not a theorem).
Pitfalls
- Skipping line L1. If a contained fragment stays, it can match into a chain on its own and add a path. Remove duplicates and contained fragments first.
- Testing only adjacent fragments in line L4. The order must use reachability, not only a direct edge from to ; otherwise is not transitive and the matching can return more paths than needed.
- Taking the paths as full transcripts. Line L8 builds paths that start and end at fragment ends. A shared fragment goes to one chain only, as in the example; report the cover as a set of partial transcripts, or extend the ends with the splice graph.
- One bad fragment costs one path. A misaligned read that is incompatible with all others forces its own transcript, because the method must explain every fragment. Filter fragments with few reads or short anchors before line L1.
- Merging mates as one path. Joining the two mates of a pair by an arbitrary connecting path in line L8 invents the part between them. Only do this when the gap has one possible path.
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/minimum-path-cover-transcript-assembly/. The authors are listed in prov/9NY424.jsonl.
"""The fewest transcripts that explain a set of fragments, by Dilworth's theorem.
The graph is a DAG on the nodes 0 to n - 1, numbered so that every edge
(u, v) has u < v; the nodes of a splice graph in coordinate order have this
property. A fragment is a path of the graph, given as its list of nodes: the
node path of a read or of a read pair whose gap is known. The task is to find
the fewest paths of the graph such that every fragment is a contiguous part of
at least one of them.
This is the parsimony step of Cufflinks in its simplest form. Cufflinks also
works on fragments that disagree (they cannot be on one transcript), weights
the matching by how close the abundances of two fragments are, and estimates
abundances afterwards. None of this is here.
"""
from __future__ import annotations
from collections import deque
from typing import Dict, List, Sequence, Set, Tuple
Path = Tuple[int, ...]
def _is_subpath(x: Path, y: Path) -> bool:
"""True if x is a contiguous part of y. A path visits each node once, so one lookup is enough."""
if x[0] not in y:
return False
i = y.index(x[0])
return y[i:i + len(x)] == x
def reach(n: int, edges: Sequence[Tuple[int, int]]) -> List[int]:
"""reach[u] is a bit set of the nodes v != u that can be reached from u."""
succ: List[List[int]] = [[] for _ in range(n)]
for u, v in edges:
if not u < v:
raise ValueError("edges must go from a smaller to a larger node id")
succ[u].append(v)
r = [0] * n
for u in range(n - 1, -1, -1):
for v in succ[u]:
r[u] |= (1 << v) | r[v]
return r
def precedes(x: Path, y: Path, r: Sequence[int]) -> bool:
"""x <= y: some path of the graph holds x and then y, and x starts first.
The fragments must not be contiguous parts of each other.
"""
if not x[0] < y[0]: # @line L2
return False
if y[0] in x: # @line L3
i = x.index(y[0])
return x[i:] == y[:len(x) - i]
return x[-1] < y[0] and bool(r[x[-1]] >> y[0] & 1) # @line L4
def _connect(succ: Sequence[Sequence[int]], s: int, t: int) -> List[int]:
"""A path from s to t by breadth-first search, without s and with t."""
parent: Dict[int, int] = {s: -1}
q = deque([s])
while q:
u = q.popleft()
if u == t:
break
for v in succ[u]:
if v not in parent:
parent[v] = u
q.append(v)
out = []
v = t
while v != s:
out.append(v)
v = parent[v]
return out[::-1]
def _max_matching(adj: Sequence[Sequence[int]], n: int) -> List[int]:
"""Kuhn's augmenting path algorithm. Returns match_right[y] = x, or -1."""
match_left, match_right = [-1] * n, [-1] * n
for root in range(n):
seen: Set[int] = set()
# Iterative depth-first search for an augmenting path from root.
stack = [(root, iter(adj[root]))]
trail: List[Tuple[int, int]] = []
found = False
while stack and not found:
x, it = stack[-1]
for y in it:
if y in seen:
continue
seen.add(y)
if match_right[y] == -1:
trail.append((x, y))
found = True
break
trail.append((x, y))
stack.append((match_right[y], iter(adj[match_right[y]])))
break
else:
stack.pop()
if trail:
trail.pop()
if found:
for x, y in trail:
match_left[x], match_right[y] = y, x
return match_right
def min_path_cover(n: int, edges: Sequence[Tuple[int, int]],
fragments: Sequence[Sequence[int]]) -> List[List[int]]:
"""The fewest paths of the DAG that hold every fragment as a contiguous part."""
r = reach(n, edges)
succ: List[List[int]] = [[] for _ in range(n)]
for u, v in sorted(set(edges)):
succ[u].append(v)
for f in fragments:
if not f or any(not (v in succ[u]) for u, v in zip(f, f[1:])):
raise ValueError("each fragment must be a nonempty path of the graph")
distinct = sorted(set(tuple(f) for f in fragments))
frags = [x for x in distinct # @line L1
if not any(x != y and _is_subpath(x, y) for y in distinct)]
k = len(frags)
adj = [[j for j in range(k) if precedes(frags[i], frags[j], r)] # @line L5
for i in range(k)]
match_right = _max_matching(adj, k) # @line L6
nxt = [-1] * k
for y, x in enumerate(match_right):
if x != -1:
nxt[x] = y
paths = []
for start in range(k): # @line L7
if match_right[start] != -1:
continue
path = list(frags[start])
j = nxt[start]
while j != -1: # @line L8
y = frags[j]
if y[0] in path:
i = path.index(y[0])
path.extend(y[len(path) - i:])
else:
path.extend(_connect(succ, path[-1], y[0]))
path.extend(y[1:])
j = nxt[j]
paths.append(path)
return paths # @line L9
test_minimum_path_cover_transcript_assembly.py 124 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/minimum-path-cover-transcript-assembly/. The authors are listed in prov/9NY424.jsonl.
import random
from itertools import combinations
from minimum_path_cover_transcript_assembly import min_path_cover, precedes, reach
def contains(path, frag):
n = len(frag)
return any(tuple(path[i:i + n]) == tuple(frag) for i in range(len(path) - n + 1))
def all_paths(n, edges):
"""Every source-to-sink path of the DAG."""
succ = {u: [] for u in range(n)}
has_pred = set()
for u, v in edges:
succ[u].append(v)
has_pred.add(v)
out, stack = [], [[s] for s in range(n) if s not in has_pred]
while stack:
p = stack.pop()
if not succ[p[-1]]:
out.append(p)
for v in succ[p[-1]]:
stack.append(p + [v])
return out
def random_instance(rng: random.Random):
n = rng.randint(2, 7)
edges = [(u, v) for u in range(n) for v in range(u + 1, n) if rng.random() < 0.45]
succ = {u: [v for a, v in edges if a == u] for u in range(n)}
frags = []
for _ in range(rng.randint(1, 6)):
f = [rng.randrange(n)]
for _ in range(rng.randint(0, 3)):
if not succ[f[-1]]:
break
f.append(rng.choice(succ[f[-1]]))
frags.append(f)
return n, edges, frags
def brute_cover(n, edges, frags):
"""The fewest source-to-sink paths that hold every fragment."""
paths = all_paths(n, edges)
for k in range(1, len(frags) + 1):
for choice in combinations(paths, k):
if all(any(contains(p, f) for p in choice) for f in frags):
return k
raise AssertionError("every fragment is on some source-to-sink path")
def test_worked_example():
# The splice graph of the page: v1 -> v2 -> v3 -> v4 and v1 -> v3, v1 -> v4 (0-based here).
edges = [(0, 1), (1, 2), (2, 3), (0, 2), (0, 3)]
frags = [[0, 1], [1, 2], [2, 3], [0, 2], [0, 3]]
paths = min_path_cover(4, edges, frags)
assert paths == [[0, 1, 2], [0, 2, 3], [0, 3]]
# A contained fragment and a duplicate change nothing.
assert min_path_cover(4, edges, frags + [[2], [0, 1]]) == paths
def test_precedes_is_a_strict_partial_order():
rng = random.Random(1)
for _ in range(300):
n, edges, frags = random_instance(rng)
r = reach(n, edges)
fs = sorted(set(tuple(f) for f in frags))
fs = [x for x in fs if not any(x != y and contains(y, x) for y in fs)]
for x in fs:
assert not precedes(x, x, r)
for y in fs:
for z in fs:
if precedes(x, y, r) and precedes(y, z, r):
assert precedes(x, z, r)
def test_precedes_means_a_common_path():
rng = random.Random(2)
for _ in range(300):
n, edges, frags = random_instance(rng)
r = reach(n, edges)
paths = all_paths(n, edges)
fs = sorted(set(tuple(f) for f in frags))
fs = [x for x in fs if not any(x != y and contains(y, x) for y in fs)]
for x in fs:
for y in fs:
if x[0] < y[0]:
both = any(contains(p, x) and contains(p, y) for p in paths)
assert precedes(x, y, r) == both
def test_against_brute_force():
rng = random.Random(3)
for _ in range(500):
n, edges, frags = random_instance(rng)
out = min_path_cover(n, edges, frags)
eset = set(edges)
for p in out:
assert all((u, v) in eset for u, v in zip(p, p[1:]))
for f in frags:
assert any(contains(p, f) for p in out)
assert len(out) == brute_cover(n, edges, frags)
def test_dilworth_antichain():
# The number of paths equals the largest set of fragments of which no two fit on one path.
rng = random.Random(4)
for _ in range(300):
n, edges, frags = random_instance(rng)
paths = all_paths(n, edges)
fs = sorted(set(tuple(f) for f in frags))
fs = [x for x in fs if not any(x != y and contains(y, x) for y in fs)]
best = 0
for k in range(1, len(fs) + 1):
for sub in combinations(fs, k):
if all(not any(contains(p, x) and contains(p, y) for p in paths)
for x, y in combinations(sub, 2)):
best = k
assert len(min_path_cover(n, edges, frags)) == best
History
Dilworth (1950) proved that the least number of chains that cover a finite partial order equals the size of its largest antichain, and Fulkerson (1956) gave a proof by bipartite matching that is also an algorithm. Trapnell, Williams, Pertea, Mortazavi, Kwan, van Baren, Salzberg, Wold and Pachter (2010) used this construction in Cufflinks to assemble the fewest transcripts that explain the fragments of each locus, and then estimated their abundances in FPKM. Rizzi, Tomescu and Mäkinen (2014) showed that the path cover with subpath constraints stays polynomial and that pairs of subpaths make it NP-hard, and Beerenwinkel, Beretta, Bonizzoni, Dondi and Pirola (2015) studied covers of pairs in DAGs.
References
- Cole Trapnell, Brian A. Williams, Geo Pertea, Ali Mortazavi, Gordon Kwan, Marijke J. van Baren, Steven L. Salzberg, Barbara J. Wold and Lior Pachter, Transcript assembly and quantification by RNA-Seq reveals unannotated transcripts and isoform switching during cell differentiation, Nature Biotechnology 28(5) (2010), pp. 511 to 515, Online Methods (the overlap graph of fragments, the minimum path cover by Dilworth's theorem and bipartite matching)
- R. P. Dilworth, A decomposition theorem for partially ordered sets, Annals of Mathematics 51(1) (1950), pp. 161 to 166
- Romeo Rizzi, Alexandru I. Tomescu and Veli Mäkinen, On the complexity of minimum path cover with subpath constraints for multi-assembly, BMC Bioinformatics 15(Suppl 9) (2014), Article S5 (subpath constraints in polynomial time by a reduction to the classical problem; pairs of subpaths are NP-hard)
- Niko Beerenwinkel, Stefano Beretta, Paola Bonizzoni, Riccardo Dondi and Yuri Pirola, Covering pairs in directed acyclic graphs, The Computer Journal 58(7) (2015), pp. 1673 to 1686 (deciding whether three paths cover all pairs is NP-hard)
- Veli Mäkinen, Djamal Belazzougui, Fabio Cunial and Alexandru I. Tomescu, Genome-Scale Algorithm Design, Cambridge University Press (2015), Part V, the chapter on transcriptomics (path covers for transcript assembly)
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 9NY424 Edit this page History Report an error Markdown