Algorithm Search⌘K

Algorithmadvanced

Flow-based transcript assembly

Also called StringTie assembly.

Assemble transcripts from a splice graph: take the heaviest path of compatible reads, give it the max flow of its reads as abundance, remove that flow, and repeat.

Time
O(R·((n+E)·F·λ + n·(n+F)^2)) worst
Space
O(n + E + F·λ) extra
Where
E = the number of edges; F = the number of fragments; R = the number of rounds, at most W_0/c_min; n = the number of nodes of the splice graph; λ = the largest number of nodes in a fragment
Properties
deterministicnot exactofflineiterative
Origin
Mihaela Pertea, Geo M. Pertea, Corina M. Antonescu, Tsung Cheng Chang, Joshua T. Mendell, Steven L. Salzberg, 2015

Flow-based transcript assembly builds transcripts and their abundances in one loop over the splice graph of a locus. It starts at the most covered node, grows the heaviest path of reads that agree with each other toward both ends, and computes how many reads the path can carry as a maximum flow through a small network of its reads. That flow is the abundance of the transcript. The flow is then removed from the reads, and the loop repeats until the coverage left is too low. This is the method of StringTie. It is a greedy heuristic: the underlying task, to split the coverage into the fewest weighted paths, is NP-hard, and the loop neither finds the fewest paths nor always finds the true ones.

In plain words

Picture the splice graph as a set of roads, and each read as a car that drove along a short stretch. The busiest place is a good place to look for a real route.

Start there and walk backward and forward, each time choosing the next stretch that the most cars agree with. That gives one route. Now ask how many cars could have driven that whole route, piece by piece, without using any stretch more often than the cars on it allow. That number is how much of this transcript there is.

Take those cars away and look again for the busiest place. Stop when the roads are almost empty.

The problem

The input is a splice graph GG on the nodes 1,…,n1, \ldots, n, with every edge (u,v)(u, v) having u<vu < v, and a set of fragments. A fragment ff is the node path of a read or of a read pair, with at least two nodes, and a weight w(f)w(f), its number of reads; reads on one node only are left out here. The coverage W(v)W(v) of a node is the total weight of the fragments that hold it. The output is a list of paths with abundances, such that the abundances explain the weights well. This is a heuristic form of transcript assembly, in which the exact goal would be a flow decomposition of the coverage into few paths.

Two definitions are used. A fragment ff is compatible with a path QQ if they share a node and agree on all the nodes between their common first and last ids. A fragment is explained by a path P=(v1,…,vm)P = (v_1, \ldots, v_m) if it is a contiguous part of PP. The network N(P)N(P) has a source ss, a sink tt, an edge ini→outi\mathrm{in}_i \to \mathrm{out}_i for each node viv_i with capacity cic_i, the weight of the explained fragments that hold viv_i, and an edge outa→inb\mathrm{out}_a \to \mathrm{in}_b with capacity w(f)w(f) for each explained fragment f=(va,…,vb)f = (v_a, \ldots, v_b). The edges s→in1s \to \mathrm{in}_1 and outm→t\mathrm{out}_m \to t have no limit.

The algorithm

  1. FLOW-ASSEMBLY(G, fragments with weights w, threshold c_min)
  2. 1T ← empty list
  3. 2while some node v has W(v) ≥ c_min do
  4. 3v* ← the node with the largest W, the smallest id on ties
  5. 4P ← (v*)
  6. 5repeat: prepend to P the predecessor u of first(P) with the largest positive weight of fragments that hold u and are compatible with u·P
  7. 6repeat: append to P the successor u of last(P) with the largest positive weight of fragments that hold u and are compatible with P·u
  8. 7(φ, g) ← a maximum flow of N(P), with g_f the flow through each explained fragment f
  9. 8if φ ≥ c_min then
  10. 9append (P, φ) to T, and set w(f) ← w(f) - g_f for each explained fragment f
  11. 10else set w(f) ← 0 for each fragment f that holds v*
  12. 11return T

