Algorithm Search⌘K

Algorithmintro

Branch-and-bound motif search

Also called branch-and-bound median string search.

Search the tree of l-mers or of motif start positions and prune a subtree when a bound shows it cannot beat the best score so far.

Time
O(4^L n W) worstO(L n W) bestO(L W^n) position_tree_worst
Space
O(n W + L) extra
Where
G = the length of each sequence; L = the motif length; W = the number of windows per sequence, G - L + 1; n = the number of sequences
Properties
deterministicexactofflinerecursive
Origin
Neil C. Jones, Pavel A. Pevzner, 2004

Branch-and-bound motif search finds an optimal solution of the motif finding problem with the total Hamming distance score, without a test of every candidate. It walks a search tree depth first, keeps the best complete score found so far, and cuts a subtree when a lower bound shows that no leaf below it can do better. There are two trees: the tree of start positions, with WnW^n leaves, and the tree of prefixes of the candidate median string, with 4L4^L leaves. The worst case is the same as exhaustive search, but on real and planted data most of the tree is cut.

In plain words

Exhaustive search tries every candidate. Branch and bound tries the candidates in an order where they share their beginnings, like words in a dictionary. While it builds a candidate letter by letter, it keeps count of the mistakes that the part built so far already makes. Mistakes never go away when you add more letters. So if the part built so far already makes as many mistakes as the best full answer you have found, you skip every candidate that starts with that part.

The same trick works when you pick one window in each sequence: pick the windows one sequence at a time, and stop when the windows picked so far already disagree too much.

The problem

Input. DNA sequences s1,…,sns_1, \ldots, s_n, each of length GG, and a motif length L≤GL \le G. Each sequence has W=G−L+1W = G - L + 1 windows. Positions are 1-based on this page and 0-based in the code.

Output, position tree. Starts p=(p1,…,pn)p = (p_1, \ldots, p_n) that minimize Score(p)=∑j(n−max⁡acj(a))\mathrm{Score}(p) = \sum_j (n - \max_a c_j(a)), where cj(a)c_j(a) counts the letter aa in column jj of the chosen windows.

Output, prefix tree. A string vv of length LL that minimizes D(v)=∑imin⁡qdH(v,si[q..q+L−1])D(v) = \sum_i \min_q d_H(v, s_i[q .. q + L - 1]).

The two optimal values are equal, and each optimum gives the other (see the median string problem).

The algorithm

The position tree. A node at depth ii fixes the starts of the first ii sequences. Its partial score is the motif score of those ii rows, ∑j(i−max⁡acj(a))\sum_j (i - \max_a c_j(a)). Adding a row raises ii by one and each max⁡acj(a)\max_a c_j(a) by at most one, so the partial score never drops on the way down. A node whose partial score is not below the best complete score can be cut.

The prefix tree. A node at depth kk is a prefix uu of length kk. For each sequence ii and window qq, let m[i][q]=dH(u,si[q..q+k−1])m[i][q] = d_H(u, s_i[q .. q + k - 1]), the mismatches of uu with the first kk letters of the window. The mismatches of a prefix stay when the string grows, so ∑imin⁡qm[i][q]\sum_i \min_q m[i][q] is a lower bound on D(v)D(v) for every extension vv of uu, and it equals D(u)D(u) at a leaf.

  1. BB-MOTIF(s[1 .. n], L)
  2. 1best ← nL + 1, bestp ← none
  3. 2c_j(a) ← 0 for every column j and letter a
  4. 3SEARCH(1)
  5. 4return bestp, best
  6. SEARCH(i)
  7. 5if i > n then
  8. 6sc ← Σ_j (n - max_a c_j(a))
  9. 7if sc < best then best ← sc, bestp ← (p_1, ..., p_n)
  10. 8return
  11. 9for q ← 1 to W do
  12. 10p_i ← q, add the letters of s_i[q .. q + L - 1] to the counts c
  13. 11if Σ_j (i - max_a c_j(a)) < best then SEARCH(i + 1)
  14. 12remove the letters of s_i[q .. q + L - 1] from the counts c
  15. BB-MEDIAN(s[1 .. n], L)
  16. 13best ← nL + 1, bestv ← none
  17. 14m[i][q] ← 0 for every sequence i and window q
  18. 15EXTEND(empty string, 0)
  19. 16return bestv, best
  20. EXTEND(u, k)
  21. 17bound ← Σ_i min_q m[i][q]
  22. 18if bound ≥ best then return
  23. 19if k = L then best ← bound, bestv ← u, return
  24. 20for a in A, C, G, T do
  25. 21for every i and q: if s_i[q + k] ≠ a then m[i][q] ← m[i][q] + 1
  26. 22EXTEND(ua, k + 1)
  27. 23for every i and q: if s_i[q + k] ≠ a then m[i][q] ← m[i][q] - 1

