Algorithmcore
MEME
Also called multiple EM for motif elicitation.
Fit a two-component mixture of motif and background by expectation maximization, starting from many seed l-mers, to find motifs.
- Solves
- Motif finding
- Time
- O(n W^2 L + I n W L) worstO(N L) per_iteration
- Space
- O(N + L) extra
- Where
- G = the length of each sequence; I = the number of EM iterations; L = the motif length; N = the number of windows, n W; 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
- Timothy L. Bailey, Charles Elkan, 1994
MEME (multiple EM for motif elicitation) of Bailey and Elkan (1994) finds a motif by fitting a mixture model to all windows of length in the input. Each window comes either from a motif model, a position-specific scoring matrix of letter probabilities, or from a background model of single letters. Expectation maximization alternates between the probability that each window is a site and new models fitted to these weights. EM finds a local optimum, so MEME starts it from many strings that occur in the data and keeps the best. This page gives the EM core for one motif.
In plain words
Cut every sequence into all its overlapping pieces of length . Some pieces are copies of a hidden word, and the rest are noise. You do not know which, so you guess a model of the hidden word, a table with the chance of each letter at each place.
Now repeat two steps. First, for each piece, work out how likely it is to be a copy, given the table and the letters of the noise. Second, build a new table from all pieces, where each piece counts as much as its chance of being a copy. Each round makes the model fit the data at least as well as before. A poor first guess can lead to a poor answer, so start from many guesses, each one taken from a piece of the data.
The problem
Input. DNA sequences , each of length , and a motif length . Let be all windows, with . Positions are 1-based on this page and 0-based in the code. Let be the frequency of the letter in the input.
The model. Each window is a motif site with probability , and then its letters are independent with probabilities at column . Otherwise it is background, with letter probabilities at every column. So
The windows are treated as independent, though they overlap.
Output. The parameters at a local maximum of the objective
the log likelihood plus the log of a Dirichlet prior with prior counts, and the weights , the posterior probability that window is a site.
The algorithm
MEME(s[1 .. n], L, β, m)- 1
X ← all N windows of length L, μ ← the letter frequencies of s - 2
for each start string u do - 3
θ_j(a) ← m if a = u_j, else (1 - m)/3; θ_0 ← μ; λ ← n/N - 4
do one E step (L7) and one M step (L8, L9), and keep the start with the largest F - 5
(θ, θ_0, λ) ← the parameters of the kept start - 6
repeat - 7
z_k ← λ Π_j θ_j(X_k,j) / (λ Π_j θ_j(X_k,j) + (1 - λ) Π_j θ_0(X_k,j)) for k ← 1 to N - 8
λ ← Σ_k z_k / N; c_j(a) ← Σ_k z_k [X_k,j = a]; c_0(a) ← Σ_k (1 - z_k) #{j : X_k,j = a} - 9
θ_j(a) ← (c_j(a) + βμ(a)) / (Σ_b c_j(b) + β); θ_0(a) ← (c_0(a) + βμ(a)) / (Σ_b c_0(b) + β) - 10
until the largest change of a θ_j(a) is below tol, or the cap on iterations is reached - 11
return θ, θ_0, λ, z
Line L7 is the E step, a use of Bayes' theorem. Lines L8 and L9 are the M step: is the mean weight, and the letter probabilities are the weighted counts plus the prior counts, divided by their total. Lines L2 to L5 pick the start: Bailey and Elkan derive starting points from the subsequences of the data and pick the best of them. Here each start gets one iteration, and the best value of after it decides.
Choices of this code. The start strings are the distinct windows of by default; the motif occurs in every sequence, so has a copy, and this keeps the start phase at starts. The start probability and the prior weight are the choice of this code, picked on planted test data; they are not values from the paper. The code works in log space and clamps into . It leaves out three parts of MEME: the erasing of found sites to find more motifs, the smoothing that stops overlapping windows from all being sites, and the search over the start value of .
Example
Take the five sequences of Rosalind problem BA2F with , so . The kept start is AACGGCCA, the window at position 25 of . After 35 iterations the objective has grown from to , and the model is:
| column | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 |
|---|---|---|---|---|---|---|---|---|
| A | 0.768 | 0.630 | 0.005 | 0.002 | 0.117 | 0.006 | 0.310 | 0.761 |
| C | 0.227 | 0.086 | 0.194 | 0.126 | 0.004 | 0.532 | 0.683 | 0.235 |
| G | 0.003 | 0.163 | 0.799 | 0.308 | 0.490 | 0.230 | 0.005 | 0.003 |
| T | 0.002 | 0.121 | 0.002 | 0.564 | 0.389 | 0.233 | 0.002 | 0.002 |
Its consensus is AAGTGCCA, which is a median string of this input, with total distance 9, the optimum. The window with the largest in each sequence is AACGGCCA (position 25, ), AAGTGCCA (16, 0.995), AAGTATAC (19, 0.788), AAGTTTCA (7, 0.990) and CAGCTCCA (8, 0.934). The final is 0.092, more than : the model counts about 11.4 windows as sites, since nothing stops it from taking two windows of one sequence.
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 equals the planted motif. Over seeds 0 to 19, with the defaults:
| consensus found | all planted starts found | ||
|---|---|---|---|
| 100 | (8, 1) | 16 of 20 | 9 of 20 |
| 100 | (10, 2) | 2 of 20 | 3 of 20 |
| 200 | (12, 3) | 0 of 20 | 0 of 20 |
The second column counts runs in which the window with the largest in each sequence is the planted one. These are measurements of this reduced code on these seeds, not of the MEME program. In every one of these 60 runs the objective did not decrease from one iteration to the next.
Correctness
Theorem (EM ascent). No iteration of lines L7 to L9 lowers .
Proof. Let plus the prior term, where comes from the E step at . For each , , with in terms of the posterior at . By Gibbs' inequality, is largest at , that is, at . So . The M step maximizes : each term separates into a function of , maximized at , and for each column a sum over the simplex, maximized at , which is line L9. So does not drop.
This is the theorem of Dempster, Laird and Rubin, with the prior added. It gives convergence of , since is bounded above, but only to a stationary point, usually a local maximum. Different starts reach different local maxima, which is why lines L2 to L5 try many.
Theorem (the site rule). exactly when .
Proof. Let be the left side. Line L7 gives , and this is above exactly when the exponent is negative.
So the motif model is a position-specific scoring matrix of log odds, and the threshold for a site depends on . The tests check the ascent on the sample and on random inputs, the E step against Bayes' theorem, the site rule, and that the M step maximizes against 200 random and nearby parameters. The proofs are in proofs/correctness.md.
Proof: Each EM iteration of MEME does not lower the objective, and the E step gives the site rulefull
Let be windows of length over the letters A, C, G, T, let and . A parameter has and in the open simplex of four letters and . Write and , and
Lemma 1 (the E step). Line L7 sets , the posterior probability that comes from the motif component, by Bayes' theorem. The code computes and returns , which is the same number: divide the numerator and the denominator by .
Corollary (the site rule). exactly when , that is, when the log odds score of is above , since is increasing and equals at .
Lemma 2 (the M step maximizes Q). For weights , let
Then lines L8 and L9 give the unique maximizer of , apart from the clamp of .
Proof. is a sum of separate parts. The part in is with ; it is strictly concave and its derivative is 0 at . The part in is with . For positive weights , the function on the simplex has its unique maximum at : by Gibbs' inequality, with , with equality only at . Here , since , so the maximum is line L9. The part in is the same with .
Theorem (ascent). Let be the parameters before an iteration, the weights of the E step at , and the result of the M step. Then .
Proof. Let be the E step weight at . For each ,
since . So with , and in the same way . By Gibbs' inequality, for all . So , the last step by Lemma 2.
Corollary (convergence of the objective). is bounded above: each , and each prior term is at most 0. So the values of along the run increase to a limit. The parameters converge to a stationary point of under the usual regularity conditions of EM, which in general is a local maximum, not the global one. Different starts can reach different local maxima.
The clamp. The code keeps in . If the clamp is active, the part of is concave and the clamped value is its maximum over the clamped interval, so the ascent proof still holds on that interval.
Cost. The E step and the M step each look at every letter of every window a constant number of times, so an iteration takes time and extra space.
The tests check the ascent on the BA2F sample and on random inputs, Lemma 1 against a direct use of Bayes' theorem, the site rule, and Lemma 2 against 200 random parameters and small moves away from the maximizer.
Complexity
- Time. The E step computes products of terms, and the M step adds each window's letters with its weight, so an iteration takes time. Bailey and Elkan give the same linear cost per iteration. The start phase does one iteration for each of at most starts, , and main iterations add .
- Space. The weights take numbers and the models numbers, so besides the input.
- In practice. On the BA2F sample the main run takes 35 iterations. On the planted runs with and seeds 0 to 5, it takes between 69 and 170.
Properties
- Deterministic. There is no randomness; the result depends only on the input, the start strings and the parameters.
- Soft assignment. Every window has a weight between 0 and 1, so the model can use evidence from windows that only look a little like sites. The randomized motif search is the same method with hard 0 or 1 weights and one site per sequence.
- A local optimum. EM stops at a stationary point of , which depends on the start.
- A mixture model. The model is a two-component mixture, like a Gaussian mixture model with discrete components, and EM is fitted the same way.
Variants and improvements
- OOPS, ZOOPS and TCM. The MEME program offers three models of the sites: exactly one occurrence per sequence (the model of Lawrence and Reilly), zero or one per sequence, and any number. The code on this page fits the last, with no limit on the number of sites.
- Erasing. After a motif is found, MEME lowers the weights of the windows that it explains and runs again, to find the next motif.
- A search over . The start value of matters, and MEME tries several and keeps the best by a statistical measure.
- Better priors. Dirichlet mixture priors help on protein sequences.
- Discriminative and Bayesian versions. Later work fits the motif against a set of control sequences, or samples the sites, as in the Gibbs motif sampler.
When to use it
Use MEME, or this EM core, when the motif may occur zero, one or several times per sequence, or when you want a probability model of the motif with weights for every window. It is deterministic, so a run can be repeated exactly. For a subtle planted motif, start the EM from the buckets of PROJECTION, which is what Buhler and Tompa did, since starts taken from single windows often lead EM to the wrong local optimum.
Pitfalls
- Overlapping windows. The model treats the windows as independent, but they overlap. A strong site makes its shifted windows look like sites too, and grows. MEME smooths the weights to fix this; the code on this page does not.
- Zero probabilities. Without prior counts, a letter that no site has gets probability 0, and the logarithm fails. Keep .
- One iteration is not enough to judge a start. Lines L2 to L5 rank starts after one iteration, which can favour a start near a shifted copy of the motif, and EM then converges to the shifted copy.
- Underflow. The product of probabilities underflows for long motifs. Work with sums of logarithms.
- Reading as the number of sites. counts windows, and overlapping windows of one site each count.
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)
meme_algorithm.py 170 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/meme-algorithm/. The authors are listed in prov/FD26PV.jsonl.
"""The EM core of MEME (Bailey and Elkan 1994) for one motif: a two-component
mixture of a motif model and a background model over all windows of length L,
fit by expectation maximization from many starting points.
This code leaves out the parts of MEME that find several motifs (erasing),
the smoothing of z over overlapping windows and the search over lambda.
Positions are 0-based in this code; the page numbers them from 1.
"""
import math
from typing import List, NamedTuple, Optional, Sequence, Tuple
from bioseq import DNA, kmers
_INDEX = {a: k for k, a in enumerate(DNA)}
class MemeResult(NamedTuple):
"""The fitted model and the run history.
theta[j][a] is the motif letter probability, theta0[a] the background one,
lam the mixing weight, z the posterior motif probability of each window in
the order of windows(), start the start string chosen, and objective the
log posterior after each iteration of the main run.
"""
theta: Tuple[Tuple[float, ...], ...]
theta0: Tuple[float, ...]
lam: float
z: Tuple[float, ...]
start: str
objective: Tuple[float, ...]
iterations: int
def windows(seqs: Sequence[str], L: int) -> List[Tuple[int, int]]:
"""All windows as (sequence index, 0-based start), sequence by sequence."""
return [(i, q) for i, s in enumerate(seqs) for q in range(len(s) - L + 1)]
def letter_frequencies(seqs: Sequence[str]) -> List[float]:
"""mu[a]: the frequency of each letter over all sequences."""
total = sum(len(s) for s in seqs)
return [sum(s.count(a) for s in seqs) / total for a in DNA]
def _encode(seqs, L):
return [tuple(_INDEX[a] for a in w) for s in seqs for w in kmers(s, L)]
def objective(X, theta, theta0, lam, beta, mu) -> float:
"""The log posterior that MEME's EM increases: the mixture log likelihood
plus beta * sum mu(a) log of the motif and background probabilities."""
lt = [[math.log(p) for p in row] for row in theta]
l0 = [math.log(p) for p in theta0]
ll = 0.0
for x in X:
a1 = math.log(lam) + sum(lt[j][c] for j, c in enumerate(x))
a0 = math.log(1 - lam) + sum(l0[c] for c in x)
m = max(a1, a0)
ll += m + math.log(math.exp(a1 - m) + math.exp(a0 - m))
prior = sum(beta * mu[a] * lt[j][a] for j in range(len(theta)) for a in range(4))
prior += sum(beta * mu[a] * l0[a] for a in range(4))
return ll + prior
def e_step(X, theta, theta0, lam) -> List[float]:
"""z_k = lam P(X_k | theta) / (lam P(X_k | theta) + (1 - lam) P(X_k | theta0))."""
lt = [[math.log(p) for p in row] for row in theta]
l0 = [math.log(p) for p in theta0]
cut = math.log((1 - lam) / lam)
z = []
for x in X:
r = sum(lt[j][c] - l0[c] for j, c in enumerate(x)) - cut
z.append(1 / (1 + math.exp(-r)) if r >= 0 else math.exp(r) / (1 + math.exp(r)))
return z
def m_step(X, z, L, beta, mu):
"""lam = sum z / N, theta_j(a) = (c_j(a) + beta mu(a)) / (sum_a c_j(a) + beta), and the same for theta0."""
lam = sum(z) / len(X) # @line L8
c = [[0.0] * 4 for _ in range(L)]
c0 = [0.0] * 4
for x, zk in zip(X, z):
for j, a in enumerate(x):
c[j][a] += zk
c0[a] += 1 - zk
theta = [[(c[j][a] + beta * mu[a]) / (sum(c[j]) + beta) for a in range(4)] for j in range(L)] # @line L9
theta0 = [(c0[a] + beta * mu[a]) / (sum(c0) + beta) for a in range(4)]
lam = min(max(lam, 1e-12), 1 - 1e-12)
return theta, theta0, lam
def start_model(u: str, m: float) -> List[List[float]]:
"""The starting motif model of the string u: probability m for its letter, (1 - m) / 3 for the others."""
return [[m if a == _INDEX[x] else (1 - m) / 3 for a in range(4)] for x in u]
def meme(seqs: Sequence[str], L: int, beta: float = 0.1, m: float = 0.7,
starts: Optional[Sequence[str]] = None, tol: float = 1e-6, max_iter: int = 200) -> MemeResult:
"""Fit the motif and background mixture by EM and return the fitted model.
starts are the start strings; by default the distinct windows of the first
sequence, in order of first occurrence. Each start gets one EM iteration
from lambda = n / N; the start with the largest objective after it is run
to convergence (the largest change of a motif probability below tol, or
max_iter iterations). The defaults m = 0.7 and beta = 0.1 are the choice
of this code, picked on planted test data. Cost:
O(N L) per iteration for the N windows.
"""
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 beta <= 0 or not 0.25 < m < 1:
raise ValueError("beta must be positive and m in (0.25, 1)")
X = _encode(seqs, L) # @line L1
N = len(X)
mu = letter_frequencies(seqs)
if min(mu) == 0:
raise ValueError("every letter must occur in the input")
if starts is None:
starts = list(dict.fromkeys(kmers(seqs[0], L)))
lam0 = min(len(seqs) / N, 0.5)
best = None
for u in starts: # @line L2
if len(u) != L or set(u) - set(DNA):
raise ValueError("start strings must be over ACGT with length L")
theta, theta0, lam = start_model(u, m), list(mu), lam0 # @line L3
z = e_step(X, theta, theta0, lam) # @line L4
theta, theta0, lam = m_step(X, z, L, beta, mu)
f = objective(X, theta, theta0, lam, beta, mu)
if best is None or f > best[0]:
best = (f, u, theta, theta0, lam)
f, u, theta, theta0, lam = best # @line L5
history = [f]
it = 1
while True: # @line L6
z = e_step(X, theta, theta0, lam) # @line L7
new_theta, theta0, lam = m_step(X, z, L, beta, mu)
change = max(abs(p - r) for row, nrow in zip(theta, new_theta) for p, r in zip(row, nrow))
theta = new_theta
history.append(objective(X, theta, theta0, lam, beta, mu))
it += 1
if change < tol or it >= max_iter: # @line L10
break
z = e_step(X, theta, theta0, lam)
return MemeResult(tuple(map(tuple, theta)), tuple(theta0), lam, tuple(z), u, tuple(history), it) # @line L11
def consensus(theta) -> str:
"""The most probable letter of each column (the first in ACGT order on a tie)."""
return "".join(DNA[max(range(4), key=lambda a: (row[a], -a))] for row in theta)
def best_sites(seqs: Sequence[str], L: int, z: Sequence[float]) -> Tuple[int, ...]:
"""For each sequence, the 0-based start of its window with the largest z (the first on a tie)."""
out, k = [], 0
for s in seqs:
w = len(s) - L + 1
row = z[k:k + w]
out.append(max(range(w), key=lambda q: (row[q], -q)))
k += w
return tuple(out)
test_meme_algorithm.py 140 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/meme-algorithm/. The authors are listed in prov/FD26PV.jsonl.
import math
import random
import pytest
from bioseq import DNA, random_dna
from meme_algorithm import (_encode, best_sites, consensus, e_step, letter_frequencies, m_step, meme, objective,
start_model)
# Sample data of Rosalind problem BA2F (k = 8, t = 5).
SAMPLE = [
"CGCCCCTCTCGGGGGTGTTCAGTAAACGGCCA",
"GGGCGAGGTATGTGTAAGTGCCAAGGTGCCAG",
"TAGTACCGAGACCGAAAGAAGTATACAGGCGT",
"TAGATCAAGTTTCAGGTGCACGTCGGTGAACC",
"AATCCACCAGCTCCACGTGCAATGTTGGCCTA",
]
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 random_simplex(rng):
v = [rng.random() + 1e-3 for _ in range(4)]
s = sum(v)
return [x / s for x in v]
def test_objective_never_decreases():
r = meme(SAMPLE, 8)
assert all(b >= a - 1e-9 for a, b in zip(r.objective, r.objective[1:]))
rng = random.Random(3)
for _ in range(4):
seqs = [random_dna(rng, 15) for _ in range(4)]
r = meme(seqs, 4, max_iter=60)
assert all(b >= a - 1e-9 for a, b in zip(r.objective, r.objective[1:]))
def test_e_step_is_the_bayes_posterior_and_the_threshold():
rng = random.Random(8)
seqs = [random_dna(rng, 12) for _ in range(3)]
X = _encode(seqs, 3)
theta = [random_simplex(rng) for _ in range(3)]
theta0 = random_simplex(rng)
for lam in (0.05, 0.3, 0.7):
z = e_step(X, theta, theta0, lam)
for x, zk in zip(X, z):
p1 = math.prod(theta[j][c] for j, c in enumerate(x))
p0 = math.prod(theta0[c] for c in x)
assert abs(zk - lam * p1 / (lam * p1 + (1 - lam) * p0)) < 1e-12
llr = math.log(p1 / p0)
cut = math.log((1 - lam) / lam)
if abs(llr - cut) > 1e-9:
assert (zk > 0.5) == (llr > cut)
def test_m_step_maximizes_the_expected_log_posterior():
rng = random.Random(11)
seqs = [random_dna(rng, 10) for _ in range(3)]
L, beta = 3, 0.5
X = _encode(seqs, L)
mu = letter_frequencies(seqs)
z = [rng.random() for _ in X]
def q_value(theta, theta0, lam):
v = 0.0
for x, zk in zip(X, z):
v += zk * (math.log(lam) + sum(math.log(theta[j][c]) for j, c in enumerate(x)))
v += (1 - zk) * (math.log(1 - lam) + sum(math.log(theta0[c]) for c in x))
v += sum(beta * mu[a] * math.log(theta[j][a]) for j in range(L) for a in range(4))
v += sum(beta * mu[a] * math.log(theta0[a]) for a in range(4))
return v
theta, theta0, lam = m_step(X, z, L, beta, mu)
top = q_value(theta, theta0, lam)
for _ in range(200):
t = [random_simplex(rng) for _ in range(L)]
assert q_value(t, random_simplex(rng), rng.uniform(0.01, 0.99)) <= top
# Small moves away from the M step values do not help either.
eps = 1e-3
t2 = [[p + eps * (1 if a == 0 else -1 / 3) for a, p in enumerate(row)] for row in theta]
assert q_value(t2, theta0, lam) <= top
def test_rosalind_ba2f_consensus_is_the_median_string():
r = meme(SAMPLE, 8)
# AAGTGCCA is a median string of this input (total distance 9, the optimum).
assert consensus(r.theta) == "AAGTGCCA"
sites = best_sites(SAMPLE, 8, r.z)
assert [s[q:q + 8] for s, q in zip(SAMPLE, sites)][:2] == ["AACGGCCA", "AAGTGCCA"]
def test_start_model():
th = start_model("ACG", 0.7)
assert [round(sum(row), 12) for row in th] == [1, 1, 1]
assert th[2][DNA.index("G")] == 0.7
def test_planted_success_rate():
# Measured on seeds 0 to 2: the consensus of theta equals the planted motif
# in 2 of 3 runs (seed 0 misses). The code is deterministic; the test asks
# for at least 2. Three seeds keep the test fast on a loaded machine.
hits = 0
for seed in range(3):
motif, seqs, _ = plant(random.Random(seed), 10, 100, 8, 1)
hits += consensus(meme(seqs, 8).theta) == motif
assert hits >= 2
def test_errors():
with pytest.raises(ValueError):
meme(["ACG"], 4)
with pytest.raises(ValueError):
meme(["ACGT"], 2, m=0.2)
with pytest.raises(ValueError):
meme(["AAAA"], 2)
with pytest.raises(ValueError):
meme(["ACGTACGT"], 2, starts=["ACG"])
with pytest.raises(ValueError):
meme([], 2)
History
Lawrence and Reilly (1990) used EM to find a site in each of a set of unaligned protein and DNA sequences, with exactly one site per sequence. Bailey and Elkan (1994) made three changes: a mixture model over all windows, so that a sequence can have no site or several, many starting points taken from the subsequences of the data, and the erasing of found sites so that one run finds several motifs. The MEME program grew from this work and became one of the most used motif finders. The general EM method and its ascent property are due to Dempster, Laird and Rubin (1977).
References
- Fitting a mixture model by expectation maximization to discover motifs in biopolymers, the two-component mixture model, the E step and the M step with Dirichlet prior counts, the starting points from subsequences, and erasing
- Charles E. Lawrence and Andrew A. Reilly, An expectation maximization (EM) algorithm for the identification and characterization of common sites in unaligned biopolymer sequences, Proteins 7(1), 1990, pp. 41 to 51, EM with one site per sequence
- Arthur P. Dempster, Nan M. Laird and Donald B. Rubin, Maximum likelihood from incomplete data via the EM algorithm, Journal of the Royal Statistical Society, Series B 39(1), 1977, pp. 1 to 22, the EM algorithm and the proof that each iteration does not lower the likelihood
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 FD26PV Edit this page History Report an error Markdown