Lines L3 to L6 build the heaviest path. Starting at the most covered node makes it likely that the path is the main isoform of the locus. The extension follows the reads: a neighbour gets the weight of only those fragments that fit the path built so far, so a read that took another splice choice upstream does not pull the path its way. Line L7 is the Edmonds-Karp algorithm on a network with 2m+22m + 2 nodes. A unit of flow goes from v1v_1 to vmv_m through a chain of explained fragments, each one starting where the previous one ends, so φ\varphi is the number of reads that the whole path can carry. Line L9 removes exactly the reads that the flow used. Line L10 is the escape when the heaviest path carries too little: the reads at v∗v^* are dropped, so the next round starts elsewhere.

The pseudocode numbers nodes from 1; the code numbers them from 0. The code is a small version of StringTie. It uses read counts where StringTie uses coverage per base, and it leaves out StringTie's bias factor on the node capacities, its use of read pairs, its filters for short or weak transcripts, and its strand and locus logic.

Example

One round at a time. The nodes are A, B and C, with the edges ABAB, BCBC and ACAC. The fragments are ABAB with 30 reads, BCBC with 30 and ACAC with 10, and cmin⁡=1c_{\min} = 1.

round coverage WW (A, B, C) path network φ\varphi weights after
1 40, 60, 40 start at B; prepend A (30 from ABAB; ACAC skips B); append C (30 from BCBC) cA=30c_A = 30, cB=60c_B = 60, cC=30c_C = 30; fragment edges ABAB 30 and BCBC 30 30 AB=0AB = 0, BC=0BC = 0, AC=10AC = 10
2 10, 0, 10 start at A, the smaller id; append C (10 from ACAC; B has no weight left) cA=10c_A = 10, cC=10c_C = 10; fragment edge ACAC 10 10 all 0

The output is ABCABC with 30 reads and ACAC with 10. In round 1 the fragment ACAC is not compatible with the path ABAB, because it jumps over B, so it does not add to the score of A.

A case the loop gets wrong. The true transcripts are v1v2v3v4v5v_1 v_2 v_3 v_4 v_5 with 10 reads on each junction and v1v3v5v_1 v_3 v_5 with 20, and every read covers one junction. The weights are 10 on v1v2v_1 v_2, v2v3v_2 v_3, v3v4v_3 v_4 and v4v5v_4 v_5, and 20 on v1v3v_1 v_3 and v3v5v_3 v_5. The loop starts at v3v_3 with W=60W = 60. Both predecessors score 20, and the tie goes to v1v_1; the successors also tie, and v4v_4 wins. The first path is v1v3v4v5v_1 v_3 v_4 v_5 with φ=10\varphi = 10, which is not a true transcript. Then come v1v2v3v5v_1 v_2 v_3 v_5 with 10 and v1v3v5v_1 v_3 v_5 with 10. The three paths explain every read, as the two true ones do. One read that covers v2v3v4v_2 v_3 v_4 links the two choices, and then the loop returns v1v3v5v_1 v_3 v_5 with 20 and v1v2v3v4v5v_1 v_2 v_3 v_4 v_5 with 10. The test file checks both outputs.

Correctness

The proof shows what holds for the loop and what does not. Every path is a path of GG with at least two nodes. The maximum flow splits into chains of explained fragments from the first node to the last, so φ\varphi never exceeds the reads that the path can carry, the weights never go below 0, and the sum of all abundances is at most the number of reads. Each round removes at least cmin⁡c_{\min} of weight, so the loop stops after at most W0/cmin⁡W_0 / c_{\min} rounds, where W0W_0 is the total weight, with every node below cmin⁡c_{\min}. These are theorems. That the paths are the true transcripts is not one: the second example is a counterexample, and with junction reads only no method can decide it.

Proof: The heaviest-path and max-flow loop stops, returns paths of the splice graph, and never assigns more reads than the fragments holdfull

We use the pseudocode of the page. GG is a DAG on the nodes 1,…,n1, \ldots, n with every edge (u,v)(u, v) having u<vu < v. Each fragment ff is a path of GG with at least two nodes and a weight w(f)≥0w(f) \ge 0, and W(v)W(v) is the total weight of the fragments that hold vv. cmin⁡>0c_{\min} > 0 is the threshold. A fragment ff is explained by a path P=(v1,…,vm)P = (v_1, \ldots, v_m) if f=(va,…,vb)f = (v_a, \ldots, v_b) is a contiguous part of PP; then a<ba < b.