Lines L1 to L12 are the search on start positions. The start value nL+1nL + 1 of line L1 is larger than any score, so the first leaf always sets the best. Line L11 is the cut: the partial score of the first ii rows is a lower bound on the score of every leaf below. Lines L13 to L23 are the search on prefixes. Line L21 adds the column k+1k + 1 of each window to the counts when the prefix gets the letter aa, and line L23 undoes it. Both searches test with a strict inequality, so a later leaf replaces the best only when it is strictly better, and the result is the first optimum in the order of the tree.

Example

Take the five sequences of Rosalind problem BA2D, GGCGTTCAGGCA, AAGAATCAGTCA, CAAGGAGTTCGC, CACGTCAATCAC and CAATAATATTCG, with L=3L = 3, so W=10W = 10. The prefix tree has 1+4+16+64=851 + 4 + 16 + 64 = 85 nodes. BB-MEDIAN visits 45 of them, in this order of events:

prefix uu bound best before action
(root), A, AA 0, 0, 1 16 go down
AAA 6 16 leaf: best ← 6
AAC 6 6 cut (not below 6)
AAG 3 6 leaf: best ← 3
AAT, AC 3, 4 3 cut
AG, AT 2, 2 3 go down; all eight leaves have bound 3 to 6, cut
C, CA 0, 0 3 go down
CAA 2 3 leaf: best ← 2
CAC, CAG, CAT, CC, CG, CT 4, 3, 5, 5, 2, 5 2 cut
G 1 2 go down; GA, GC, GG cut; GT has bound 1, its leaves 3 to 6 are cut
T, TC 0, 0 2 go down; TCA has bound 2, which is not below 2, so it is cut
TA, TG, TT 4, 5, 2 2 cut

The result is CAA with D=2D = 2. TCA and TTC are also median strings, but the strict test keeps the first one. The position tree on the same input has 1+10+⋯+105=111,1111 + 10 + \cdots + 10^5 = 111{,}111 nodes, and BB-MOTIF visits 166 of them. It returns the 0-based starts (4, 4, 7, 3, 8), the windows TTC, ATC, TTC, GTC and TTC, with score 2.

Measured pruning on planted motifs. The test generator plants a motif of length 8 with exactly one change in each of 10 random sequences of length 100. On seeds 0, 1 and 2, BB-MEDIAN visits 12,757, 6,677 and 8,921 of the 87,381 nodes of the prefix tree, and returns the planted motif each time, with D=10D = 10. These are measurements on three inputs, not a bound.

Correctness

Both searches have the same shape. The bound at a node is at most the score of every leaf below it, and at a leaf it equals the score. A subtree is cut only when its bound is not below the best score found, so the cut removes no leaf that is strictly better than the current best. Every leaf that is not cut is reached, so the best of the reached leaves is optimal. For the position tree, the bound is the partial score, and the key fact is that adding a row never lowers it. For the prefix tree, the key fact is that the mismatches of a prefix are kept by each of its extensions, so the smallest mismatch count for a sequence can only grow. The full proof is in proofs/correctness.md.

Proof: Both branch and bound searches return an optimumfull

Let s1,…,sns_1, \ldots, s_n be sequences, each with W≥1W \ge 1 windows of length LL. For a tuple of starts p=(p1,…,pi)p = (p_1, \ldots, p_i) of the first ii sequences, let cjp(a)c^{p}_j(a) be the number of the ii windows with letter aa in column jj, and let S(p)=∑j=1L(i−max⁡acjp(a))S(p) = \sum_{j=1}^{L} (i - \max_a c^{p}_j(a)), the partial score. For i=ni = n this is the motif score. For a string uu of length k≤Lk \le L, let B(u)=∑imin⁡1≤q≤WdH(u,si[q..q+k−1])B(u) = \sum_i \min_{1 \le q \le W} d_H(u, s_i[q .. q + k - 1]). For k=Lk = L this is the total distance D(u)D(u).

Lemma 1 (the partial score never drops). If p′p' extends pp by one start, then S(p′)≥S(p)S(p') \ge S(p).

Proof. Let pp fix ii rows. The new row adds one letter to each column, so for each jj the number of rows grows by 1 and max⁡acj(a)\max_a c_j(a) grows by 0 or 1. So each term i−max⁡acj(a)i - \max_a c_j(a) grows by 1 or stays. □\square

By induction, S(p)≤S(r)S(p) \le S(r) for every complete tuple rr that extends pp.

Lemma 2 (the prefix bound never drops). If u′u' is uu followed by one letter, then B(u′)≥B(u)B(u') \ge B(u). So B(u)≤D(v)B(u) \le D(v) for every string vv of length LL with prefix uu.

