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.
- Solves
- Motif finding
- 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
- Model
- Word RAM
- Properties
- deterministicexactofflinerecursive
- Evidence
- Proof sketchCode in 1 languages
- 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 leaves, and the tree of prefixes of the candidate median string, with 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 , each of length , and a motif length . Each sequence has windows. Positions are 1-based on this page and 0-based in the code.
Output, position tree. Starts that minimize , where counts the letter in column of the chosen windows.
Output, prefix tree. A string of length that minimizes .
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 fixes the starts of the first sequences. Its partial score is the motif score of those rows, . Adding a row raises by one and each 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 is a prefix of length . For each sequence and window , let , the mismatches of with the first letters of the window. The mismatches of a prefix stay when the string grows, so is a lower bound on for every extension of , and it equals at a leaf.
BB-MOTIF(s[1 .. n], L)- 1
best ← nL + 1, bestp ← none - 2
c_j(a) ← 0 for every column j and letter a - 3
SEARCH(1) - 4
return bestp, best SEARCH(i)- 5
if i > n then - 6
sc ← Σ_j (n - max_a c_j(a)) - 7
if sc < best then best ← sc, bestp ← (p_1, ..., p_n) - 8
return - 9
for q ← 1 to W do - 10
p_i ← q, add the letters of s_i[q .. q + L - 1] to the counts c - 11
if Σ_j (i - max_a c_j(a)) < best then SEARCH(i + 1) - 12
remove the letters of s_i[q .. q + L - 1] from the counts c BB-MEDIAN(s[1 .. n], L)- 13
best ← nL + 1, bestv ← none - 14
m[i][q] ← 0 for every sequence i and window q - 15
EXTEND(empty string, 0) - 16
return bestv, best EXTEND(u, k)- 17
bound ← Σ_i min_q m[i][q] - 18
if bound ≥ best then return - 19
if k = L then best ← bound, bestv ← u, return - 20
for a in A, C, G, T do - 21
for every i and q: if s_i[q + k] ≠ a then m[i][q] ← m[i][q] + 1 - 22
EXTEND(ua, k + 1) - 23
for 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 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 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 of each window to the counts when the prefix gets the letter , 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 , so . The prefix tree has nodes. BB-MEDIAN visits 45 of them, in this order of events:
| prefix | 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 . TCA and TTC are also median strings, but the strict test keeps the first one. The position tree on the same input has 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 . 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 be sequences, each with windows of length . For a tuple of starts of the first sequences, let be the number of the windows with letter in column , and let , the partial score. For this is the motif score. For a string of length , let . For this is the total distance .
Lemma 1 (the partial score never drops). If extends by one start, then .
Proof. Let fix rows. The new row adds one letter to each column, so for each the number of rows grows by 1 and grows by 0 or 1. So each term grows by 1 or stays.
By induction, for every complete tuple that extends .
Lemma 2 (the prefix bound never drops). If is followed by one letter, then . So for every string of length with prefix .
Proof. For each and , . A minimum over of larger terms is at least as large, and the sum over keeps the order. Apply this times.
Lemma 3 (the table). When EXTEND starts, for all and . So line L17 computes .
Proof. By induction on the calls. At the first call, is empty and line L14 sets every entry to 0, which is the distance of two empty strings. Suppose the claim holds when EXTEND starts. Before the call EXTEND, line L21 adds 1 to exactly when , which is the mismatch in column (with 1-based columns of the window), so the claim holds for . 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 when the next letter is tried.
The counts of the position search satisfy the same kind of invariant: when SEARCH starts, holds the letters of the windows of . Line L10 adds the window of and line L12 removes it. So line L11 computes and line L6 computes the score of the complete tuple.
Lemma 4 (no better leaf is cut). Let be the value of at some moment, and let a subtree be cut at that moment. Then no leaf of the subtree has a score below .
Proof. In the position search, the cut is the failed test of line L11, so , and by Lemma 1 every complete tuple below has a score at least . In the prefix search, the cut is line L18, so , and by Lemma 2 every string below has .
Theorem. BB-MOTIF returns a tuple of starts with the smallest motif score, and BB-MEDIAN returns a string with the smallest total distance . 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 only decreases, and when it changes at line L19 it becomes of a leaf by Lemma 3, with . The first leaf of the tree, AA...A, is reached: on its path every bound is at most , the start value. So at the end for some string .
Let be the smallest total distance and the first string in tree order with . Suppose is not reached as a leaf with and the test of line L18 passed. Then some node on its path, a prefix , was cut at line L18 with at that moment, or was cut at line L18 itself. At that moment is the distance of a leaf before in tree order, which is larger than by the choice of . So by Lemma 2, and the cut could not happen. So is reached, its bound is below , and line L19 sets and .
After that, , and no later leaf can pass line L18, since its bound is its distance, at least . So the result is with distance .
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 strings.
Complexity
- Prefix tree, worst case. The tree has nodes. Lines L17, L21 and L23 take time per node, so the time is . This is the cost of the plain enumeration on the tree; without the tree, each of the strings would cost .
- Position tree, worst case. The tree has nodes, and lines L10 to L12 take time per child. So the time is .
- 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 nodes and takes time; the position tree tests children at time each.
- Space. The table takes words, the counts take words, and the recursion depth is or . So the extra space is , and 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 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 and bound a node by the value of the rows placed so far plus 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 version. For the planted motif problem, cut a prefix when some sequence has no window within mismatches of it: for some . This lists all motifs.
- Both strands. Add the windows of the reverse complement of each sequence to the table .
When to use it
Use the prefix tree search when the worst case of cell updates is affordable and the exact optimum of the Hamming score is wanted. For and 20 sequences of 600 letters this is 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 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 memory per level.
- Window range. The starts run from 1 to , not to ; 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.
# 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 -mers.
References
- 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)
- 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.
| 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 6XQ8GR Edit this page History Report an error Markdown