Algorithm Search⌘K

Algorithmintro

Greedy motif search

Also called CONSENSUS algorithm.

Seed with each window of the first sequence, add from each next sequence the window most probable under the profile of the windows so far, and keep the best result.

Time
O(W^2 n L) worst · average
Space
O(n 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
deterministicnot exactofflineiterative
Origin
Gerald Z. Hertz, George W. Hartzell, Gary D. Stormo, 1990

Greedy motif search is a fast heuristic for the motif finding problem. It tries each window of the first sequence as a seed. From the seed it builds a profile, the column frequencies of the windows chosen so far, and adds from each next sequence the window that is most probable under that profile. The best of the WW results is the output. It runs in O(W2nL)O(W^2 n L) time, but it can miss the optimum, and without pseudocounts it often does.

In plain words

Start with one short piece of the first sequence and guess that it is the hidden word. Look in the second sequence for the piece that best fits your guess, and add it to your list. Now you have two pieces. For each column, count the letters of the pieces. Look in the third sequence for the piece that best fits these counts, and add it. Go on to the last sequence.

Do this once for every possible start piece in the first sequence, and keep the list whose pieces agree best. Each choice is made once and never changed, which is why the method is called greedy. A small fix helps a lot: add one to every count, so that a letter that you have not seen yet in a column is not ruled out.

The problem

Input. DNA sequences s1,…,sns_1, \ldots, s_n, each of length GG, a motif length LL, and a pseudocount b≥0b \ge 0 (0 or 1 in practice). 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 method does not promise the smallest score.

The algorithm

Let the counts of the first i−1i - 1 chosen windows, plus bb, be cj(a)c_j(a). The profile is Pj(a)=cj(a)/(i−1+4b)P_j(a) = c_j(a) / (i - 1 + 4b), and the probability of a window ww is ∏jPj(wj)\prod_j P_j(w_j). All windows share the denominator (i−1+4b)L(i - 1 + 4b)^L, so the most probable window is the one with the largest product of counts ∏jcj(wj)\prod_j c_j(w_j), an exact integer.

  1. GREEDY-MOTIF(s[1 .. n], L, b)
  2. 1best ← (s_1[1 .. L], ..., s_n[1 .. L]), bestscore ← Score(best)
  3. 2for q ← 1 to W do
  4. 3t_1 ← s_1[q .. q + L - 1], c_j(a) ← b for every column j and letter a
  5. 4for i ← 2 to n do
  6. 5add the letters of t_(i-1) to the counts c
  7. 6t_i ← the first window w of s_i with the largest Π_j c_j(w_j)
  8. 7if Score(t_1, ..., t_n) < bestscore then best ← (t_1, ..., t_n), bestscore ← Score(best)
  9. 8return best

Line L1 starts from the first window of every sequence, as Compeau and Pevzner do. Line L3 picks the seed. Lines L5 and L6 are the greedy step: the profile of the windows chosen so far picks the next window, and the choice is never undone. Line L6 breaks ties by the first window, and if every product is 0 (possible only with b=0b = 0), it takes the first window of the sequence. Line L7 keeps a new result only if it is strictly better.

Example

Take the five sequences of Rosalind problem BA2D, GGCGTTCAGGCA, AAGAATCAGTCA, CAAGGAGTTCGC, CACGTCAATCAC and CAATAATATTCG, with L=3L = 3. The table shows the result of each seed for b=0b = 0 and for b=1b = 1, with the 1-based starts:

seed qq windows, b=0b = 0 score windows, b=1b = 1 score
1 GGC AAG AAG CAC CAA 7 GGC GTC GGA GTC TTC 4
2 GCG AAG AAG ACG CAA 5 GCG AAG AAG ACG TCG 4
3 CGT AAG AAG AAT AAT 4 CGT AGT AGT CGT AAT 3
4 GTT AAG AAG AAT AAT 4 GTT GTC GTT GTC ATT 3
5 TTC AAG AAG ATC TTC 6 TTC ATC TTC ATC TTC 2
6 TCA TCA CAA TCA TAA 3 TCA TCA TCG TCA TCG 2
7 CAG CAG CAA CAA CAA 2 CAG CAG CAA CAA CAA 2
8 AGG AAG AAG CAC CAA 5 AGG AAG AAG ACG AAT 3
9 GGC AAG AAG CAC CAA 7 GGC GTC GGA GTC TTC 4
10 GCA AAG AAG ACG CAA 6 GCA GAA GGA TCA TAA 5

With b=0b = 0 the output is CAG, CAG, CAA, CAA, CAA from seed 7, at starts 7, 7, 1, 6, 1, which is the sample answer of BA2D. With b=1b = 1 the first seed that reaches score 2 is seed 5, and the output is TTC, ATC, TTC, ATC, TTC, the sample answer of BA2E. Both have score 2, the optimum of this input.

The b=0b = 0 column shows the trouble with zero counts. With seed 7, the profile of CAG and CAG gives probability 0 to every window of s3s_3, since s3s_3 has no CAG, and line L6 falls back to the first window CAA. Most seeds take AAG in s2s_2 for the same reason: no window of s2s_2 equals the seed, so every product is 0 and AAG, the first window, is taken. The profile of the seed and AAG then makes AAG the most probable window of s3s_3 too.

A miss. On CAGAACCT, GCTGTGAC and ATAAACTA with L=3L = 3, the optimum is AAC, GAC, AAC (starts 4, 6, 4) with score 1. With b=0b = 0, the seed AAC gives probability 0 to every window of the second sequence, since none is AAC, so the search takes the first window GCT, and the best of all seeds has score 2. With b=1b = 1, GAC gets a positive probability and the optimum is found.

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. Over seeds 0 to 19:

GG (L,d)(L, d) b=0b = 0 b=1b = 1
100 (8, 1) 1 of 20 19 of 20
100 (10, 2) 0 of 20 10 of 20
200 (12, 3) 0 of 20 4 of 20

These are measurements on these seeds, not guarantees.

Correctness

The method is a heuristic, so the claim is about what it returns, not about optimality. Each returned tit_i is a window of sis_i, since line L6 picks from the windows of sis_i and line L1 starts with windows. The returned score is the smallest score over the WW seed runs and the start, since line L7 keeps a strict minimum. Line L6 returns a most probable window: the profile probabilities of all windows have the same denominator, so their order is the order of the integer products. The greedy result is not always optimal; the miss above is a counterexample, and the tests check it against brute force. The proof of the facts about line L6 and line L7 is in proofs/correctness.md.

Proof: Greedy motif search returns valid windows with the best score over its seedsfull

Let s1,…,sns_1, \ldots, s_n be DNA sequences, each with at least LL letters, and let b≥0b \ge 0 be an integer pseudocount. The claim is about what GREEDY-MOTIF returns. It does not claim that the result is optimal, and the last part of this note shows that it is not always optimal.

Lemma 1 (the counts). When line L6 runs for sequence sis_i, cj(a)=b+#{k<i:tk[j]=a}c_j(a) = b + \#\{k < i : t_k[j] = a\} for every column jj and letter aa.

Proof. Line L3 sets every count to bb. Before line L6 runs for sis_i, line L5 has run once for each of s2,…,sis_2, \ldots, s_i, and the run for sks_k adds the letters of tk−1t_{k-1}. So the windows added are t1,…,ti−1t_1, \ldots, t_{i-1}, each once. □\square

Lemma 2 (line L6 picks a most probable window). Let Pj(a)=cj(a)/(i−1+4b)P_j(a) = c_j(a) / (i - 1 + 4b) be the profile of the counts of Lemma 1. Line L6 returns the first window ww of sis_i with the largest ∏jPj(wj)\prod_j P_j(w_j).

Proof. By Lemma 1, ∑acj(a)=i−1+4b\sum_a c_j(a) = i - 1 + 4b for every column, so ∏jPj(wj)=∏jcj(wj)/(i−1+4b)L\prod_j P_j(w_j) = \prod_j c_j(w_j) / (i - 1 + 4b)^L for every window ww. The denominator is positive and the same for all windows, so the order of the probabilities is the order of the integer products. The code computes the products exactly with integers, keeps a window only when its product is strictly larger than the best so far, and starts with the value −1-1, so the first window with the largest product is returned. If every product is 0, the first window has the largest product and is returned. □\square

Lemma 3 (the result is a choice of windows). Each tuple formed in a seed run, and the start tuple of line L1, has one window of length LL from each sequence, and the start recorded for sis_i is the start of that window.

Proof. Line L1 takes the first window of each sequence. In a seed run, t1t_1 is a window of s1s_1 by line L3, and each tit_i for i≥2i \ge 2 is a window of sis_i by line L6. The code stores the start pp and the window si[p..p+L−1]s_i[p .. p + L - 1] together. □\square

Theorem. GREEDY-MOTIF returns a tuple (t1,…,tn)(t_1, \ldots, t_n) with tit_i a window of sis_i, and its motif score is the smallest score among the start tuple of line L1 and the WW tuples of the seed runs. Among tuples with this score, it is the first one in the order start tuple, seed 1, seed 2, and so on.

Proof. By Lemma 3 every candidate is a valid choice of windows. The value of bestbest changes only at line L7, and only to a candidate with a strictly smaller score. So after all seeds, bestscorebestscore is the minimum of the scores of the candidates, and bestbest is the first candidate that reached it. Line L8 returns it. □\square

Cost. There are WW seeds. In each seed run, line L5 costs O(L)O(L) per sequence, and line L6 looks at WW windows of LL letters, so a seed run costs O(nWL)O(n W L), and line L7 adds O(nL)O(nL). The total is O(W2nL)O(W^2 n L) time. The counts take 4L4L integers and the current tuple nn windows, so the extra space is O(nL)O(nL).

The result is not always optimal. Take $s_1 = $ CAGAACCT, $s_2 = $ GCTGTGAC, $s_3 = $ ATAAACTA, L=3L = 3 and b=0b = 0. The tuple AAC, GAC, AAC (1-based starts 4, 6, 4) has score 1, and no tuple has score 0, since no window of s1s_1 occurs in all three sequences. The six seed runs give scores 6, 3, 4, 3, 2 and 4. For the seed AAC, no window of s2s_2 equals AAC, so every product is 0 and Lemma 2 gives the first window GCT. The start tuple CAG, GCT, ATA has score 6. So the result has score 2, above the optimum 1. With b=1b = 1 the seed AAC gives GAC a positive probability, and the search returns the optimum. The tests check both runs, and check on random inputs that the greedy score is never below the brute-force optimum.

Complexity

  • Time. There are WW seeds. For each seed and each of the n−1n - 1 later sequences, line L5 takes O(L)O(L) time and line L6 scans WW windows at O(L)O(L) time each. Line L7 takes O(nL)O(nL). So the total is O(W(nWL+nL))=O(W2nL)O(W (n W L + n L)) = O(W^2 n L).
  • Space. The counts take 4L4L words and the chosen windows nLnL letters, so O(nL)O(nL).
  • In practice. For n=20n = 20, G=600G = 600 and L=15L = 15, W2nL=5862×20×15≈1.0×108W^2 n L = 586^2 \times 20 \times 15 \approx 1.0 \times 10^8 steps, which is fast. The exact searches cost 4L4^L or WnW^n instead.

Properties

  • Deterministic. There is no randomness, and ties go to the first window and the first seed.
  • Not exact. It can return a score above the optimum, as in the miss above.
  • Order dependent. The result depends on the order of the sequences: the seed comes from s1s_1 and the profile grows in the given order. Another order can give another result.
  • Pseudocounts matter. With b=0b = 0 a single unseen letter gives a window probability 0, and the search can fall back to the first window of a sequence for no reason in the data. With b=1b = 1 (Laplace's rule) every window has a positive probability.

Variants and improvements

  • The best pair as the seed. Jones and Pevzner start from the pair of windows of s1s_1 and s2s_2 with the best score and then add one sequence at a time. The cost of the seed step is O(W2L)O(W^2 L).
  • CONSENSUS. The program of Hertz and Stormo builds alignments one sequence at a time in the same way, but it scores them by information content against the background, and it reports the statistical significance of the result. It differs from the plain greedy search on this page in its score and its details.
  • Several orders. Run the search with several orders of the sequences and keep the best result, to reduce the effect of the order.
  • As a start for a local search. The output is a good start for a randomized motif search or a Gibbs sampler, or a first bound for a branch and bound search.

When to use it

Use greedy motif search when you need a quick answer or a starting point, and the motif is strong: a long motif with few changes in each site. Always use a pseudocount. When the motif is subtle, as in the planted (15, 4) motif of Pevzner and Sze, the greedy search fails most of the time, and a randomized search, MEME or PROJECTION is the better choice. When LL is small, an exact median string search is affordable and gives the optimum.

Pitfalls

  • No pseudocounts. With b=0b = 0, most windows get probability 0 after one or two steps, and line L6 picks the first window of a sequence by default. The success rates above drop from 19 of 20 to 1 of 20.
  • Floating point products. The product of LL probabilities underflows for long motifs, and ties between equal products can break in a different way after rounding. Compare integer products of counts, or sums of logarithms with a fixed tie rule.
  • Scoring the profile and not the windows. Line L7 compares the motif scores of the windows, not the probabilities of the profile, which grow as the profile becomes narrow.
  • Reading the output as the answer. The output has a small score but need not be optimal. Check it with an exact method on small data, or run the search with several orders.

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)
greedy_motif_search.py 93 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/greedy-motif-search/. The authors are listed in prov/5WRFD0.jsonl.
"""Greedy motif search (GreedyMotifSearch of Compeau and Pevzner), with or
without pseudocounts.

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

from typing import List, NamedTuple, Sequence, Tuple

from bioseq import DNA, kmers

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


class GreedyResult(NamedTuple):
    """The chosen windows, their 0-based starts and their motif score."""

    motifs: Tuple[str, ...]
    starts: Tuple[int, ...]
    score: 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) -> List[List[int]]:
    """counts[j][a] = the number of windows with letter a in column j, plus pseudo."""
    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 profile probability.

    The profile is counts[j][a] / (row sum). The row sums are equal, so the
    largest probability is the largest product of counts, computed exactly with
    integers. If every product is 0, the first window wins.
    """
    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 == 0:
                break
        if v > best_v:
            best_q, best_v = q, v
    return best_q


def greedy_motif_search(seqs: Sequence[str], L: int, pseudo: int = 0) -> GreedyResult:
    """Try each window of the first sequence as a seed; extend it one sequence at a time
    with the most probable window under the profile of the windows chosen so far.

    pseudo is the pseudocount added to every count (0 in the first version of
    Compeau and Pevzner, 1 for Laplace's rule). Among seeds with the same score
    the first one wins. Cost: O(W^2 n L) time for W = G - L + 1, O(nL) space.
    """
    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")
    if pseudo < 0:
        raise ValueError("pseudo must be at least 0")
    n = len(seqs)
    best_starts = tuple([0] * n)  # @line L1
    best_motifs = tuple(s[:L] for s in seqs)
    best_score = motif_score(best_motifs)
    for q in range(len(seqs[0]) - L + 1):  # @line L2
        starts = [q]  # @line L3
        motifs = [seqs[0][q:q + L]]
        counts = count_matrix([], L, pseudo)
        for i in range(1, n):  # @line L4
            for j, a in enumerate(motifs[-1]):  # @line L5
                counts[j][_INDEX[a]] += 1
            p = most_probable(seqs[i], counts)  # @line L6
            starts.append(p)
            motifs.append(seqs[i][p:p + L])
        sc = motif_score(motifs)
        if sc < best_score:  # @line L7
            best_starts, best_motifs, best_score = tuple(starts), tuple(motifs), sc
    return GreedyResult(best_motifs, best_starts, best_score)  # @line L8
test_greedy_motif_search.py 116 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/greedy-motif-search/. The authors are listed in prov/5WRFD0.jsonl.

import itertools
import random

import pytest

from bioseq import DNA, kmers, random_dna
from greedy_motif_search import count_matrix, greedy_motif_search, most_probable, motif_score

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


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_ba2d_without_pseudocounts():
    r = greedy_motif_search(SAMPLE, 3)
    assert r.motifs == ("CAG", "CAG", "CAA", "CAA", "CAA")
    assert r.starts == (6, 6, 0, 5, 0)
    assert r.score == 2


def test_rosalind_ba2e_with_pseudocounts():
    r = greedy_motif_search(SAMPLE, 3, pseudo=1)
    assert r.motifs == ("TTC", "ATC", "TTC", "ATC", "TTC")
    assert r.score == 2


def test_most_probable_matches_float_profile():
    rng = random.Random(5)
    for _ in range(40):
        L = rng.randint(2, 5)
        rows = [random_dna(rng, L) for _ in range(rng.randint(1, 4))]
        seq = random_dna(rng, rng.randint(L, 15))
        pseudo = rng.randint(0, 1)
        counts = count_matrix(rows, L, pseudo)
        total = len(rows) + 4 * pseudo
        probs = []
        for w in kmers(seq, L):
            p = 1.0
            for j, a in enumerate(w):
                p *= counts[j][DNA.index(a)] / total
            probs.append(p)
        # The first window with the largest probability (exact ties come from equal products).
        assert most_probable(seq, counts) == probs.index(max(probs))


def test_not_optimal_without_pseudocounts():
    seqs = ["CAGAACCT", "GCTGTGAC", "ATAAACTA"]
    r = greedy_motif_search(seqs, 3)
    assert r.score == 2 and brute_best_score(seqs, 3) == 1
    # With one pseudocount the seed AAC reaches GAC, and the optimum is found.
    r1 = greedy_motif_search(seqs, 3, pseudo=1)
    assert r1.motifs == ("AAC", "GAC", "AAC") and r1.score == 1


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)]
        for pseudo in (0, 1):
            r = greedy_motif_search(seqs, 3, pseudo)
            assert r.score == motif_score(r.motifs) >= brute_best_score(seqs, 3)
            assert all(s[q:q + 3] == m for s, q, m in zip(seqs, r.starts, r.motifs))