Proof. For each ii and qq, dH(u′,si[q..q+k])=dH(u,si[q..q+k−1])+[uk+1′≠si[q+k]]≥dH(u,si[q..q+k−1])d_H(u', s_i[q .. q + k]) = d_H(u, s_i[q .. q + k - 1]) + [u'_{k+1} \ne s_i[q + k]] \ge d_H(u, s_i[q .. q + k - 1]). A minimum over qq of larger terms is at least as large, and the sum over ii keeps the order. Apply this L−kL - k times. □\square

Lemma 3 (the table). When EXTEND(u,k)(u, k) starts, m[i][q]=dH(u,si[q..q+k−1])m[i][q] = d_H(u, s_i[q .. q + k - 1]) for all ii and qq. So line L17 computes B(u)B(u).

Proof. By induction on the calls. At the first call, uu is empty and line L14 sets every entry to 0, which is the distance of two empty strings. Suppose the claim holds when EXTEND(u,k)(u, k) starts. Before the call EXTEND(ua,k+1)(ua, k + 1), line L21 adds 1 to m[i][q]m[i][q] exactly when si[q+k]≠as_i[q + k] \ne a, which is the mismatch in column k+1k + 1 (with 1-based columns of the window), so the claim holds for uaua. That call and its own calls end with the table as it was at their start, by induction on the depth of the recursion, and line L23 then removes what line L21 added. So the table is again the table of uu when the next letter is tried. □\square

The counts cc of the position search satisfy the same kind of invariant: when SEARCH(i)(i) starts, cc holds the letters of the windows of p1,…,pi−1p_1, \ldots, p_{i-1}. Line L10 adds the window of pip_i and line L12 removes it. So line L11 computes S(p1,…,pi)S(p_1, \ldots, p_i) and line L6 computes the score of the complete tuple.

Lemma 4 (no better leaf is cut). Let bb be the value of bestbest at some moment, and let a subtree be cut at that moment. Then no leaf of the subtree has a score below bb.

Proof. In the position search, the cut is the failed test of line L11, so S(p1,…,pi)≥bS(p_1, \ldots, p_i) \ge b, and by Lemma 1 every complete tuple below has a score at least bb. In the prefix search, the cut is line L18, so B(u)≥bB(u) \ge b, and by Lemma 2 every string below has D≥bD \ge b. □\square

Theorem. BB-MOTIF returns a tuple of starts with the smallest motif score, and BB-MEDIAN returns a string with the smallest total distance DD. In each case the result is the first optimum in the order of the tree.

Proof. We give the proof for BB-MEDIAN; the proof for BB-MOTIF is the same with Lemma 1 in place of Lemma 2 and line L7 in place of line L19.

The value of bestbest only decreases, and when it changes at line L19 it becomes D(u)D(u) of a leaf uu by Lemma 3, with bestv=ubestv = u. The first leaf of the tree, AA...A, is reached: on its path every bound is at most nL<nL+1nL < nL + 1, the start value. So at the end best=D(bestv)best = D(bestv) for some string bestvbestv.

Let D∗D^* be the smallest total distance and v∗v^* the first string in tree order with D(v∗)=D∗D(v^*) = D^*. Suppose v∗v^* is not reached as a leaf with B=D∗B = D^* and the test of line L18 passed. Then some node on its path, a prefix uu, was cut at line L18 with B(u)≥bestB(u) \ge best at that moment, or v∗v^* was cut at line L18 itself. At that moment bestbest is the distance of a leaf before v∗v^* in tree order, which is larger than D∗D^* by the choice of v∗v^*. So B(u)≤D(v∗)=D∗<bestB(u) \le D(v^*) = D^* < best by Lemma 2, and the cut could not happen. So v∗v^* is reached, its bound D∗D^* is below bestbest, and line L19 sets best=D∗best = D^* and bestv=v∗bestv = v^*.

After that, best=D∗best = D^*, and no later leaf can pass line L18, since its bound is its distance, at least D∗D^*. So the result is v∗v^* with distance D∗D^*. □\square

Corollary (the equivalence check). The score returned by BB-MOTIF equals the distance returned by BB-MEDIAN, by the equivalence theorem of the median string problem. The tests check this on random inputs, and check both results against brute force over all tuples of starts and all 4L4^L strings.

Complexity

  • Prefix tree, worst case. The tree has ∑k=0L4k<434L\sum_{k=0}^{L} 4^k < \frac{4}{3} 4^L nodes. Lines L17, L21 and L23 take O(nW)O(nW) time per node, so the time is O(4LnW)O(4^L n W). This is the cost of the plain enumeration on the tree; without the tree, each of the 4L4^L strings would cost O(nWL)O(nWL).
  • Position tree, worst case. The tree has O(Wn)O(W^n) nodes, and lines L10 to L12 take O(L)O(L) time per child. So the time is O(LWn)O(L W^n).
  • Best case. If the first leaf has score 0, every later bound is at least 0 and the search cuts every node after the first path. The prefix tree then visits O(L)O(L) nodes and takes O(LnW)O(L n W) time; the position tree tests O(nW)O(nW) children at O(L)O(L) time each.
  • Space. The table mm takes nWnW words, the counts take 4L4L words, and the recursion depth is LL or nn. So the extra space is O(nW+L)O(nW + L), and O(nW)O(nW) more for the windows of the position search.
  • In practice. The number of nodes depends on the data and on how soon a good leaf is found. The measured counts above are examples, not bounds. A good first best score, for example from a greedy motif search, makes the cuts start earlier.

