Algorithmintro
Exon chaining
Also called weighted interval chaining of exons.
Choose a set of non-overlapping candidate exons of maximum total weight by dynamic programming over their sorted end points.
- Time
- Θ(n log n) worst · average · best
- Space
- Θ(n) extra
- Where
- n = the number of candidate exons
- Model
- Word RAM
- Properties
- deterministicexactofflineiterative
- Evidence
- Proof sketchCode in 1 languages
Exon chaining chooses, from a list of candidate exons in a genomic sequence, a set of exons that do not overlap and whose total weight is as large as possible. Each candidate is an interval of the genome with a weight, for example the score of a local alignment of that interval with a related protein. The problem is weighted interval scheduling, and one sweep over the sorted end points solves it exactly in time. The chosen chain is a quick first model of the exon structure of a gene; the spliced alignment problem is the stricter version that also checks that the exons fit the protein in order.
In plain words
Somebody has marked some stretches of a genome that may be pieces of a gene, and has given each stretch a score: how much it looks like a piece of a known protein. Stretches can overlap, but the pieces of a real gene do not. We want the set of stretches with no overlaps and the largest total score. Walk along the genome from left to right and keep one number: the best total so far. When a stretch starts, write down that number next to it. When the stretch ends, see if the number written at its start plus its own score beats the best total so far, and if it does, take it. At the end, the best total is the answer, and the notes tell which stretches give it.
The problem
Input. A list of candidate exons . Exon covers the genome positions to , both included, with , and has a weight , a real number.
Output. A chain: a set of exons that pairwise do not overlap, listed from left to right, with the largest total weight. Two exons overlap when they share at least one position, so an exon that starts at the position where another ends overlaps it. The empty chain is allowed and has weight 0.
This is weighted interval scheduling with the genome as the time axis. Jones and Pevzner state it with positive weights and assume that all end points are distinct, so that no exon starts exactly where another ends. The version here drops both assumptions: it allows any weights and equal end points, and the rule for equal points is part of the algorithm.
The input does not say where the candidates come from. In the setting of Jones and Pevzner, they are the parts of the genome that are similar to a target protein or mRNA, extended or shortened so that they sit between AG and GT dinucleotides, and the weight is the local alignment score or a mix of that score and the strength of the splice sites. This is a different task from spliced read alignment and maximal mappable prefix alignment, which map millions of short RNA-seq reads to the genome; exon chaining and spliced alignment assemble one gene model from candidate exons and one related protein or transcript.
The algorithm
Sort the end points by position. At equal positions, put every left point before every right point, so that an exon that starts at position never counts as compatible with an exon that ends at . Then scan. The variable best is the weight of the best chain among the exons whose right end has been passed. At the left end of , store best as : by the order of the points, it is the best weight of a chain that ends before . At the right end of , the best chain that uses has weight , so compare it with best.
EXON-CHAINING(I_1, ..., I_n) ▷ I_j = (l_j, r_j, w_j) with l_j ≤ r_j- 1
P ← the 2n points (l_j, left, j) and (r_j, right, j) - 2
sort P by position, with left points before right points at equal positions - 3
best ← 0, last ← nil - 4
for each point (x, side, j) of P in sorted order do - 5
if side = left then - 6
s[j] ← best, pred[j] ← last - 7
else if s[j] + w_j > best then - 8
best ← s[j] + w_j, last ← j - 9
C ← the empty list, j ← last - 10
while j ≠ nil do put j at the front of C, j ← pred[j] - 11
return best, C
The variable last is the last exon of a best chain so far, and is the last exon of the best chain that ends before . Lines L9 and L10 follow these links back to rebuild the chain.
Jones and Pevzner write the same scan as a longest path in a graph with vertices, one per end point in sorted order, edges of weight 0 between neighbours and one edge of weight from to for each exon, so edges. With the longest path to the -th vertex, if vertex is the right end of an exon of weight whose left end is vertex , and otherwise. The pseudocode above keeps only the last value (as best) and the values at left ends (as ), and it adds the tie rule and the traceback. The graph is a DAG, so this is a special case of the longest path in a DAG.
Example
Take seven candidate exons:
| exon | |||
|---|---|---|---|
| A | 1 | 5 | 5 |
| B | 3 | 9 | 8 |
| C | 7 | 12 | 6 |
| D | 10 | 14 | 4 |
| E | 13 | 20 | 9 |
| F | 15 | 18 | 3 |
| G | 21 | 24 | 5 |
The sorted points and the actions of the scan are:
| position | point | line | action | best |
|---|---|---|---|---|
| 1 | left of A | L6 | 0 | |
| 3 | left of B | L6 | 0 | |
| 5 | right of A | L7, L8 | 5, last A | |
| 7 | left of C | L6 | , | 5 |
| 9 | right of B | L7, L8 | 8, last B | |
| 10 | left of D | L6 | , | 8 |
| 12 | right of C | L7, L8 | 11, last C | |
| 13 | left of E | L6 | , | 11 |
| 14 | right of D | L7, L8 | 12, last D | |
| 15 | left of F | L6 | , | 12 |
| 18 | right of F | L7, L8 | 15, last F | |
| 20 | right of E | L7, L8 | 20, last E | |
| 21 | left of G | L6 | , | 20 |
| 24 | right of G | L7, L8 | 25, last G |
The traceback goes G, E, C, A, so the best chain is A, C, E, G with weight . The next best chain is B, E, G with weight 22. The exon B has the largest single weight but is not in the best chain. At position 13, E starts before D ends at 14, so is 11 and not 12: D and E overlap. The test file checks this example and compares the result with a search over all subsets.
Correctness
The proof is an induction over the sorted points. Let be the set of exons whose right point has been handled.
- When the scan reaches the left point of , the set is exactly the set of exons with . An exon with is not in it, because left points sort first at equal positions.
- At the right point of , every exon of a chain inside has its right end at most . In a chain that uses , the other exons do not overlap , so they all end before . Their best weight is .
- So the best weight inside is , which is what lines L7 and L8 compute.
At the end holds every exon, so best is the optimum (a theorem). The links are written once, and each one points to an exon that ends before the current exon starts, so the traceback stops and gives a chain of weight best. The full proof is in the proofs folder.
Proof: The sweep over the end points returns a chain of maximum weightfull
The input is a list of exons with integers and real weights . Two exons overlap when the closed intervals and share a position. A chain is a set of pairwise non-overlapping exons, and its weight is the sum of their weights. The empty chain has weight 0. For a set of exons, is the largest weight of a chain whose exons are all in . Since the empty chain is allowed, .
Order of the points. Line L1 makes the points and , where 0 means a left point and 1 a right point. Line L2 sorts them as tuples, so a point with a smaller position comes first, and at equal positions every left point comes before every right point. Let be the sorted list. For , let be the set of exons whose right point is among .
Lemma 1. If is the left point of exon , then .
Proof. Take an exon . If , the right point of has a smaller position than , so it comes earlier and . If , the right point of comes later. If , the right point comes after the left point by the second key. So in both cases. This also holds for , because .
Lemma 2. Let exon and a chain be given, and let every exon of have . Then every exon of has .
Proof. The exons and do not overlap, so or . In the second case , which is false.
Lemma 3 (invariant). After line L4 has handled , the variable best is . For each exon whose left point is among , the value is .
Proof. By induction on . For , line L3 sets best to , and no is claimed.
Let . If is the left point of exon , line L6 sets to best, which is by the hypothesis. By Lemma 1 this is . No right point is handled, so and best stays correct. No other value changes, because each exon has one left point.
If is the right point of exon , then . The left point of comes before , so is already set and correct. A best chain in either does not hold , and then its weight is at most , or it holds . In the second case, every exon of the chain is in , so its right point is not after , and its right end is at most . By Lemma 2, the other exons have , so their weight is at most . So . Both values are reached: the first by a chain in , and the second by a best chain in with added, which is a chain because each of its exons ends before , and whose exons are in by Lemma 1. Lines L7 and L8 set best to the larger of the two values.
At the end holds every exon, so best is the weight of a best chain.
Lemma 4 (the chain). Define as the empty list and followed by . Whenever best and last are read or written, is a chain of weight best, listed from left to right, whose exons all have their right point already handled.
Proof. Each is written once, at the left point of , and never changes after that. At line L3 the claim holds with . Line L6 copies last into when the handled right points are those of (Lemma 1). So is a chain of weight whose exons all end before . Then, when line L8 sets , the list is that chain followed by : it is a chain, it is in order from left to right, and its weight is , the new best.
Lines L9 and L10 build . The loop stops, because each step goes from to an exon whose right end is less than , so the right ends strictly decrease. So line L11 returns a best weight and a chain with that weight.
Remarks. An exon with is never put in the chain: best never decreases, and is an earlier value of best, so best and the strict test of line L7 fails. If all weights are at most 0, the result is . Among best chains, the strict test keeps the first one found, so the last exon of the returned chain has the leftmost right point among the last exons of all best chains.
Cost. Line L2 sorts tuples in time. The loop of line L4 does work per point, and the loop of line L10 does at most steps. The arrays and and the list of points take space. If the end points are already sorted, or are integers in a range of size that a counting sort can sort, the whole method runs in time.
Complexity
- Time. On a word RAM with positions that fit in a word, line L2 sorts points in time with a comparison sort. The loop of line L4 does work per point, and the traceback takes at most steps. So the total is , and the sort is the only part above linear. If the points come sorted, for example from a scan along the genome, or if the positions are integers in a range of size , a counting sort or a merge of two sorted lists makes the whole method run in time.
- Lower bound. For general interval scheduling, the sort cannot be avoided in the algebraic decision tree model; the weighted interval scheduling page gives the bound.
- Space. for the points and the arrays and .
The cost to find the candidate exons is not part of this. If they come from local alignments of a genome of length with a protein of length , that step costs with Smith-Waterman, and it is much more than the chaining.
Properties
- Exact. It returns a chain of the largest total weight; there is no approximation.
- Weights of any sign. An exon with is never chosen, because it cannot raise
best. Fractions and integers give exact results. - Tie rule. The strict test of line L7 keeps the first best chain found. Of all best chains, the returned one has the leftmost right end of its last exon.
- Only overlap counts. The weight of a chain is a plain sum. The chain does not know the order of the exons along the target protein, the reading frame, or the lengths of the introns between them.
- Not online. It needs all candidates before the scan, because it sorts them. If the candidates arrive in order of their left ends and the right ends are handled with a priority queue, the same scan runs as a stream.
Variants and improvements
- Equal weights. If all exons have the same weight, the best chain is a largest set of disjoint intervals. The greedy rule "take the exon with the leftmost right end, drop the ones that overlap it, repeat" finds it. This is Problem 6.56 of Jones and Pevzner and the unweighted interval scheduling problem.
- The textbook form. Sort the exons by right end, find with binary search the last exon that ends before , and set . This is the form of Kleinberg and Tardos. It gives the same value; the test file uses it as a second method.
- Order along the target. The best chain may join an exon that matches the end of the protein with a later exon that matches its start (figure 6.27 of Jones and Pevzner). If each candidate also has an interval on the target, ask for a chain that increases in both the genome and the target. This is colinear chaining, which still runs in time with a range maximum tree.
- Rules between neighbours. A minimum intron length, a compatible reading frame, or a penalty for each intron depends on the pair of consecutive exons. Then the chain is a path in a DAG with an edge for each allowed pair, which costs time in general, and less if the rule is a simple distance rule that a range query can handle.
- Spliced alignment. Score a chain by the alignment of the joined exons with the target, not by a sum of separate scores. This is the spliced alignment problem of Gelfand, Mironov and Pevzner, solved by dynamic programming over the candidate blocks.
- Gene finders. A generalized HMM gene finder also builds the best chain of exons, but with scores for the exons, the introns and the signals between them, and with frame and strand rules. Exon chaining is the simplest case of that dynamic program.
When to use it
Use it to turn a set of local hits of a protein or a transcript on a genome into a first gene model, when speed matters more than a full alignment. It is also the right tool for any selection of disjoint weighted intervals on a line: hits of a profile, ORFs, or seeds on one sequence. When the order along the target matters, use colinear chaining or seed chaining; when the exon boundaries and the alignment both matter, use spliced alignment. To map RNA-seq reads, use a read aligner such as spliced read alignment; exon chaining does not map reads.
Pitfalls
- Ties at shared positions. Sort left points first at equal positions, or treat exons as half-open intervals and say so. If right points sort first, two exons that share one base both enter the chain.
- Distinct points in the book. The graph of Jones and Pevzner assumes that no two end points are equal. Code that copies it without a tie rule gives wrong chains on real candidate sets, where many exons share a splice site.
- The best chain is not always a gene. A large weight can come from exons that match the target in the wrong order or in different frames. Check the order along the target, or use colinear chaining or spliced alignment. This is a limit of the model, not of the algorithm.
- Fixed ends. The candidate ends are fixed before the chain is chosen, so an exon with a slightly wrong end cannot be moved to fit its neighbour. Spliced alignment has the same issue in a smaller form.
- Both strands. Candidates on the plus and the minus strand can overlap in the genome but belong to different genes. Chain each strand on its own.
- Recursion. The memoized recursive form of Kleinberg and Tardos needs a depth of . Use the loop.
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/exon-chaining/. The authors are listed in prov/BSR162.jsonl.
"""Exon chaining: a set of non-overlapping candidate exons of maximum total weight.
Coordinates follow the page: an exon is the closed interval [left, right] of
1-based genome positions, with left <= right. Two exons overlap when they share
a position, so an exon that starts at the position where another ends overlaps
it. A chain is a set of pairwise non-overlapping exons; the empty chain has
weight 0.
"""
from typing import List, NamedTuple, Sequence, Tuple, Union
Number = Union[int, float]
LEFT, RIGHT = 0, 1 # at equal positions, left points sort before right points
class Exon(NamedTuple):
"""A candidate exon: the positions left to right (1-based, inclusive) and a weight."""
left: int
right: int
weight: Number
def exon_chaining(exons: Sequence[Exon]) -> Tuple[Number, List[int]]:
"""Return (best, chain): the largest total weight of a chain and one chain with it.
chain lists indices into exons from left to right along the genome. Weights
may be any numbers; an exon with weight <= 0 is never used, and if no
exon has a positive weight the result is (0, []). Among chains with the
best weight, the one whose last exon has the leftmost right end point is
returned (the strict test of line L7).
Cost: O(n log n) time for the sort and O(n) for the scan, O(n) space.
"""
n = len(exons)
for e in exons:
if e.left > e.right:
raise ValueError("an exon needs left <= right")
points = [(e.left, LEFT, j) for j, e in enumerate(exons)] # @line L1
points += [(e.right, RIGHT, j) for j, e in enumerate(exons)]
points.sort() # @line L2
best: Number = 0 # @line L3
last = -1
s: List[Number] = [0] * n
pred = [-1] * n
for _, side, j in points: # @line L4
if side == LEFT: # @line L5
s[j], pred[j] = best, last # @line L6
elif s[j] + exons[j].weight > best: # @line L7
best, last = s[j] + exons[j].weight, j # @line L8
chain: List[int] = [] # @line L9
j = last
while j != -1: # @line L10
chain.append(j)
j = pred[j]
chain.reverse()
return best, chain # @line L11
def is_chain(exons: Sequence[Exon], chain: Sequence[int]) -> bool:
"""True if the listed exons are distinct, in genome order and pairwise non-overlapping."""
for a, b in zip(chain, chain[1:]):
if exons[a].right >= exons[b].left:
return False
return len(set(chain)) == len(chain)
def chain_weight(exons: Sequence[Exon], chain: Sequence[int]) -> Number:
"""The total weight of the listed exons."""
return sum((exons[j].weight for j in chain), 0)
test_exon_chaining.py 108 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/exon-chaining/. The authors are listed in prov/BSR162.jsonl.
"""Tests of exon chaining against brute force over all subsets and a second method."""
import bisect
import itertools
import random
import unittest
from fractions import Fraction
from exon_chaining import Exon, chain_weight, exon_chaining, is_chain
PAGE_EXAMPLE = [
Exon(1, 5, 5),
Exon(3, 9, 8),
Exon(7, 12, 6),
Exon(10, 14, 4),
Exon(13, 20, 9),
Exon(15, 18, 3),
Exon(21, 24, 5),
]
def brute_force(exons):
"""The best weight over all subsets of pairwise non-overlapping exons."""
best = 0
order = sorted(range(len(exons)), key=lambda j: (exons[j].left, exons[j].right))
for r in range(1, len(exons) + 1):
for subset in itertools.combinations(order, r):
if is_chain(exons, subset):
best = max(best, chain_weight(exons, subset))
return best
def by_right_ends(exons):
"""Weighted interval scheduling in the textbook form: sort by right end, binary search."""
order = sorted(range(len(exons)), key=lambda j: exons[j].right)
rights = [exons[j].right for j in order]
opt = [0] * (len(order) + 1)
for t, j in enumerate(order, 1):
p = bisect.bisect_left(rights, exons[j].left) # exons with right < left
opt[t] = max(opt[t - 1], opt[p] + exons[j].weight)
return opt[-1]
def random_exons(rng, n, span, wmax, allow_negative=False):
out = []
for _ in range(n):
a = rng.randint(1, span)
b = rng.randint(a, min(span, a + rng.randint(0, span // 3)))
lo = -wmax if allow_negative else 1
out.append(Exon(a, b, rng.randint(lo, wmax)))
return out
class TestExonChaining(unittest.TestCase):
def test_page_example(self):
best, chain = exon_chaining(PAGE_EXAMPLE)
self.assertEqual(best, 25)
self.assertEqual(chain, [0, 2, 4, 6])
self.assertTrue(is_chain(PAGE_EXAMPLE, chain))
self.assertEqual(brute_force(PAGE_EXAMPLE), 25)
def test_empty_and_single(self):
self.assertEqual(exon_chaining([]), (0, []))
self.assertEqual(exon_chaining([Exon(4, 4, 7)]), (7, [0]))
self.assertEqual(exon_chaining([Exon(4, 9, -2)]), (0, []))
def test_touching_exons_overlap(self):
exons = [Exon(1, 5, 3), Exon(5, 9, 4)]
self.assertEqual(exon_chaining(exons), (4, [1]))
exons = [Exon(1, 5, 3), Exon(6, 9, 4)]
self.assertEqual(exon_chaining(exons), (7, [0, 1]))
def test_against_brute_force(self):
rng = random.Random(20261118)
for trial in range(300):
n = rng.randint(1, 9)
exons = random_exons(rng, n, 30, 10, allow_negative=(trial % 3 == 0))
best, chain = exon_chaining(exons)
self.assertEqual(best, brute_force(exons))
self.assertTrue(is_chain(exons, chain))
self.assertEqual(chain_weight(exons, chain), best)
def test_against_right_end_method(self):
rng = random.Random(7)
for _ in range(200):
exons = random_exons(rng, rng.randint(1, 60), 200, 50)
best, chain = exon_chaining(exons)
self.assertEqual(best, by_right_ends(exons))
self.assertEqual(chain_weight(exons, chain), best)
def test_fraction_weights(self):
rng = random.Random(3)
for _ in range(50):
exons = [Exon(e.left, e.right, Fraction(e.weight, rng.randint(1, 7)))
for e in random_exons(rng, 8, 25, 9)]
best, chain = exon_chaining(exons)
self.assertEqual(best, brute_force(exons))
self.assertEqual(chain_weight(exons, chain), best)
def test_bad_interval(self):
with self.assertRaises(ValueError):
exon_chaining([Exon(5, 4, 1)])
if __name__ == "__main__":
unittest.main()
History
Weighted interval scheduling is a standard first example of dynamic programming in algorithm textbooks, for example Section 6.1 of Kleinberg and Tardos (2005). Jones and Pevzner (2004) present it as the Exon Chaining problem in Section 6.13 of their textbook, with candidate exons from similarity to a target protein, and they show its main weakness: a chain of separate high scores need not form one valid alignment. Gelfand, Mironov and Pevzner (1996) had already given the stronger formulation, spliced alignment, which scores the whole chain by one alignment with the target.
References
- Neil C. Jones and Pavel A. Pevzner, An Introduction to Bioinformatics Algorithms, MIT Press, 2004, Section 6.13, Similarity-Based Approaches to Gene Prediction (the Exon Chaining problem on p. 201, the algorithm ExonChaining, and figures 6.26 and 6.27); Problem 6.56
- Jon Kleinberg and Eva Tardos, Algorithm Design, Addison-Wesley, 2005, Section 6.1, Weighted Interval Scheduling, A Recursive Procedure
- Mikhail S. Gelfand, Andrey A. Mironov and Pavel A. Pevzner, Gene recognition via spliced sequence alignment, Proceedings of the National Academy of Sciences USA 93(17), 1996, pp. 9061 to 9066; the spliced alignment that replaces a plain chain of exon scores by one alignment with the target protein
Where this leads
About this page
The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.
| 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 BSR162 Edit this page History Report an error Markdown