Algorithm Search⌘K

Algorithmintro

Randomized motif search

Also called random restart motif search.

Start from random l-mers, then repeat build a profile and pick the most probable l-mer in each sequence until the score stops improving.

Time
O(R L^2 n^2 W) worstO(n W L) per_step
Space
O(n L) extra
Where
G = the length of each sequence; L = the motif length; R = the number of restarts; W = the number of windows per sequence, G - L + 1; n = the number of sequences
Properties
randomizednot exactofflineiterative
Origin
Phillip Compeau, Pavel Pevzner, 2015

Randomized motif search is a local search for the motif finding problem. It picks one random window in each sequence, builds a profile of these windows, and replaces every window by the window of its sequence that is most probable under the profile. It repeats the profile step while the motif score drops, and it restarts from new random windows many times. Each restart ends in a local optimum after at most L(n−⌈n/4⌉)+1L(n - \lceil n/4 \rceil) + 1 steps; the restarts make it likely that one of them reaches a good motif.

In plain words

Pick one piece at random from each sequence. Most of the pieces are noise, but by chance a few may be copies of the hidden word. Count the letters in each column of the pieces, and use the counts to pick the best fitting piece of every sequence again. The copies that you picked by luck pull the counts toward the hidden word, so the new pieces fit it better. Repeat until the pieces stop getting better.

One try usually ends in a poor answer. So try again from new random pieces, a few hundred or a few thousand times, and keep the best answer of all tries.

The problem

Input. DNA sequences s1,…,sns_1, \ldots, s_n, each of length GG, a motif length LL, a number of restarts RR and a seed for the random number generator. 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. One window tit_i in each sequence, with a small motif score Score(t1,…,tn)=∑j(n−max⁡acj(a))\mathrm{Score}(t_1, \ldots, t_n) = \sum_j (n - \max_a c_j(a)), where cj(a)c_j(a) counts the letter aa in column jj of the windows. The result depends on the seed, and it need not be optimal.

The algorithm