Properties

  • Exact. Both searches return an optimum of the total Hamming distance score for every input.
  • Deterministic. The tree order is fixed (windows from left to right, letters in the order A, C, G, T) and the test is strict, so the result is the first optimum in that order.
  • The same optimum. By the equivalence theorem, the score of BB-MOTIF equals the distance of BB-MEDIAN, and the consensus of the returned sites is a median string. On the example, the sites TTC, ATC, TTC, GTC and TTC have the consensus TTC, a median string that BB-MEDIAN does not return because CAA comes first.
  • Only for the Hamming score. The bounds use the fact that each mismatch stays. They do not hold for an information content score, where a new row can raise or lower the score of a column.

Variants and improvements

  • A better start. Set bestbest in line L1 or L13 to the score of a heuristic solution plus one, so that the cuts work from the first node.
  • The maximization form. Jones and Pevzner maximize nL−Score(p)nL - \mathrm{Score}(p) and bound a node by the value of the rows placed so far plus LL for each row not yet placed. This is the same cut as the partial score above, written for the other form of the score.
  • Best first. A best-first branch and bound expands the open node with the smallest bound. It visits fewer nodes, but it needs memory for the open nodes.
  • The (L,d)(L, d) version. For the planted motif problem, cut a prefix when some sequence has no window within dd mismatches of it: min⁡qm[i][q]>d\min_q m[i][q] > d for some ii. This lists all (L,d)(L, d) motifs.
  • Both strands. Add the windows of the reverse complement of each sequence to the table mm.

When to use it

Use the prefix tree search when the worst case of 4LnW4^L n W cell updates is affordable and the exact optimum of the Hamming score is wanted. For L=8L = 8 and 20 sequences of 600 letters this is 65,536×20×593≈7.8×10865{,}536 \times 20 \times 593 \approx 7.8 \times 10^8 updates, which is practical; each extra letter multiplies it by 4. It is a good reference for the heuristic methods on small data. Do not use the position tree for more than a few short sequences, since WnW^n grows with each sequence. For long motifs, use Gibbs sampling, MEME or PROJECTION; for an information content score, use those or the greedy search.

Pitfalls

  • Cut with a strict test. Line L18 must cut when the bound equals the best. A cut only when the bound is strictly larger is still correct, but it visits every tied subtree and can lose most of the gain.
  • Undo exactly. Line L23 must remove exactly what line L21 added, letter by letter. A copy of the whole table at each node is also correct, but it costs O(nW)O(nW) memory per level.
  • Window range. The starts run from 1 to W=G−L+1W = G - L + 1, not to GG; a window that runs past the end of a sequence gives wrong counts.
  • Ties. The motif finding problem often has many optimal answers. A test that compares the output with one fixed answer can fail for a correct search with another tree order.

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.

bioseq.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Shared helper of the biology pages of https://algorithm.tamnd.com/. The authors are listed in prov/.
"""Small DNA utilities shared by the biology pages.

Conventions:
- DNA is a str over "ACGT", written 5' to 3'. Positions are 0-based.
- Random draws use a random.Random object that the caller passes in, and the
  order of the draws is fixed and written in each docstring, so that a seed
  gives the same output on every run.
- Alignment scores are added: pass match as a positive number and mismatch and
  gap as negative numbers. A CIGAR string uses M (a column with a base of both
  strings, equal or not), I (a base of a, the query, against a gap) and D (a
  base of b, the reference, against a gap).

This module holds no algorithm of a page: no ORF finder, no motif finder and
no caller. The functions are building blocks for the page code and its tests.
"""

from __future__ import annotations

import math
import random
from collections import namedtuple
from typing import Dict, List, Sequence, Tuple, Union

DNA = "ACGT"

_COMPLEMENT = {"A": "T", "C": "G", "G": "C", "T": "A", "N": "N",
               "a": "t", "c": "g", "g": "c", "t": "a", "n": "n"}


def revcomp(seq: str) -> str:
    """The reverse complement of seq. N maps to N; other letters raise KeyError."""
    return "".join(_COMPLEMENT[c] for c in reversed(seq))