def test_planted_success_rate_with_pseudocounts():
    # Measured on seeds 0 to 9: the consensus equals the planted motif in 10 of 10
    # runs with pseudocount 1 and in 0 of 10 runs without. The test asks for at least 8 and at most 3.
    hits = {0: 0, 1: 0}
    for seed in range(10):
        motif, seqs, _ = plant(random.Random(seed), 10, 100, 8, 1)
        for pseudo in (0, 1):
            hits[pseudo] += consensus(greedy_motif_search(seqs, 8, pseudo).motifs) == motif
    assert hits[1] >= 8
    assert hits[0] <= 3


def test_errors():
    with pytest.raises(ValueError):
        greedy_motif_search(["ACG"], 4)
    with pytest.raises(ValueError):
        greedy_motif_search([], 2)
    with pytest.raises(ValueError):
        greedy_motif_search(["ACGT"], 2, pseudo=-1)
    with pytest.raises(ValueError):
        greedy_motif_search(["ACXT"], 2)

History

Hertz, Hartzell and Stormo (1990) described a greedy method that builds a weight matrix from unaligned sequences one sequence at a time and keeps the matrix least likely to arise by chance. Hertz and Stormo (1999) revised it as the CONSENSUS program, with an information content score and p-values for the alignments. Jones and Pevzner (2004) presented a greedy motif search that starts from the best pair of windows, and Compeau and Pevzner (2015) the form on this page, with every window of the first sequence as a seed and with Laplace's rule of succession as the fix for zero counts. The greedy search is now the standard first example of a motif finding heuristic.

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.5 (greedy motif search) and the section on pseudocounts that follows it
  2. Neil C. Jones and Pavel A. Pevzner, An Introduction to Bioinformatics Algorithms, MIT Press, 2004, Chapter 5, Section 5.5, a greedy approach to motif finding (the seed from the best pair of windows)
  3. Gerald Z. Hertz, George W. Hartzell and Gary D. Stormo, Identification of consensus patterns in unaligned DNA sequences known to be functionally related, CABIOS 6(2), 1990, pp. 81 to 92, the greedy construction of a weight matrix, one sequence at a time
  4. Gerald Z. Hertz and Gary D. Stormo, Identifying DNA and protein patterns with statistically significant alignments of multiple sequences, Bioinformatics 15, 1999, pp. 563 to 577, the CONSENSUS program, its information content score and the p-values of the alignments

About this page

The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.

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