The network N(P)N(P) of line L7 has a source ss, a sink tt, and for each ii two nodes ini\mathrm{in}_i and outi\mathrm{out}_i. Its edges are ini→outi\mathrm{in}_i \to \mathrm{out}_i with capacity cic_i, the total weight of the explained fragments that hold viv_i; one edge outa→inb\mathrm{out}_a \to \mathrm{in}_b with capacity w(f)w(f) for each explained fragment f=(va,…,vb)f = (v_a, \ldots, v_b) of positive weight; and s→in1s \to \mathrm{in}_1 and outm→t\mathrm{out}_m \to t with a capacity larger than the total weight.

1. The paths are paths of GG

Lemma 1. Every path PP that lines L4 to L6 build is a path of GG.

Proof. Line L4 starts with one node. Line L5 only prepends a predecessor uu of the first node of PP, that is, a node with an edge (u,first(P))(u, \mathrm{first}(P)), and line L6 only appends a successor of the last node. So consecutive nodes are joined by edges. The extensions stop, because each one adds a node with a smaller id (line L5) or a larger id (line L6), and the ids are in 1..n1..n. □\square

2. The flow is well defined and is a set of fragment chains

N(P)N(P) is a DAG: the order s,in1,out1,in2,out2,…,outm,ts, \mathrm{in}_1, \mathrm{out}_1, \mathrm{in}_2, \mathrm{out}_2, \ldots, \mathrm{out}_m, t is topological, because each fragment edge goes from outa\mathrm{out}_a to inb\mathrm{in}_b with a<ba < b. It has no pair of opposite edges, so the Edmonds-Karp algorithm of line L7 returns a maximum flow φ\varphi and a flow gg on each edge, with 0≤gf≤w(f)0 \le g_f \le w(f) on each fragment edge, by the max-flow min-cut theorem.

Lemma 2. Every unit of the flow follows a chain of explained fragments f1,…,frf_1, \ldots, f_r in which f1f_1 starts at v1v_1, frf_r ends at vmv_m, and each fj+1f_{j+1} starts at the node where fjf_j ends. The value φ\varphi equals the total flow on the fragment edges that leave out1\mathrm{out}_1.

Proof. A flow in a DAG splits into flows along ss-tt paths. An ss-tt path of N(P)N(P) enters at in1\mathrm{in}_1, and from each ini\mathrm{in}_i the only edge goes to outi\mathrm{out}_i. From outi\mathrm{out}_i with i<mi < m the only edges are the fragment edges that start at viv_i, and from outm\mathrm{out}_m the edge to tt. So the path is s,in1,out1s, \mathrm{in}_1, \mathrm{out}_1, a fragment edge to some inb\mathrm{in}_b, then outb\mathrm{out}_b, and so on until outm\mathrm{out}_m and tt. This is the chain of the claim. All flow from ss passes out1\mathrm{out}_1, and if m>1m > 1 it leaves out1\mathrm{out}_1 only on fragment edges. If m=1m = 1, no fragment is explained, so c1=0c_1 = 0 and φ=0\varphi = 0. □\square

So φ\varphi is the largest number of reads that can be placed on PP as chains of explained fragments from the first node to the last, such that no fragment is used more often than its weight and no node more often than the weight of the fragments that hold it. It is a measure of the abundance of PP in the model, not a proof that PP is a transcript.

3. Weights stay valid, and the loop stops

Lemma 3. All weights stay at least 0. The sum of the abundances returned is at most the total initial weight.

Proof. Line L9 lowers w(f)w(f) by gf≤w(f)g_f \le w(f), and line L10 sets weights to 0. In a round that adds (P,φ)(P, \varphi), the total weight falls by ∑fgf≥φ\sum_f g_f \ge \varphi, by Lemma 2, because the fragment edges that leave out1\mathrm{out}_1 are among all fragment edges. Adding over the rounds, the sum of the returned abundances is at most the total fall of the weight, which is at most the initial total. □\square