# NCBI genetic code table 1 (the standard code), in the TCAG order of the NCBI
# listing: the first base changes slowest and the third base fastest.
_AAS = "FFLLSSSSYY**CC*WLLLLPPPPHHQQRRRRIIIMTTTTNNKKSSRRVVVVAAAADDEEGGGG"
_ORDER = "TCAG"
CODON_TABLE: Dict[str, str] = {
    a + b + c: _AAS[16 * i + 4 * j + k]
    for i, a in enumerate(_ORDER)
    for j, b in enumerate(_ORDER)
    for k, c in enumerate(_ORDER)
}
STOPS = frozenset(c for c, aa in CODON_TABLE.items() if aa == "*")


def translate(seq: str, frame: int = 0) -> str:
    """Translate seq[frame:] codon by codon with CODON_TABLE.

    frame is 0, 1 or 2. A stop codon gives "*", a codon with a letter other than
    A, C, G or T gives "X", and a last part shorter than three bases is dropped.
    The function does not look for start or stop codons.
    """
    if frame not in (0, 1, 2):
        raise ValueError("frame must be 0, 1 or 2")
    s = seq.upper()
    out = []
    for i in range(frame, len(s) - 2, 3):
        out.append(CODON_TABLE.get(s[i:i + 3], "X"))
    return "".join(out)


def random_dna(rng: random.Random, n: int, gc: float = 0.5) -> str:
    """n random bases, independent, with P(G) = P(C) = gc/2 and P(A) = P(T) = (1 - gc)/2.

    Draw order: one rng.random() per base, from left to right.
    """
    if not 0.0 <= gc <= 1.0:
        raise ValueError("gc must be in [0, 1]")
    half_gc, cut = gc / 2.0, gc + (1.0 - gc) / 2.0
    out = []
    for _ in range(n):
        u = rng.random()
        if u < half_gc:
            out.append("C")
        elif u < gc:
            out.append("G")
        elif u < cut:
            out.append("A")
        else:
            out.append("T")
    return "".join(out)


def _other_base(rng: random.Random, base: str) -> str:
    """A base other than base, uniform among the other three (one rng.choice)."""
    return rng.choice([b for b in DNA if b != base])


def mutate(rng: random.Random, seq: str, rate: float) -> str:
    """Substitute each base with probability rate, uniformly by one of the other three.

    Draw order: for each position from left to right, one rng.random(); if it is
    below rate, one rng.choice for the new base. Letters other than A, C, G and T
    are kept and use no draw. No insertions or deletions.
    """
    out = []
    for c in seq:
        if c in DNA and rng.random() < rate:
            out.append(_other_base(rng, c))
        else:
            out.append(c)
    return "".join(out)


SimRead = namedtuple("SimRead", ["read", "pos", "strand", "true_seq"])


def simulate_reads(rng: random.Random, genome: str, n: int, length: int,
                   error_rate: float) -> List[SimRead]:
    """n single-end reads of the given length from both strands of genome.

    Each item is SimRead(read, pos, strand, true_seq): pos is the 0-based start
    of the read on the forward strand of genome, strand is "+" or "-", true_seq
    is the error-free read (genome[pos:pos + length], or its reverse complement
    for "-"), and read is true_seq with substitution errors at rate error_rate.

    Draw order for each read: rng.randrange(len(genome) - length + 1) for pos,
    then rng.random() < 0.5 for the "+" strand, then the draws of mutate on
    true_seq.
    """
    if length > len(genome) or length <= 0:
        raise ValueError("need 0 < length <= len(genome)")
    reads = []
    for _ in range(n):
        pos = rng.randrange(len(genome) - length + 1)
        strand = "+" if rng.random() < 0.5 else "-"
        frag = genome[pos:pos + length]
        true_seq = frag if strand == "+" else revcomp(frag)
        reads.append(SimRead(mutate(rng, true_seq, error_rate), pos, strand, true_seq))
    return reads


def phred_to_prob(q: float) -> float:
    """Error probability of the Phred score q: p = 10^(-q/10)."""
    return 10.0 ** (-q / 10.0)


def prob_to_phred(p: float) -> float:
    """Phred score of the error probability p in (0, 1]: Q = -10 log10(p)."""
    if not 0.0 < p <= 1.0:
        raise ValueError("p must be in (0, 1]")
    return -10.0 * math.log10(p)


def hamming(a: Sequence, b: Sequence) -> int:
    """The number of positions where a and b differ; they must have the same length."""
    if len(a) != len(b):
        raise ValueError("hamming needs sequences of equal length")
    return sum(1 for x, y in zip(a, b) if x != y)


def kmers(seq: str, k: int) -> List[str]:
    """All len(seq) - k + 1 substrings of length k, from left to right (with repeats)."""
    if k <= 0:
        raise ValueError("k must be positive")
    return [seq[i:i + k] for i in range(len(seq) - k + 1)]


def gc_content(seq: str) -> float:
    """The fraction of G and C letters in seq (upper or lower case); 0.0 for an empty seq."""
    if not seq:
        return 0.0
    s = seq.upper()
    return (s.count("G") + s.count("C")) / len(s)


Number = Union[int, float]


