Algorithm Search⌘K

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
Properties
deterministicexactofflineiterative

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 2n2n sorted end points solves it exactly in O(nlog⁡n)O(n \log n) 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 nn candidate exons I1,…,InI_1, \ldots, I_n. Exon Ij=(lj,rj,wj)I_j = (l_j, r_j, w_j) covers the genome positions ljl_j to rjr_j, both included, with 1≤lj≤rj1 \le l_j \le r_j, and has a weight wjw_j, 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 2n2n 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 2n2n end points by position. At equal positions, put every left point before every right point, so that an exon that starts at position xx never counts as compatible with an exon that ends at xx. 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 IjI_j, store best as s[j]s[j]: by the order of the points, it is the best weight of a chain that ends before ljl_j. At the right end of IjI_j, the best chain that uses IjI_j has weight s[j]+wjs[j] + w_j, so compare it with best.

  1. EXON-CHAINING(I_1, ..., I_n) ▷ I_j = (l_j, r_j, w_j) with l_j ≤ r_j
  2. 1P ← the 2n points (l_j, left, j) and (r_j, right, j)
  3. 2sort P by position, with left points before right points at equal positions
  4. 3best ← 0, last ← nil
  5. 4for each point (x, side, j) of P in sorted order do
  6. 5if side = left then
  7. 6s[j] ← best, pred[j] ← last
  8. 7else if s[j] + w_j > best then
  9. 8best ← s[j] + w_j, last ← j
  10. 9C ← the empty list, j ← last
  11. 10while j ≠ nil do put j at the front of C, j ← pred[j]
  12. 11return best, C