Theorem 1. The loop stops after at most ⌊W0/cmin⁡⌋+1\lfloor W_0 / c_{\min} \rfloor + 1 rounds, where W0W_0 is the total initial weight. When it stops, every node has W(v)<cmin⁡W(v) < c_{\min}.

Proof. Consider one round, with start node v∗v^* and W(v∗)≥cmin⁡W(v^*) \ge c_{\min} by line L2. If line L8 accepts, the total weight falls by at least φ≥cmin⁡\varphi \ge c_{\min} (Lemma 3). If not, line L10 sets to 0 every fragment that holds v∗v^*, and these fragments have total weight W(v∗)≥cmin⁡W(v^*) \ge c_{\min}. In both cases the total weight, which is never negative, falls by at least cmin⁡c_{\min}. So there are at most W0/cmin⁡W_0 / c_{\min} rounds, and the loop ends only when the test of line L2 fails. □\square

Theorem 2. Every returned pair (P,φ)(P, \varphi) has a path PP of GG with at least two nodes and φ≥cmin⁡\varphi \ge c_{\min}.

Proof. PP is a path of GG by Lemma 1. Line L9 runs only when φ≥cmin⁡>0\varphi \ge c_{\min} > 0, and φ>0\varphi > 0 needs an explained fragment by Lemma 2, which has at least two nodes, so m≥2m \ge 2. □\square

4. What is not true

The loop is a greedy heuristic. It does not find the fewest paths that explain the weights, and it does not always find the true transcripts. With only junction reads, the transcripts v1v2v3v4v5v_1 v_2 v_3 v_4 v_5 with 10 reads per junction and v1v3v5v_1 v_3 v_5 with 20 give the weights v1v2=v2v3=v3v4=v4v5=10v_1 v_2 = v_2 v_3 = v_3 v_4 = v_4 v_5 = 10 and v1v3=v3v5=20v_1 v_3 = v_3 v_5 = 20. The loop returns three paths, v1v3v4v5v_1 v_3 v_4 v_5, v1v2v3v5v_1 v_2 v_3 v_5 and v1v3v5v_1 v_3 v_5, each with 10, which explain the weights as well as the two true ones. No method can tell these apart from these weights alone, because both are flow decompositions of the same flow. Finding a decomposition into the fewest paths is NP-hard in the strong sense, even on DAGs (Vatinlen, Chauvet, Chrétienne and Mahey 2008). ■\blacksquare

Complexity

The word RAM, with nn nodes, EE edges, FF fragments of at most λ\lambda nodes, and R≤W0/cmin⁡R \le W_0 / c_{\min} rounds.

  • Lines L2 and L3: the coverage of all nodes, O(nFλ)O(n F \lambda) as the code computes it, or O(Fλ)O(F \lambda) with a running count.
  • Lines L5 and L6: each step scores the neighbours of one end, and each score checks every fragment in O(λ)O(\lambda). Over all steps of a round that is O((n+E)Fλ)O((n + E) F \lambda).
  • Line L7: N(P)N(P) has 2m+2≤2n+22m + 2 \le 2n + 2 nodes and m+F+2m + F + 2 edges. Edmonds-Karp costs O(∣V∣∣E∣2)=O(n(n+F)2)O(|V| |E|^2) = O(n (n + F)^2).

The total is O(R⋅((n+E)Fλ+n(n+F)2))O(R \cdot ((n + E) F \lambda + n (n + F)^2)) time and O(n+E+Fλ)O(n + E + F \lambda) space. The bound is loose. A locus has tens of nodes and few rounds, and the max flow on a path network is fast in practice.

Properties

  • A heuristic. It returns a decomposition, not the fewest paths and not always the true paths (Section 4 of the proof).
  • Assembly and quantification together. Each transcript comes with its abundance from line L7, and later transcripts see only the reads that earlier ones did not use.
  • Terminates. At most W0/cmin⁡W_0 / c_{\min} rounds, a theorem.
  • Never overspends reads. The abundances add up to at most the number of reads, a theorem.
  • Order-dependent. The first path takes its reads first. A different start or tie rule gives a different output.