def _cigar(ops: List[str]) -> str:
    """Run-length code a list of single-letter operations, for example MMMID to 3M1I1D."""
    out = []
    i = 0
    while i < len(ops):
        j = i
        while j < len(ops) and ops[j] == ops[i]:
            j += 1
        out.append(f"{j - i}{ops[i]}")
        i = j
    return "".join(out)


def _fill(a: str, b: str, match: Number, mismatch: Number, gap: Number, free_b_ends: bool):
    """The dynamic programming table of a linear gap alignment of a and b."""
    n, m = len(a), len(b)
    S = [[0] * (m + 1) for _ in range(n + 1)]
    for i in range(1, n + 1):
        S[i][0] = i * gap
    for j in range(1, m + 1):
        S[0][j] = 0 if free_b_ends else j * gap
    for i in range(1, n + 1):
        ai = a[i - 1]
        row, up = S[i], S[i - 1]
        for j in range(1, m + 1):
            diag = up[j - 1] + (match if ai == b[j - 1] else mismatch)
            row[j] = max(diag, up[j] + gap, row[j - 1] + gap)
    return S


def _trace(S, a: str, b: str, i: int, j: int, match: Number, mismatch: Number,
           gap: Number, free_b_ends: bool) -> Tuple[List[str], int]:
    """Trace back from cell (i, j); prefer M, then I, then D. Returns the ops and the start in b."""
    ops: List[str] = []
    while i > 0 or (j > 0 and not free_b_ends):
        if i > 0 and j > 0 and S[i][j] == S[i - 1][j - 1] + (match if a[i - 1] == b[j - 1] else mismatch):
            ops.append("M")
            i, j = i - 1, j - 1
        elif i > 0 and S[i][j] == S[i - 1][j] + gap:
            ops.append("I")
            i -= 1
        else:
            ops.append("D")
            j -= 1
    ops.reverse()
    return ops, j


def global_align(a: str, b: str, match: Number = 1, mismatch: Number = -1,
                 gap: Number = -1) -> Tuple[Number, str]:
    """Needleman-Wunsch alignment of all of a with all of b, with linear gaps.

    Returns (score, cigar). The cigar uses M, I (a base of a only) and D (a base of
    b only); an empty alignment gives "".
    """
    S = _fill(a, b, match, mismatch, gap, False)
    ops, _ = _trace(S, a, b, len(a), len(b), match, mismatch, gap, False)
    return S[len(a)][len(b)], _cigar(ops)


def semiglobal_align(a: str, b: str, match: Number = 1, mismatch: Number = -1,
                     gap: Number = -1, with_start: bool = False):
    """Align all of a (the query) to a substring of b (the reference), with linear gaps.

    Bases of b before and after the aligned part cost nothing and are not in the
    cigar, as in SAM. Returns (score, cigar), or (score, cigar, start) with
    with_start=True, where start is the 0-based position in b of the first
    reference base of the alignment. Among best end columns the leftmost wins.
    """
    S = _fill(a, b, match, mismatch, gap, True)
    n = len(a)
    best_j = max(range(len(b) + 1), key=lambda j: (S[n][j], -j))
    ops, start = _trace(S, a, b, n, best_j, match, mismatch, gap, True)
    if with_start:
        return S[n][best_j], _cigar(ops), start
    return S[n][best_j], _cigar(ops)
branch_and_bound_motif_search.py 146 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/branch-and-bound-motif-search/. The authors are listed in prov/6XQ8GR.jsonl.
"""Exact motif search by branch and bound, on the tree of start positions and
on the tree of string prefixes (the median string search).

Positions are 0-based in this code; the page numbers them from 1.
"""

from typing import List, NamedTuple, Optional, Sequence, Tuple

from bioseq import DNA, hamming, kmers

_INDEX = {a: k for k, a in enumerate(DNA)}


class MotifResult(NamedTuple):
    """An optimal choice of sites: the 0-based starts, the motif score and the tree nodes visited."""

    starts: Tuple[int, ...]
    score: int
    nodes: int


class MedianResult(NamedTuple):
    """A median string, its total distance and the tree nodes visited."""

    pattern: str
    distance: int
    nodes: int


def _check(seqs: Sequence[str], L: int) -> None:
    if L <= 0:
        raise ValueError("L must be positive")
    if not seqs:
        raise ValueError("need at least one sequence")
    for s in seqs:
        if len(s) < L:
            raise ValueError("every sequence must have length at least L")
        if set(s) - set(DNA):
            raise ValueError("sequences must be over ACGT")


def motif_score(windows: Sequence[str]) -> int:
    """The number of letters that differ from the consensus: sum over columns of n - max count."""
    n = len(windows)
    return sum(n - max(col.count(a) for a in DNA) for col in zip(*windows))


