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.
- Solves
- Motif finding
- 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
- Model
- Word RAM
- Properties
- deterministicnot exactofflineiterative
- Evidence
- Proof sketchCode in 1 languages
- 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 results is the output. It runs in 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 , each of length , a motif length , and a pseudocount (0 or 1 in practice). Each sequence has windows. Positions are 1-based on this page and 0-based in the code.
Output. One window in each sequence, with a small motif score , where counts the letter in column of the windows. The method does not promise the smallest score.
The algorithm
Let the counts of the first chosen windows, plus , be . The profile is , and the probability of a window is . All windows share the denominator , so the most probable window is the one with the largest product of counts , an exact integer.
GREEDY-MOTIF(s[1 .. n], L, b)- 1
best ← (s_1[1 .. L], ..., s_n[1 .. L]), bestscore ← Score(best) - 2
for q ← 1 to W do - 3
t_1 ← s_1[q .. q + L - 1], c_j(a) ← b for every column j and letter a - 4
for i ← 2 to n do - 5
add the letters of t_(i-1) to the counts c - 6
t_i ← the first window w of s_i with the largest Π_j c_j(w_j) - 7
if Score(t_1, ..., t_n) < bestscore then best ← (t_1, ..., t_n), bestscore ← Score(best) - 8
return 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 ), 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 . The table shows the result of each seed for and for , with the 1-based starts:
| seed | windows, | score | windows, | 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 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 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 column shows the trouble with zero counts. With seed 7, the profile of CAG and CAG gives probability 0 to every window of , since has no CAG, and line L6 falls back to the first window CAA. Most seeds take AAG in for the same reason: no window of 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 too.
A miss. On CAGAACCT, GCTGTGAC and ATAAACTA with , the optimum is AAC, GAC, AAC (starts 4, 6, 4) with score 1. With , 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 , GAC gets a positive probability and the optimum is found.
Measured success on planted motifs. The test generator plants a motif with exactly 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:
| 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 is a window of , since line L6 picks from the windows of and line L1 starts with windows. The returned score is the smallest score over the 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 be DNA sequences, each with at least letters, and let 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 , for every column and letter .
Proof. Line L3 sets every count to . Before line L6 runs for , line L5 has run once for each of , and the run for adds the letters of . So the windows added are , each once.
Lemma 2 (line L6 picks a most probable window). Let be the profile of the counts of Lemma 1. Line L6 returns the first window of with the largest .
Proof. By Lemma 1, for every column, so for every window . 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 , 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.
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 from each sequence, and the start recorded for is the start of that window.
Proof. Line L1 takes the first window of each sequence. In a seed run, is a window of by line L3, and each for is a window of by line L6. The code stores the start and the window together.
Theorem. GREEDY-MOTIF returns a tuple with a window of , and its motif score is the smallest score among the start tuple of line L1 and the 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 changes only at line L7, and only to a candidate with a strictly smaller score. So after all seeds, is the minimum of the scores of the candidates, and is the first candidate that reached it. Line L8 returns it.
Cost. There are seeds. In each seed run, line L5 costs per sequence, and line L6 looks at windows of letters, so a seed run costs , and line L7 adds . The total is time. The counts take integers and the current tuple windows, so the extra space is .
The result is not always optimal. Take $s_1 = $ CAGAACCT, $s_2 = $ GCTGTGAC, $s_3 = $ ATAAACTA, and . The tuple AAC, GAC, AAC (1-based starts 4, 6, 4) has score 1, and no tuple has score 0, since no window of 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 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 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 seeds. For each seed and each of the later sequences, line L5 takes time and line L6 scans windows at time each. Line L7 takes . So the total is .
- Space. The counts take words and the chosen windows letters, so .
- In practice. For , and , steps, which is fast. The exact searches cost or 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 and the profile grows in the given order. Another order can give another result.
- Pseudocounts matter. With 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 (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 and with the best score and then add one sequence at a time. The cost of the seed step is .
- 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 is small, an exact median string search is affordable and gives the optimum.
Pitfalls
- No pseudocounts. With , 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 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.
# 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
- 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
- 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)
- 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
- 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.
| 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 5WRFD0 Edit this page History Report an error Markdown