Variants and improvements

  • StringTie. Coverage per base on the nodes and the reads, a bias factor on the node capacities, read pairs joined into longer fragments, and filters that drop transcripts with too little coverage or too short a length.
  • Scallop. Shao and Kingsford (2017) decompose the splice graph flow while they keep phasing paths, the paths that single reads or pairs cover, so that the choices at two splice sites stay linked.
  • Minimum flow decomposition. The exact problem: split a flow into the fewest weighted source-to-sink paths. It is NP-hard in the strong sense, even on DAGs (Vatinlen, Chauvet, Chrétienne and Mahey 2008), and stays NP-hard with the flow values 1, 2 and 4 (Hartman, Hassidim, Kaplan, Raz and Segalov 2012). Greedy rules such as the widest path first are the usual approximations.
  • Min-cost flow formulations. Methods in the book of Mäkinen, Belazzougui, Cunial and Tomescu (2015) fit a flow to noisy coverage with a min-cost flow and then decompose it.
  • Path covers. Without weights, the fewest transcripts that explain all reads come from minimum path cover assembly, as in Cufflinks.

When to use it

Use it for genome-guided assembly of short reads, when the isoforms of a gene have very different abundances: the coverage separates them, which a path cover cannot do. StringTie reported more complete and accurate assemblies than Cufflinks and other assemblers on simulated and real data, which is a measurement on benchmarks, not a guarantee. If reads or pairs are long enough to span several splice sites, a method that keeps phasing paths, such as Scallop, uses that information better. Without a genome, use de novo transcriptome assembly. If only the abundances of known transcripts are needed, skip assembly and use EM quantification.

Pitfalls

  • Scoring all fragments in line L5. If the extension counts every fragment at uu, not only those compatible with u⋅Pu \cdot P, a read that jumps over the path pulls it the wrong way, as ACAC would in the first example. Count only compatible fragments.
  • Taking the coverage as the abundance. The weight at the start node v∗v^* includes the reads of other isoforms. The abundance is the flow φ\varphi of line L7, which is limited by the weakest part of the path.
  • Missing line L10. If the heaviest path carries less than cmin⁡c_{\min}, nothing is removed and the loop repeats forever. Drop the reads at v∗v^*, or mark v∗v^* as done.
  • Trusting unphased paths. With junction reads only, a path can mix the choices of two transcripts, as in the second example. Paths through two or more splice choices need reads or pairs that span both.
  • Overlapping fragments in N(P)N(P). In the network a unit of flow moves from a fragment to one that starts exactly where it ends. Two explained fragments that overlap in more than one node cannot both carry the same read flow, so some weight stays behind and can come back as a short extra path. The toy keeps this limit.

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.

flow_based_transcript_assembly.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/flow-based-transcript-assembly/. The authors are listed in prov/9XQGWM.jsonl.

"""Transcript assembly by heaviest paths and max flow, in the style of StringTie.

The graph is a splice graph: a DAG on the nodes 0 to n - 1 with every edge
(u, v) having u < v. A fragment is a path of at least two nodes (the node path
of a read or of a read pair) with a weight, its number of reads. Fragments on
one node only are ignored here. The coverage W(v) of a node is the total
weight of the fragments that hold v.

Each round starts at the node of highest coverage, extends a path toward the
source and then toward the sink with the neighbour that has the most
compatible fragment weight, and computes the abundance of the path as a
maximum flow through the fragments that the path explains. The flow on each
fragment is subtracted, and the loop stops when no node has coverage c_min.

What this leaves out, compared with StringTie: coverage per base instead of
read counts, the bias factor on node capacities, super-reads from read pairs,
the filters on short and weak transcripts, and the strand and locus logic.
"""

from __future__ import annotations

from collections import deque
from typing import Dict, List, Sequence, Tuple

Path = Tuple[int, ...]