def consensus(windows: Sequence[str]) -> str:
    """A consensus string; among letters with the same count, the first in ACGT order wins."""
    return "".join(max(DNA, key=lambda a: (col.count(a), -_INDEX[a])) for col in zip(*windows))


def total_distance(pattern: str, seqs: Sequence[str]) -> int:
    """D(v): the sum over the sequences of the Hamming distance from v to its closest window."""
    L = len(pattern)
    return sum(min(hamming(pattern, w) for w in kmers(s, L)) for s in seqs)


def bb_motif_search(seqs: Sequence[str], L: int) -> MotifResult:
    """Branch and bound over the tree of start positions.

    A node of depth i fixes the windows of the first i sequences. Its partial
    score, the motif score of those i rows, never drops when rows are added,
    so a node whose partial score is not below the best complete score is cut.
    Returns the lexicographically first optimal tuple of starts.
    Cost: O(L W^n) time in the worst case, W = G - L + 1, and O(n + L) space.
    """
    _check(seqs, L)
    n = len(seqs)
    wins = [kmers(s, L) for s in seqs]
    starts = [0] * n
    best = n * L + 1  # @line L1
    best_starts: Optional[Tuple[int, ...]] = None
    counts = [[0] * 4 for _ in range(L)]  # @line L2
    nodes = 0

    def partial(rows: int) -> int:
        return sum(rows - max(c) for c in counts)

    def search(i: int) -> None:
        # i rows are placed; the pseudocode calls this SEARCH(i + 1).
        nonlocal best, best_starts, nodes
        nodes += 1
        if i == n:  # @line L5
            sc = partial(n)  # @line L6
            if sc < best:  # @line L7
                best, best_starts = sc, tuple(starts)
            return  # @line L8
        for q, w in enumerate(wins[i]):  # @line L9
            starts[i] = q  # @line L10
            for j, a in enumerate(w):
                counts[j][_INDEX[a]] += 1
            if partial(i + 1) < best:  # @line L11
                search(i + 1)
            for j, a in enumerate(w):  # @line L12
                counts[j][_INDEX[a]] -= 1

    search(0)  # @line L3
    assert best_starts is not None
    return MotifResult(best_starts, best, nodes)  # @line L4


def bb_median_string(seqs: Sequence[str], L: int) -> MedianResult:
    """Branch and bound over the tree of prefixes of the candidate string.

    For a prefix u of length k, m[i][q] is the Hamming distance from u to the
    first k letters of window q of sequence i. The sum over i of the smallest
    m[i][q] is a lower bound on D(v) for every extension v of u, and equals D(u)
    at a leaf. Returns the lexicographically first median string (ACGT order).
    Cost: O(4^L n W) time in the worst case and O(n W + L) space.
    """
    _check(seqs, L)
    n = len(seqs)
    best = n * L + 1  # @line L13
    best_pattern: Optional[str] = None
    m: List[List[int]] = [[0] * (len(s) - L + 1) for s in seqs]  # @line L14
    prefix: List[str] = []
    nodes = 0

    def extend(k: int) -> None:
        nonlocal best, best_pattern, nodes
        nodes += 1
        bound = sum(min(row) for row in m)  # @line L17
        if bound >= best:  # @line L18
            return
        if k == L:  # @line L19
            best, best_pattern = bound, "".join(prefix)
            return
        for a in DNA:  # @line L20
            for s, row in zip(seqs, m):  # @line L21
                for q in range(len(row)):
                    if s[q + k] != a:
                        row[q] += 1
            prefix.append(a)
            extend(k + 1)  # @line L22
            prefix.pop()
            for s, row in zip(seqs, m):  # @line L23
                for q in range(len(row)):
                    if s[q + k] != a:
                        row[q] -= 1

    extend(0)  # @line L15
    assert best_pattern is not None
    return MedianResult(best_pattern, best, nodes)  # @line L16
test_branch_and_bound_motif_search.py 126 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/branch-and-bound-motif-search/. The authors are listed in prov/6XQ8GR.jsonl.

import itertools
import random

import pytest

from bioseq import DNA, random_dna
from branch_and_bound_motif_search import (
    bb_median_string,
    bb_motif_search,
    consensus,
    motif_score,
    total_distance,
)

# Sample data of Rosalind problem BA2D (k = 3, t = 5).
SAMPLE = ["GGCGTTCAGGCA", "AAGAATCAGTCA", "CAAGGAGTTCGC", "CACGTCAATCAC", "CAATAATATTCG"]


def windows(seqs, starts, L):
    return [s[q:q + L] for s, q in zip(seqs, starts)]


def brute_sites(seqs, L):
    """The lexicographically first tuple of starts with the smallest motif score."""
    ranges = [range(len(s) - L + 1) for s in seqs]
    return min(itertools.product(*ranges), key=lambda p: (motif_score(windows(seqs, p, L)), p))