The variable last is the last exon of a best chain so far, and pred[j]\mathit{pred}[j] is the last exon of the best chain that ends before IjI_j. 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 2n2n vertices, one per end point in sorted order, 2n−12n - 1 edges of weight 0 between neighbours and one edge of weight wjw_j from ljl_j to rjr_j for each exon, so 3n−13n - 1 edges. With sis_i the longest path to the ii-th vertex, si=max⁡(si−1,si′+w)s_i = \max(s_{i-1}, s_{i'} + w) if vertex ii is the right end of an exon of weight ww whose left end is vertex i′i', and si=si−1s_i = s_{i-1} otherwise. The pseudocode above keeps only the last value si−1s_{i-1} (as best) and the values at left ends (as s[j]s[j]), 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 ll rr ww
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 s[A]=0s[A] = 0 0
3 left of B L6 s[B]=0s[B] = 0 0
5 right of A L7, L8 0+5=5>00 + 5 = 5 > 0 5, last A
7 left of C L6 s[C]=5s[C] = 5, pred[C]=A\mathit{pred}[C] = A 5
9 right of B L7, L8 0+8=8>50 + 8 = 8 > 5 8, last B
10 left of D L6 s[D]=8s[D] = 8, pred[D]=B\mathit{pred}[D] = B 8
12 right of C L7, L8 5+6=11>85 + 6 = 11 > 8 11, last C
13 left of E L6 s[E]=11s[E] = 11, pred[E]=C\mathit{pred}[E] = C 11
14 right of D L7, L8 8+4=12>118 + 4 = 12 > 11 12, last D
15 left of F L6 s[F]=12s[F] = 12, pred[F]=D\mathit{pred}[F] = D 12
18 right of F L7, L8 12+3=15>1212 + 3 = 15 > 12 15, last F
20 right of E L7, L8 11+9=20>1511 + 9 = 20 > 15 20, last E
21 left of G L6 s[G]=20s[G] = 20, pred[G]=E\mathit{pred}[G] = E 20
24 right of G L7, L8 20+5=25>2020 + 5 = 25 > 20 25, last G

The traceback goes G, E, C, A, so the best chain is A, C, E, G with weight 5+6+9+5=255 + 6 + 9 + 5 = 25. 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 s[E]s[E] 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 RR be the set of exons whose right point has been handled.

  1. When the scan reaches the left point of IjI_j, the set RR is exactly the set of exons with ri<ljr_i < l_j. An exon with ri=ljr_i = l_j is not in it, because left points sort first at equal positions.
  2. At the right point of IjI_j, every exon of a chain inside R∪{Ij}R \cup \{I_j\} has its right end at most rjr_j. In a chain that uses IjI_j, the other exons do not overlap IjI_j, so they all end before ljl_j. Their best weight is s[j]s[j].
  3. So the best weight inside R∪{Ij}R \cup \{I_j\} is max⁡(best,s[j]+wj)\max(\mathit{best}, s[j] + w_j), which is what lines L7 and L8 compute.

At the end RR holds every exon, so best is the optimum (a theorem). The links pred\mathit{pred} 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 nn exons Ij=(lj,rj,wj)I_j = (l_j, r_j, w_j) with integers lj≤rjl_j \le r_j and real weights wjw_j. Two exons overlap when the closed intervals [li,ri][l_i, r_i] and [lj,rj][l_j, r_j] 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 XX of exons, OPT(X)\mathrm{OPT}(X) is the largest weight of a chain whose exons are all in XX. Since the empty chain is allowed, OPT(X)≥0\mathrm{OPT}(X) \ge 0.

Order of the points. Line L1 makes the 2n2n points (lj,0,j)(l_j, 0, j) and (rj,1,j)(r_j, 1, j), 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 p1,p2,…,p2np_1, p_2, \ldots, p_{2n} be the sorted list. For t=0,1,…,2nt = 0, 1, \ldots, 2n, let RtR_t be the set of exons whose right point is among p1,…,ptp_1, \ldots, p_t.

Lemma 1. If ptp_t is the left point of exon jj, then Rt−1={i:ri<lj}R_{t-1} = \{ i : r_i < l_j \}.

Proof. Take an exon ii. If ri<ljr_i < l_j, the right point of ii has a smaller position than ptp_t, so it comes earlier and i∈Rt−1i \in R_{t-1}. If ri>ljr_i > l_j, the right point of ii comes later. If ri=ljr_i = l_j, the right point (lj,1,i)(l_j, 1, i) comes after the left point (lj,0,j)(l_j, 0, j) by the second key. So i∉Rt−1i \notin R_{t-1} in both cases. This also holds for i=ji = j, because rj≥ljr_j \ge l_j. □\square

Lemma 2. Let exon jj and a chain C∋jC \ni j be given, and let every exon of CC have ri≤rjr_i \le r_j. Then every exon i≠ji \ne j of CC has ri<ljr_i < l_j.

Proof. The exons ii and jj do not overlap, so ri<ljr_i < l_j or rj<lir_j < l_i. In the second case rj<li≤rir_j < l_i \le r_i, which is false. □\square

Lemma 3 (invariant). After line L4 has handled p1,…,ptp_1, \ldots, p_t, the variable best is OPT(Rt)\mathrm{OPT}(R_t). For each exon jj whose left point is among p1,…,ptp_1, \ldots, p_t, the value s[j]s[j] is OPT({i:ri<lj})\mathrm{OPT}(\{ i : r_i < l_j \}).

Proof. By induction on tt. For t=0t = 0, line L3 sets best to 0=OPT(∅)0 = \mathrm{OPT}(\emptyset), and no s[j]s[j] is claimed.

Let t≥1t \ge 1. If ptp_t is the left point of exon jj, line L6 sets s[j]s[j] to best, which is OPT(Rt−1)\mathrm{OPT}(R_{t-1}) by the hypothesis. By Lemma 1 this is OPT({i:ri<lj})\mathrm{OPT}(\{ i : r_i < l_j \}). No right point is handled, so Rt=Rt−1R_t = R_{t-1} and best stays correct. No other ss value changes, because each exon has one left point.

If ptp_t is the right point of exon jj, then Rt=Rt−1∪{j}R_t = R_{t-1} \cup \{ j \}. The left point of jj comes before ptp_t, so s[j]s[j] is already set and correct. A best chain in RtR_t either does not hold jj, and then its weight is at most OPT(Rt−1)\mathrm{OPT}(R_{t-1}), or it holds jj. In the second case, every exon of the chain is in RtR_t, so its right point is not after ptp_t, and its right end is at most rjr_j. By Lemma 2, the other exons have ri<ljr_i < l_j, so their weight is at most s[j]s[j]. So OPT(Rt)≤max⁡(OPT(Rt−1),s[j]+wj)\mathrm{OPT}(R_t) \le \max(\mathrm{OPT}(R_{t-1}), s[j] + w_j). Both values are reached: the first by a chain in Rt−1⊆RtR_{t-1} \subseteq R_t, and the second by a best chain in {i:ri<lj}\{ i : r_i < l_j \} with jj added, which is a chain because each of its exons ends before ljl_j, and whose exons are in RtR_t by Lemma 1. Lines L7 and L8 set best to the larger of the two values. □\square

At the end R2nR_{2n} holds every exon, so best is the weight of a best chain.

Lemma 4 (the chain). Define ch(nil)\mathrm{ch}(\mathit{nil}) as the empty list and ch(j)=ch(pred[j])\mathrm{ch}(j) = \mathrm{ch}(\mathit{pred}[j]) followed by jj. Whenever best and last are read or written, ch(last)\mathrm{ch}(\mathit{last}) is a chain of weight best, listed from left to right, whose exons all have their right point already handled.

Proof. Each pred[j]\mathit{pred}[j] is written once, at the left point of jj, and never changes after that. At line L3 the claim holds with last=nil\mathit{last} = \mathit{nil}. Line L6 copies last into pred[j]\mathit{pred}[j] when the handled right points are those of {i:ri<lj}\{ i : r_i < l_j \} (Lemma 1). So ch(pred[j])\mathrm{ch}(\mathit{pred}[j]) is a chain of weight s[j]s[j] whose exons all end before ljl_j. Then, when line L8 sets last=j\mathit{last} = j, the list ch(j)\mathrm{ch}(j) is that chain followed by jj: it is a chain, it is in order from left to right, and its weight is s[j]+wjs[j] + w_j, the new best. □\square

Lines L9 and L10 build ch(last)\mathrm{ch}(\mathit{last}). The loop stops, because each step goes from jj to an exon whose right end is less than lj≤rjl_j \le r_j, so the right ends strictly decrease. So line L11 returns a best weight and a chain with that weight. ■\blacksquare

Remarks. An exon with wj≤0w_j \le 0 is never put in the chain: best never decreases, and s[j]s[j] is an earlier value of best, so s[j]+wj≤s[j] + w_j \le best and the strict test of line L7 fails. If all weights are at most 0, the result is (0,[ ])(0, [\,]). 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 2n2n tuples in O(nlog⁡n)O(n \log n) time. The loop of line L4 does O(1)O(1) work per point, and the loop of line L10 does at most nn steps. The arrays ss and pred\mathit{pred} and the list of points take O(n)O(n) space. If the end points are already sorted, or are integers in a range of size O(n)O(n) that a counting sort can sort, the whole method runs in O(n)O(n) time.

Complexity

  • Time. On a word RAM with positions that fit in a word, line L2 sorts 2n2n points in O(nlog⁡n)O(n \log n) time with a comparison sort. The loop of line L4 does O(1)O(1) work per point, and the traceback takes at most nn steps. So the total is Θ(nlog⁡n)\Theta(n \log n), 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 O(n)O(n), a counting sort or a merge of two sorted lists makes the whole method run in O(n)O(n) 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. Θ(n)\Theta(n) for the points and the arrays ss and pred\mathit{pred}.

The cost to find the candidate exons is not part of this. If they come from local alignments of a genome of length GG with a protein of length mm, that step costs O(Gm)O(G m) 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 wj≤0w_j \le 0 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 p(j)p(j) that ends before ljl_j, and set OPT(j)=max⁡(OPT(j−1),OPT(p(j))+wj)\mathrm{OPT}(j) = \max(\mathrm{OPT}(j - 1), \mathrm{OPT}(p(j)) + w_j). 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 O(nlog⁡n)O(n \log n) 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 O(n2)O(n^2) 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 nn. 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.

exon_chaining.pyI0RawGitHub
# 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

  1. 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
  2. Jon Kleinberg and Eva Tardos, Algorithm Design, Addison-Wesley, 2005, Section 6.1, Weighted Interval Scheduling, A Recursive Procedure
  3. 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.

LadderLevelWhat the next level needs
Human proofH1 sketch
  • a full proof of time.average
  • a full proof of time.best
  • 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
  • History with a source
  • a scene preset for the example