def edmonds_karp(n: int, cap: Dict[Tuple[int, int], float], s: int, t: int):
    """Maximum flow by shortest augmenting paths. Returns (value, flow on each edge of cap).

    The network must have no pair of opposite edges (u, v) and (v, u); N(P) has none.
    """
    res: Dict[int, Dict[int, float]] = {u: {} for u in range(n)}
    for (u, v), c in cap.items():
        if (v, u) in cap:
            raise ValueError("opposite edges are not supported")
        res[u][v] = c
        res[v][u] = 0
    value = 0
    while True:
        parent = {s: s}
        q = deque([s])
        while q and t not in parent:
            u = q.popleft()
            for v, c in res[u].items():
                if c > 1e-12 and v not in parent:
                    parent[v] = u
                    q.append(v)
        if t not in parent:
            break
        b, v = float("inf"), t
        while v != s:
            b = min(b, res[parent[v]][v])
            v = parent[v]
        v = t
        while v != s:
            u = parent[v]
            res[u][v] -= b
            res[v][u] += b
            v = u
        value += b
    return value, {(u, v): c - res[u][v] for (u, v), c in cap.items()}


def _part(f: Path, lo: int, hi: int) -> Path:
    return tuple(x for x in f if lo <= x <= hi)


def compatible(f: Path, q: Path) -> bool:
    """f and q overlap and agree on the node range they share, so one path can hold both."""
    lo, hi = max(f[0], q[0]), min(f[-1], q[-1])
    part = _part(f, lo, hi)
    return bool(part) and part == _part(q, lo, hi)


def _explained(f: Path, p: Path) -> int:
    """The index of f in p if f is a contiguous part of p, else -1."""
    if f[0] not in p:
        return -1
    i = p.index(f[0])
    return i if p[i:i + len(f)] == f else -1


def path_flow(p: Path, weight: Dict[Path, float]):
    """The max flow of the network N(p). Returns (value, flow of each explained fragment)."""
    m = len(p)
    big = sum(weight.values()) + 1
    explained = {}
    for f, w in weight.items():
        i = _explained(f, p)
        if w > 0 and i >= 0:
            explained[f] = (i, i + len(f) - 1)
    cap: Dict[Tuple[int, int], float] = {}
    for i, v in enumerate(p):
        c = sum(weight[f] for f, (a, b) in explained.items() if a <= i <= b)
        cap[(2 + 2 * i, 3 + 2 * i)] = c
    for f, (a, b) in explained.items():
        cap[(3 + 2 * a, 2 + 2 * b)] = weight[f]
    cap[(0, 2)] = big
    cap[(3 + 2 * (m - 1), 1)] = big
    value, flow = edmonds_karp(2 + 2 * m, cap, 0, 1)
    return value, {f: flow[(3 + 2 * a, 2 + 2 * b)] for f, (a, b) in explained.items()}


def assemble(n: int, edges: Sequence[Tuple[int, int]], fragments: Dict[Sequence[int], float],
             c_min: float = 1.0) -> List[Tuple[List[int], float]]:
    """Return a list of (transcript path, abundance in reads)."""
    succ: List[List[int]] = [[] for _ in range(n)]
    pred: List[List[int]] = [[] for _ in range(n)]
    for u, v in sorted(set(edges)):
        if not u < v:
            raise ValueError("edges must go from a smaller to a larger node id")
        succ[u].append(v)
        pred[v].append(u)
    weight: Dict[Path, float] = {}
    for f, w in fragments.items():
        f = tuple(f)
        if any(v not in succ[u] for u, v in zip(f, f[1:])):
            raise ValueError("each fragment must be a path of the graph")
        if len(f) >= 2 and w > 0:
            weight[f] = weight.get(f, 0) + w

    def coverage(v: int) -> float:
        return sum(w for f, w in weight.items() if v in f)

    def score(u: int, q: Path) -> float:
        return sum(w for f, w in weight.items() if w > 0 and u in f and compatible(f, q))

    out: List[Tuple[List[int], float]] = []  # @line L1
    while n and max(coverage(v) for v in range(n)) >= c_min:  # @line L2
        cov = [coverage(v) for v in range(n)]
        start = max(range(n), key=lambda v: (cov[v], -v))  # @line L3
        p: Path = (start,)  # @line L4
        while True:  # @line L5
            best = max(((score(u, (u,) + p), -u) for u in pred[p[0]]), default=(0, 0))
            if best[0] <= 0:
                break
            p = (-best[1],) + p
        while True:  # @line L6
            best = max(((score(u, p + (u,)), -u) for u in succ[p[-1]]), default=(0, 0))
            if best[0] <= 0:
                break
            p = p + (-best[1],)
        value, gflow = path_flow(p, weight)  # @line L7
        if value >= c_min:  # @line L8
            out.append((list(p), value))  # @line L9
            for f, g in gflow.items():
                weight[f] -= g
        else:
            for f in weight:  # @line L10
                if start in f:
                    weight[f] = 0
    return out  # @line L11