def brute_median(seqs, L):
    """The first string in ACGT order with the smallest total distance."""
    pats = ("".join(t) for t in itertools.product(DNA, repeat=L))
    return min(pats, key=lambda v: (total_distance(v, seqs), [DNA.index(c) for c in v]))


def plant(rng, n, G, L, d):
    """Plant a random motif with exactly d changes in each of n random sequences.

    Draw order: random_dna for the motif; then for each sequence random_dna(G),
    rng.randrange(G - L + 1) for the start, rng.sample(range(L), d) for the
    changed positions, and one rng.choice per changed position.
    """
    motif = random_dna(rng, L)
    seqs, starts = [], []
    for _ in range(n):
        bg = random_dna(rng, G)
        q = rng.randrange(G - L + 1)
        inst = list(motif)
        for j in rng.sample(range(L), d):
            inst[j] = rng.choice([b for b in DNA if b != inst[j]])
        seqs.append(bg[:q] + "".join(inst) + bg[q + L:])
        starts.append(q)
    return motif, seqs, starts


def test_sample_sites():
    r = bb_motif_search(SAMPLE, 3)
    assert r.score == 2
    assert r.starts == (4, 4, 7, 3, 8)
    assert windows(SAMPLE, r.starts, 3) == ["TTC", "ATC", "TTC", "GTC", "TTC"]
    assert r.starts == brute_sites(SAMPLE, 3)
    assert r.nodes == 166


def test_sample_median():
    r = bb_median_string(SAMPLE, 3)
    assert r == ("CAA", 2, 45)
    assert brute_median(SAMPLE, 3) == "CAA"
    assert sorted(v for v in ("".join(t) for t in itertools.product(DNA, repeat=3))
                  if total_distance(v, SAMPLE) == 2) == ["CAA", "TCA", "TTC"]


def test_against_brute_force_random():
    rng = random.Random(2024)
    for _ in range(25):
        n = rng.randint(2, 4)
        L = rng.randint(2, 4)
        seqs = [random_dna(rng, rng.randint(L, 7)) for _ in range(n)]
        sites = bb_motif_search(seqs, L)
        med = bb_median_string(seqs, L)
        p = brute_sites(seqs, L)
        assert sites.starts == p
        assert sites.score == motif_score(windows(seqs, p, L))
        assert med.pattern == brute_median(seqs, L)
        assert med.distance == total_distance(med.pattern, seqs)
        # The equivalence: the smallest motif score equals the smallest total distance.
        assert sites.score == med.distance


def test_consensus_of_optimal_sites_is_a_median():
    rng = random.Random(7)
    for _ in range(15):
        seqs = [random_dna(rng, 8) for _ in range(3)]
        r = bb_motif_search(seqs, 3)
        v = consensus(windows(seqs, r.starts, 3))
        assert total_distance(v, seqs) == r.score


def test_pruning_on_planted_motif():
    rng = random.Random(11)
    motif, seqs, _ = plant(rng, 6, 40, 7, 1)
    r = bb_median_string(seqs, 7)
    full = sum(4 ** k for k in range(8))
    assert r.distance <= total_distance(motif, seqs) <= 6
    assert r.nodes < full // 10


def test_position_tree_prunes():
    rng = random.Random(3)
    _, seqs, _ = plant(rng, 4, 12, 4, 0)
    r = bb_motif_search(seqs, 4)
    assert r.score == 0
    assert r.nodes < sum(9 ** k for k in range(5))


def test_errors():
    with pytest.raises(ValueError):
        bb_motif_search(["ACG"], 4)
    with pytest.raises(ValueError):
        bb_median_string([], 2)
    with pytest.raises(ValueError):
        bb_median_string(["ACGN"], 2)
    with pytest.raises(ValueError):
        bb_motif_search(["ACGT"], 0)

History

Branch and bound was introduced for integer programming by Land and Doig in 1960, and it became a standard tool for exact search. In the motif setting, Jones and Pevzner (2004) presented the motif finding problem and the median string problem in Chapter 4 of their textbook, showed that the two have the same optimum under the total Hamming distance, and used them as the main example of branch and bound in bioinformatics: first on the tree of start positions, then on the much smaller tree of candidate strings. Compeau and Pevzner (2015) teach the median string search by plain enumeration of all kk-mers.

References

  1. Neil C. Jones and Pavel A. Pevzner, An Introduction to Bioinformatics Algorithms, MIT Press, 2004, Chapter 4, Sections 4.7 (search trees), 4.8 (finding motifs, the branch and bound search on start positions) and 4.9 (finding a median string, the branch and bound search on prefixes)
  2. Phillip Compeau and Pavel Pevzner, Bioinformatics Algorithms, An Active Learning Approach, Volume I, 2nd edition, Active Learning Publishers, 2015, Chapter 2, Section 2.4, the median string search by enumeration of all k-mers

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.best
  • a full proof of time.position_tree_worst
  • 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
  • at least three sources
  • a scene preset for the example