The profile of windows t1,…,tnt_1, \ldots, t_n with pseudocount 1 is Pj(a)=(cj(a)+1)/(n+4)P_j(a) = (c_j(a) + 1)/(n + 4). All rows have the same sum, so the most probable window of a sequence is the window with the largest product of counts ∏j(cj(wj)+1)\prod_j (c_j(w_j) + 1), an exact integer.

  1. RANDOMIZED-MOTIF(s[1 .. n], L, R, rng)
  2. 1best ← none
  3. 2for r ← 1 to R do
  4. 3t_i ← s_i[q_i .. q_i + L - 1] with q_i uniform in 1 .. W, for i ← 1 to n
  5. 4sc ← Score(t_1, ..., t_n)
  6. 5loop
  7. 6P ← the profile of t_1, ..., t_n with pseudocount 1
  8. 7t'_i ← the first most probable window of s_i under P, for i ← 1 to n
  9. 8if Score(t') < sc then t ← t', sc ← Score(t')
  10. 9else exit the loop
  11. 10if best = none or sc < Score(best) then best ← t
  12. 11return best

Line L3 is the only random step. The code draws the starts with rng.randrange(W) once per sequence, in the order of the sequences, from random.Random(seed), so a seed fixes the whole run. Lines L5 to L9 are the deterministic local search: the profile picks new windows (line L7), and the search goes on only while the score drops strictly (line L8). Line L10 keeps the first restart with the smallest score.

Example

Take the five sequences of Rosalind problem BA2F, each 32 letters long, with L=8L = 8, so W=25W = 25:

CGCCCCTCTCGGGGGTGTTCAGTAAACGGCCA
GGGCGAGGTATGTGTAAGTGCCAAGGTGCCAG
TAGTACCGAGACCGAAAGAAGTATACAGGCGT
TAGATCAAGTTTCAGGTGCACGTCGGTGAACC
AATCCACCAGCTCCACGTGCAATGTTGGCCTA

With seed 0 and R=1000R = 1000, restart 316 draws the 1-based starts 6, 3, 22, 21 and 6:

step starts windows score
start 6, 3, 22, 21, 6 CTCTCGGG GCGAGGTA TATACAGG CGTCGGTG ACCAGCTC 19
1 7, 21, 22, 11, 12 TCTCGGGG CCAAGGTG TATACAGG TTCAGGTG TCCACGTG 12
2 7, 21, 24, 11, 12 TCTCGGGG CCAAGGTG TACAGGCG TTCAGGTG TCCACGTG 9
3 7, 21, 24, 11, 12 the same windows 9

The start has little agreement, but the profile of its five windows already moves four of them to their final places. Step 3 makes no change, so the restart stops with score 9. This is the sample answer of BA2F, and score 9 is the optimum of this input: the branch and bound median search finds the median string AAGTGCCA with total distance 9.

Most restarts end worse. Over the 1000 restarts of seed 0, the final scores range from 9 to 21, and only 2 restarts reach 9. The two runs reach different optimal choices: the second is AACGGCCA, AAGTGCCA, TAGTACCG, AAGTTTCA, ACGTGCAA. Line L10 keeps the first of them. Over 2000 more restarts with seed 1, 8 reach score 9, a measured rate of 0.4 percent per restart. At that rate, the chance that 1000 restarts reach the optimum at least once is 1−0.9961000≈0.981 - 0.996^{1000} \approx 0.98.

Measured success on planted motifs. The test generator plants a motif with exactly dd changes in each of 10 random sequences. A run counts as a success when the consensus of the output equals the planted motif. With 20 seeds (0 to 19):

GG (L,d)(L, d) R=10R = 10 R=100R = 100 R=1000R = 1000
100 (8, 1) 3 of 20 20 of 20 20 of 20
100 (10, 2) 2 of 20 8 of 20 16 of 20
200 (12, 3) 0 of 20 0 of 20 2 of 20

These are measurements on these seeds, not guarantees. The same inputs in the greedy search with pseudocount 1 give 19, 10 and 4 of 20.

Correctness

The claims are about what a run returns and how long it takes; the method is a heuristic and does not promise an optimum.

Theorem (valid output and local optimum). Each restart ends with one window from each sequence, and its score is at most the score of its random start. When it stops, one more profile step from its windows does not lower the score.

Proof. Line L3 picks windows. Line L7 picks a window of each sis_i, and line L8 accepts the new windows only when the score drops, so the score never rises. The loop exits at line L9 exactly when the profile step does not lower the score. □\square

Theorem (step bound). A restart makes at most Score(start)+1≤L(n−⌈n/4⌉)+1\mathrm{Score}(\text{start}) + 1 \le L(n - \lceil n/4 \rceil) + 1 profile steps.

Proof. Each step but the last lowers the integer score by at least 1, and the score is at least 0, so there are at most Score(start)\mathrm{Score}(\text{start}) such steps. In each column the most common of the four letters occurs at least ⌈n/4⌉\lceil n/4 \rceil times, so the score of any choice is at most L(n−⌈n/4⌉)L(n - \lceil n/4 \rceil). □\square

Line L7 picks a most probable window because the rows of the profile have equal sums, so the order of the probabilities is the order of the integer products. The tests check the step bound and the local optimum on 60 random inputs, the draw order against a manual replay, and that the score is never below the brute-force optimum. The proof of the facts about the profile step is in proofs/correctness.md.

Proof: Each restart of randomized motif search ends in a local optimum within a bounded number of stepsfull

Let s1,…,sns_1, \ldots, s_n be DNA sequences with at least LL letters each. For windows t=(t1,…,tn)t = (t_1, \ldots, t_n) with tit_i a window of sis_i, let cj(a)c_j(a) be the number of windows with letter aa in column jj, and Score(t)=∑j=1L(n−max⁡acj(a))\mathrm{Score}(t) = \sum_{j=1}^{L} (n - \max_a c_j(a)). The profile with pseudocount 1 is Pj(a)=(cj(a)+1)/(n+4)P_j(a) = (c_j(a) + 1)/(n + 4).

Lemma 1 (line L7 picks a most probable window). For each ii, line L7 returns the first window ww of sis_i with the largest ∏jPj(wj)\prod_j P_j(w_j).

Proof. For every column, ∑a(cj(a)+1)=n+4\sum_a (c_j(a) + 1) = n + 4, so ∏jPj(wj)=∏j(cj(wj)+1)/(n+4)L\prod_j P_j(w_j) = \prod_j (c_j(w_j) + 1)/(n + 4)^L. The denominator is the same positive number for all windows, so the order of the probabilities is the order of the integer products. The code computes these products exactly, starts from the value −1-1 and keeps a window only when its product is strictly larger, so it returns the first window with the largest product. □\square

Lemma 2 (the score bound). For every choice of windows, Score(t)≤L(n−⌈n/4⌉)\mathrm{Score}(t) \le L(n - \lceil n/4 \rceil).

Proof. In column jj the four counts sum to nn, so the largest is at least n/4n/4, and since it is an integer, at least ⌈n/4⌉\lceil n/4 \rceil. Each column term is at most n−⌈n/4⌉n - \lceil n/4 \rceil, and there are LL columns. □\square

Theorem. Let a restart start from windows t(0)t^{(0)}. Then:

  1. Every tuple it holds has one window from each sequence, and the scores of the tuples it holds strictly decrease.
  2. It makes at most Score(t(0))+1≤L(n−⌈n/4⌉)+1\mathrm{Score}(t^{(0)}) + 1 \le L(n - \lceil n/4 \rceil) + 1 profile steps, so it stops.
  3. When it stops with windows tt, the windows t′t' that the profile of tt picks by Lemma 1 have Score(t′)≥Score(t)\mathrm{Score}(t') \ge \mathrm{Score}(t).

Proof. (1) Line L3 picks a window of each sequence, and line L7 picks a window of each sequence. Line L8 replaces tt only by a tuple with a strictly smaller score.

(2) Number the profile steps 1,2,…1, 2, \ldots. Every step but the last is accepted at line L8 and lowers the integer score by at least 1. The score is at least 0, so at most Score(t(0))\mathrm{Score}(t^{(0)}) steps are accepted, and the next step is rejected and ends the loop. So there are at most Score(t(0))+1\mathrm{Score}(t^{(0)}) + 1 steps, and Lemma 2 gives the second bound.

(3) The loop ends only at line L9, which runs when the test of line L8 fails, that is, when Score(t′)≥Score(t)\mathrm{Score}(t') \ge \mathrm{Score}(t) for the windows t′t' that line L7 picked from the profile of the current tt. □\square

Corollary (the best restart). RANDOMIZED-MOTIF returns the tuple of the first restart with the smallest final score over the RR restarts. Line L10 replaces bestbest only by a strictly smaller score, as in the proof for the greedy search. The result is a valid choice of windows, and its score is at least the optimum of the motif finding problem.

Cost. A profile step builds the counts in O(nL)O(nL) time and scans nWnW windows at O(L)O(L) each, so it takes O(nWL)O(nWL) time. By the theorem, a restart makes O(nL)O(nL) steps, and RR restarts take O(RL2n2W)O(R L^2 n^2 W) time in the worst case. The extra space is the counts and the current windows, O(nL)O(nL).

The theorem does not say that a restart reaches an optimum, and it often does not: on the Rosalind sample BA2F, 2 of 1000 restarts with seed 0 reach the optimal score 9. The success rate over restarts is a measurement, given on the page.

Complexity

  • Time. A profile step builds the counts in O(nL)O(nL) time and scans the WW windows of each of the nn sequences at O(L)O(L) each, so it costs O(nWL)O(n W L). By the step bound, a restart makes O(nL)O(nL) steps, so the worst case is O(RL2n2W)O(R L^2 n^2 W). In practice a restart makes few steps: on the BA2F sample the mean is 2.2 steps and the most is 5.
  • Space. The counts take 4L4L integers and the windows nLnL letters, so O(nL)O(nL) besides the input.
  • Randomness. Each restart draws nn integers.

Properties

  • Randomized. The output depends on the seed. It is a Monte Carlo algorithm: it always stops in bounded time, but its answer may not be optimal.
  • Local search. Each restart is a hill climbing search that moves to the windows its own profile picks. It stops in the first local optimum.
  • Moves all windows at once. A step can change every window, which lets it jump far in one step, as the example shows. The Gibbs sampler changes one window per step instead.
  • Needs pseudocounts. Without them a letter that does not occur in a column gives probability 0 to many windows, and the search gets stuck.

Variants and improvements

  • The Gibbs sampler. Replace one window at a time, chosen by a random draw from the probabilities of the profile of the other windows, not by the largest one. Compeau and Pevzner present it next, and it is less likely to get stuck.
  • Hard EM. The profile step is the hard form of expectation maximization: line L7 is a hard E step that picks one site per sequence, and line L6 is the M step. MEME uses soft weights for all windows instead. The same pattern, with points and means, is the k-means algorithm.
  • A better start. Start from the output of the greedy search, or from windows near a candidate string.
  • More restarts in parallel. The restarts are independent, so they can run on many cores, each with its own seed.

When to use it

Use randomized motif search when the motif is strong enough that a few correct windows in a random start pull the profile toward it, and when you can afford hundreds or thousands of restarts. It is easy to write and to check, and it usually beats the greedy search, as the table shows. For subtle motifs, such as the planted (15, 4) motif, use PROJECTION or a Gibbs sampler with many iterations, or MEME.

Pitfalls

  • Too few restarts. Most restarts end in a poor local optimum; on BA2F only 0.4 percent reach the optimum. Measure the rate on your data and pick RR from it.
  • Stopping on a tie. The loop stops when the score does not drop strictly. Accepting equal scores can loop for ever between two choices with the same score.
  • Floating point products. The product of LL probabilities underflows for long motifs. Compare integer products of counts, or sums of logarithms with a fixed tie rule.
  • Reusing one seed. Restarts that share a seed repeat the same starts. Use one generator for all restarts, or a different seed for each.
  • A wrong motif length. A run with the wrong LL still returns windows with a low score, often a shifted or a partial copy of the true motif.

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)
randomized_motif_search.py 131 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/randomized-motif-search/. The authors are listed in prov/V85QPB.jsonl.
"""Randomized motif search (RandomizedMotifSearch of Compeau and Pevzner) with
random restarts and Laplace pseudocounts.

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

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

from bioseq import DNA, kmers

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


class RunResult(NamedTuple):
    """The windows, 0-based starts and score at the end of one run, and the
    number of profile steps the run made."""

    motifs: Tuple[str, ...]
    starts: Tuple[int, ...]
    score: int
    steps: int


class RandomizedResult(NamedTuple):
    """The best windows over all restarts, their starts and score, and the
    number of profile steps of each restart."""

    motifs: Tuple[str, ...]
    starts: Tuple[int, ...]
    score: int
    steps: Tuple[int, ...]


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 count_matrix(windows: Sequence[str], L: int, pseudo: int = 1) -> List[List[int]]:
    """counts[j][a] = the number of windows with letter a in column j, plus pseudo.

    The profile is counts[j][a] / (n + 4 pseudo); every row has the same sum.
    """
    counts = [[pseudo] * 4 for _ in range(L)]
    for w in windows:
        for j, a in enumerate(w):
            counts[j][_INDEX[a]] += 1
    return counts


def most_probable(seq: str, counts: List[List[int]]) -> int:
    """The 0-based start of the first window of seq with the largest product of counts.

    The rows of counts have equal sums, so this is the window with the largest
    profile probability. Integers keep the comparison exact.
    """
    L = len(counts)
    best_q, best_v = 0, -1
    for q, w in enumerate(kmers(seq, L)):
        v = 1
        for j, a in enumerate(w):
            v *= counts[j][_INDEX[a]]
        if v > best_v:
            best_q, best_v = q, v
    return best_q


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 or set(s) - set(DNA):
            raise ValueError("sequences must be over ACGT with length at least L")


def improve(seqs: Sequence[str], L: int, starts: Sequence[int], pseudo: int = 1) -> RunResult:
    """One run from the given starts: replace the windows by the most probable
    windows of their own profile while the score drops strictly.

    This is lines L4 to L9 of the page, without the random draw.
    """
    _check(seqs, L)
    if len(starts) != len(seqs) or any(not 0 <= q <= len(s) - L for s, q in zip(seqs, starts)):
        raise ValueError("one valid start per sequence is needed")
    cur = tuple(starts)
    motifs = tuple(s[q:q + L] for s, q in zip(seqs, cur))
    sc = motif_score(motifs)  # @line L4
    steps = 0
    while True:  # @line L5
        counts = count_matrix(motifs, L, pseudo)  # @line L6
        nxt = tuple(most_probable(s, counts) for s in seqs)  # @line L7
        steps += 1
        new_motifs = tuple(s[q:q + L] for s, q in zip(seqs, nxt))
        new_sc = motif_score(new_motifs)
        if new_sc < sc:  # @line L8
            cur, motifs, sc = nxt, new_motifs, new_sc
        else:
            break  # @line L9
    return RunResult(motifs, cur, sc, steps)


def randomized_motif_search(seqs: Sequence[str], L: int, restarts: int, seed: int = 0,
                            pseudo: int = 1) -> RandomizedResult:
    """Run improve from random starts `restarts` times and keep the best result.

    Draw order: random.Random(seed); for each restart, one rng.randrange(W_i)
    per sequence, in the order of the sequences. Among restarts with the same
    score the first one wins. Each restart makes at most
    L (n - ceil(n / 4)) + 1 profile steps, each of cost O(n W L).
    """
    _check(seqs, L)
    if restarts < 1:
        raise ValueError("restarts must be at least 1")
    if pseudo < 1:
        raise ValueError("pseudo must be at least 1")
    rng = random.Random(seed)
    best = None  # @line L1
    steps = []
    for _ in range(restarts):  # @line L2
        starts = [rng.randrange(len(s) - L + 1) for s in seqs]  # @line L3
        run = improve(seqs, L, starts, pseudo)
        steps.append(run.steps)
        if best is None or run.score < best.score:  # @line L10
            best = run
    return RandomizedResult(best.motifs, best.starts, best.score, tuple(steps))  # @line L11
test_randomized_motif_search.py 117 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/randomized-motif-search/. The authors are listed in prov/V85QPB.jsonl.

import itertools
import random

import pytest

from bioseq import DNA, random_dna
from randomized_motif_search import count_matrix, improve, most_probable, motif_score, randomized_motif_search

# Sample data of Rosalind problem BA2F (k = 8, t = 5).
SAMPLE = [
    "CGCCCCTCTCGGGGGTGTTCAGTAAACGGCCA",
    "GGGCGAGGTATGTGTAAGTGCCAAGGTGCCAG",
    "TAGTACCGAGACCGAAAGAAGTATACAGGCGT",
    "TAGATCAAGTTTCAGGTGCACGTCGGTGAACC",
    "AATCCACCAGCTCCACGTGCAATGTTGGCCTA",
]
SAMPLE_ANSWER = ("TCTCGGGG", "CCAAGGTG", "TACAGGCG", "TTCAGGTG", "TCCACGTG")


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), rng.sample(range(L), d) 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 consensus(windows):
    return "".join(max(DNA, key=lambda a: (col.count(a), -DNA.index(a))) for col in zip(*windows))


def brute_best_score(seqs, L):
    ranges = [range(len(s) - L + 1) for s in seqs]
    return min(motif_score([s[q:q + L] for s, q in zip(seqs, p)]) for p in itertools.product(*ranges))


def test_rosalind_ba2f_sample():
    # Score 9 is the optimum of this input (the branch and bound median search gives distance 9).
    r = randomized_motif_search(SAMPLE, 8, 1000, seed=0)
    assert r.motifs == SAMPLE_ANSWER
    assert r.score == motif_score(SAMPLE_ANSWER) == 9


def test_draw_order_and_best_of_runs():
    seqs = SAMPLE
    rng = random.Random(3)
    runs = []
    for _ in range(30):
        starts = [rng.randrange(len(s) - 8 + 1) for s in seqs]
        runs.append(improve(seqs, 8, starts))
    r = randomized_motif_search(seqs, 8, 30, seed=3)
    best = min(runs, key=lambda x: x.score)  # min keeps the first of equal scores
    assert (r.motifs, r.starts, r.score) == (best.motifs, best.starts, best.score)
    assert r.steps == tuple(x.steps for x in runs)


def test_each_run_ends_in_a_local_optimum_within_the_step_bound():
    rng = random.Random(7)
    for _ in range(60):
        n, L = rng.randint(2, 6), rng.randint(2, 6)
        seqs = [random_dna(rng, rng.randint(L, 20)) for _ in range(n)]
        starts = [rng.randrange(len(s) - L + 1) for s in seqs]
        start_score = motif_score([s[q:q + L] for s, q in zip(seqs, starts)])
        r = improve(seqs, L, starts)
        assert r.score == motif_score(r.motifs) <= start_score
        assert all(s[q:q + L] == m for s, q, m in zip(seqs, r.starts, r.motifs))
        assert r.steps <= start_score - r.score + 1 <= L * (n - (n + 3) // 4) + 1
        # One more profile step does not lower the score.
        counts = count_matrix(r.motifs, L)
        again = [s[q:q + L] for s in seqs for q in [most_probable(s, counts)]]
        assert motif_score(again) >= r.score


def test_score_is_never_below_the_optimum():
    rng = random.Random(9)
    for _ in range(20):
        seqs = [random_dna(rng, 7) for _ in range(3)]
        r = randomized_motif_search(seqs, 3, 20, seed=rng.randrange(1000))
        assert r.score >= brute_best_score(seqs, 3)


def test_planted_success_rate():
    # Measured on seeds 0 to 9 with 100 restarts: the consensus equals the
    # planted motif in 10 of 10 runs. The test asks for at least 8.
    hits = 0
    for seed in range(10):
        motif, seqs, _ = plant(random.Random(seed), 10, 100, 8, 1)
        hits += consensus(randomized_motif_search(seqs, 8, 100, seed=seed).motifs) == motif
    assert hits >= 8


def test_errors():
    with pytest.raises(ValueError):
        randomized_motif_search(["ACG"], 4, 1)
    with pytest.raises(ValueError):
        randomized_motif_search(["ACGT"], 2, 0)
    with pytest.raises(ValueError):
        randomized_motif_search(["ACGT"], 2, 1, pseudo=0)
    with pytest.raises(ValueError):
        improve(["ACGT", "ACGT"], 2, [0, 3])
    with pytest.raises(ValueError):
        randomized_motif_search([], 2, 1)

History

Lawrence and others (1993) built the Gibbs sampler on a random form of the same update: the profile of the other sites gives the probabilities of the windows of one sequence, and a draw picks the new site. Compeau and Pevzner (2015) gave the randomized motif search in its present form as a teaching step between the greedy search and the Gibbs sampler. The Rosalind problem BA2F asks for it. Compeau and Pevzner explain in Section 2.8 why a few correct windows in a random start are enough to pull the profile toward the motif.

References

  1. Phillip Compeau and Pavel Pevzner, Bioinformatics Algorithms, An Active Learning Approach, Volume I, 2nd edition, Active Learning Publishers, 2015, Chapter 2, Section 2.7 (randomized motif search) and Section 2.8 (how a randomized algorithm can perform so well)
  2. Charles E. Lawrence, Stephen F. Altschul, Mark S. Boguski, Jun S. Liu, Andrew F. Neuwald and John C. Wootton, Detecting subtle sequence signals, a Gibbs sampling strategy for multiple alignment, Science 262(5131), 1993, pp. 208 to 214, the profile and site update that the randomized search makes deterministic

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.per_step
  • 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