test_flow_based_transcript_assembly.py 115 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/flow-based-transcript-assembly/. The authors are listed in prov/9XQGWM.jsonl.

import random
from itertools import product

from flow_based_transcript_assembly import assemble, compatible, edmonds_karp, path_flow


def brute_min_cut(n, cap, s, t):
    best = float("inf")
    others = [v for v in range(n) if v not in (s, t)]
    for side in product([0, 1], repeat=len(others)):
        S = {s} | {v for v, b in zip(others, side) if b}
        best = min(best, sum(c for (u, v), c in cap.items() if u in S and v not in S))
    return best


def test_edmonds_karp_against_min_cut():
    rng = random.Random(1)
    for _ in range(500):
        n = rng.randint(2, 6)
        cap = {(u, v): rng.randint(0, 9) for u in range(n) for v in range(u + 1, n) if rng.random() < 0.6}
        value, flow = edmonds_karp(n, cap, 0, n - 1)
        assert value == brute_min_cut(n, cap, 0, n - 1)
        for e, c in cap.items():
            assert 0 <= flow[e] <= c
        for v in range(1, n - 1):
            inflow = sum(f for (a, b), f in flow.items() if b == v)
            outflow = sum(f for (a, b), f in flow.items() if a == v)
            assert inflow == outflow


def test_worked_example():
    # A = 0, B = 1, C = 2. Fragments AB 30, BC 30 and AC 10.
    edges = [(0, 1), (1, 2), (0, 2)]
    out = assemble(3, edges, {(0, 1): 30, (1, 2): 30, (0, 2): 10})
    assert out == [([0, 1, 2], 30), ([0, 2], 10)]
    value, g = path_flow((0, 1, 2), {(0, 1): 30, (1, 2): 30, (0, 2): 10})
    assert value == 30 and g == {(0, 1): 30, (1, 2): 30}


def test_two_isoforms_are_recovered():
    # T1 = 0 1 2 3 with 50 reads per junction and T2 = 0 2 3 with 20; the junction 2 3 is shared.
    edges = [(0, 1), (1, 2), (2, 3), (0, 2)]
    frags = {(0, 1): 50, (1, 2): 50, (2, 3): 70, (0, 2): 20}
    assert assemble(4, edges, frags) == [([0, 1, 2, 3], 50), ([0, 2, 3], 20)]


def test_unphased_junctions_give_false_transcripts():
    # T1 = 0 1 2 3 4 with 10 reads per junction and T2 = 0 2 4 with 20. Junction reads alone
    # do not link the choice before node 2 to the choice after it.
    edges = [(0, 1), (1, 2), (2, 3), (3, 4), (0, 2), (2, 4)]
    frags = {(0, 1): 10, (1, 2): 10, (2, 3): 10, (3, 4): 10, (0, 2): 20, (2, 4): 20}
    assert assemble(5, edges, frags) == [([0, 2, 3, 4], 10), ([0, 1, 2, 4], 10), ([0, 2, 4], 10)]
    # One read that spans 1 2 3 links the two choices, and the true pair comes out.
    frags = {(0, 1): 10, (1, 2, 3): 10, (3, 4): 10, (0, 2): 20, (2, 4): 20}
    assert assemble(5, edges, frags) == [([0, 2, 4], 20), ([0, 1, 2, 3, 4], 10)]


def test_compatibility():
    assert compatible((0, 1), (0, 1, 2))
    assert compatible((1, 2, 3), (0, 1, 2))
    assert not compatible((0, 2), (0, 1, 2))
    assert not compatible((3, 4), (0, 1, 2))
    assert compatible((2, 5), (0, 1, 2))


def random_instance(rng):
    n = rng.randint(2, 7)
    edges = sorted({(u, u + 1) for u in range(n - 1)} |
                   {(u, v) for u in range(n) for v in range(u + 2, n) if rng.random() < 0.3})
    succ = {u: [v for a, v in edges if a == u] for u in range(n)}
    frags = {}
    for _ in range(rng.randint(1, 8)):
        f = [rng.randrange(n - 1)]
        for _ in range(rng.randint(1, 3)):
            if not succ[f[-1]]:
                break
            f.append(rng.choice(succ[f[-1]]))
        if len(f) >= 2:
            frags[tuple(f)] = frags.get(tuple(f), 0) + rng.randint(1, 40)
    return n, edges, frags


def test_random_graphs_terminate_with_valid_output():
    rng = random.Random(2)
    for _ in range(300):
        n, edges, frags = random_instance(rng)
        out = assemble(n, edges, frags, c_min=1)
        eset = set(edges)
        total = sum(frags.values())
        for p, a in out:
            assert len(p) >= 2 and all((u, v) in eset for u, v in zip(p, p[1:]))
            assert 1 <= a <= total
        assert len(out) <= sum(frags.values())


def test_single_isoform():
    rng = random.Random(3)
    for _ in range(100):
        n = rng.randint(3, 8)
        path = list(range(n))
        edges = [(u, u + 1) for u in range(n - 1)]
        frags = {}
        for _ in range(30):
            a = rng.randrange(n - 1)
            b = rng.randint(a + 1, min(n - 1, a + 3))
            frags[tuple(path[a:b + 1])] = frags.get(tuple(path[a:b + 1]), 0) + 1
        out = assemble(n, edges, frags)
        assert out
        # The first transcript is the whole path whenever the fragments chain from end to end.
        value, _ = path_flow(tuple(path), frags)
        if value >= 1:
            assert out[0] == (path, value)

History

Edmonds and Karp (1972) gave the shortest augmenting path rule for maximum flow. Vatinlen, Chauvet, Chrétienne and Mahey (2008) studied the decomposition of a flow into the fewest paths and greedy algorithms for it, and Hartman, Hassidim, Kaplan, Raz and Segalov (2012) showed that it stays hard for small flow values. Pertea, Pertea, Antonescu, Chang, Mendell and Salzberg (2015) combined the heaviest path and maximum flow in StringTie, so that assembly and quantification were done in one loop. Shao and Kingsford (2017) added phasing paths to the flow decomposition in Scallop.

References

  1. Mihaela Pertea, Geo M. Pertea, Corina M. Antonescu, Tsung-Cheng Chang, Joshua T. Mendell and Steven L. Salzberg, StringTie enables improved reconstruction of a transcriptome from RNA-seq reads, Nature Biotechnology 33(3) (2015), pp. 290 to 295, Online Methods (the splice graph, the heaviest path, the flow network and the removal of the flow)
  2. Benedicte Vatinlen, Fabrice Chauvet, Philippe Chrétienne and Philippe Mahey, Simple bounds and greedy algorithms for decomposing a flow into a minimal set of paths, European Journal of Operational Research 185(3) (2008), pp. 1390 to 1401
  3. Tzvika Hartman, Avinatan Hassidim, Haim Kaplan, Danny Raz and Michal Segalov, How to split a flow?, Proceedings of IEEE INFOCOM 2012, pp. 828 to 836 (minimum flow decomposition is NP-hard even with the flow values 1, 2 and 4)
  4. Mingfu Shao and Carl Kingsford, Accurate assembly of transcripts through phase-preserving graph decomposition, Nature Biotechnology 35(12) (2017), pp. 1167 to 1169
  5. Jack Edmonds and Richard M. Karp, Theoretical improvements in algorithmic efficiency for network flow problems, Journal of the ACM 19(2) (1972), pp. 248 to 264
  6. 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 (transcript assembly with network flows)

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