Algorithm Search⌘K

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.

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
Properties
deterministicnot exactofflineiterative
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 LL 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 LL. 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 s1,…,sns_1, \ldots, s_n, each of length GG, and a motif length LL. Let X1,…,XNX_1, \ldots, X_N be all N=nWN = nW windows, with W=G−L+1W = G - L + 1. Positions are 1-based on this page and 0-based in the code. Let μ(a)\mu(a) be the frequency of the letter aa in the input.

The model. Each window is a motif site with probability λ\lambda, and then its letters are independent with probabilities θj(a)\theta_j(a) at column jj. Otherwise it is background, with letter probabilities θ0(a)\theta_0(a) at every column. So

P(Xk)=λ∏jθj(Xk,j)+(1−λ)∏jθ0(Xk,j).P(X_k) = \lambda \prod_{j} \theta_j(X_{k,j}) + (1 - \lambda) \prod_{j} \theta_0(X_{k,j}).

The windows are treated as independent, though they overlap.

Output. The parameters θ,θ0,λ\theta, \theta_0, \lambda at a local maximum of the objective

F=∑k=1Nlog⁡P(Xk)+β∑aμ(a)(∑jlog⁡θj(a)+log⁡θ0(a)),F = \sum_{k=1}^{N} \log P(X_k) + \beta \sum_a \mu(a) \Big( \sum_j \log \theta_j(a) + \log \theta_0(a) \Big),

the log likelihood plus the log of a Dirichlet prior with βμ(a)\beta\mu(a) prior counts, and the weights zkz_k, the posterior probability that window kk is a site.

The algorithm

  1. MEME(s[1 .. n], L, β, m)
  2. 1X ← all N windows of length L, μ ← the letter frequencies of s
  3. 2for each start string u do
  4. 3θ_j(a) ← m if a = u_j, else (1 - m)/3; θ_0 ← μ; λ ← n/N
  5. 4do one E step (L7) and one M step (L8, L9), and keep the start with the largest F
  6. 5(θ, θ_0, λ) ← the parameters of the kept start
  7. 6repeat
  8. 7z_k ← λ Π_j θ_j(X_k,j) / (λ Π_j θ_j(X_k,j) + (1 - λ) Π_j θ_0(X_k,j)) for k ← 1 to N
  9. 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}
  10. 9θ_j(a) ← (c_j(a) + βμ(a)) / (Σ_b c_j(b) + β); θ_0(a) ← (c_0(a) + βμ(a)) / (Σ_b c_0(b) + β)
  11. 10until the largest change of a θ_j(a) is below tol, or the cap on iterations is reached
  12. 11return θ, θ_0, λ, z

Line L7 is the E step, a use of Bayes' theorem. Lines L8 and L9 are the M step: λ\lambda 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 FF after it decides.

Choices of this code. The start strings are the distinct windows of s1s_1 by default; the motif occurs in every sequence, so s1s_1 has a copy, and this keeps the start phase at O(W)O(W) starts. The start probability m=0.7m = 0.7 and the prior weight β=0.1\beta = 0.1 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 λ\lambda into (10−12,1−10−12)(10^{-12}, 1 - 10^{-12}). 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 λ\lambda.

Example

Take the five sequences of Rosalind problem BA2F with L=8L = 8, so N=125N = 125. The kept start is AACGGCCA, the window at position 25 of s1s_1. After 35 iterations the objective has grown from −1367.755-1367.755 to −1357.015-1357.015, 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 zz in each sequence is AACGGCCA (position 25, z=0.959z = 0.959), AAGTGCCA (16, 0.995), AAGTATAC (19, 0.788), AAGTTTCA (7, 0.990) and CAGCTCCA (8, 0.934). The final λ\lambda is 0.092, more than n/N=0.04n/N = 0.04: 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 dd changes in each of 10 random sequences. A run counts as a success when the consensus of θ\theta equals the planted motif. Over seeds 0 to 19, with the defaults:

GG (L,d)(L, d) 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 zz 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 FF.

Proof. Let Q(ϕ′∣ϕ)=∑k[zk(log⁡λ′+∑jlog⁡θj′(Xk,j))+(1−zk)(log⁡(1−λ′)+∑jlog⁡θ0′(Xk,j))]Q(\phi' \mid \phi) = \sum_k [z_k (\log \lambda' + \sum_j \log \theta'_j(X_{k,j})) + (1 - z_k)(\log (1 - \lambda') + \sum_j \log \theta'_0(X_{k,j}))] plus the prior term, where zz comes from the E step at ϕ\phi. For each kk, log⁡Pϕ′(Xk)=(the kth term of Q)−Hk\log P_{\phi'}(X_k) = (\text{the } k\text{th term of } Q) - H_k, with Hk=zklog⁡zk′+(1−zk)log⁡(1−zk′)H_k = z_k \log z'_k + (1 - z_k) \log (1 - z'_k) in terms of the posterior z′z' at ϕ′\phi'. By Gibbs' inequality, HkH_k is largest at z′=zz' = z, that is, at ϕ′=ϕ\phi' = \phi. So F(ϕ′)−F(ϕ)≥Q(ϕ′∣ϕ)−Q(ϕ∣ϕ)F(\phi') - F(\phi) \ge Q(\phi' \mid \phi) - Q(\phi \mid \phi). The M step maximizes QQ: each term separates into a function of λ′\lambda', maximized at ∑z/N\sum z / N, and for each column a sum ∑a(cj(a)+βμ(a))log⁡θj′(a)\sum_a (c_j(a) + \beta\mu(a)) \log \theta'_j(a) over the simplex, maximized at θj′(a)∝cj(a)+βμ(a)\theta'_j(a) \propto c_j(a) + \beta\mu(a), which is line L9. So FF does not drop. □\square

This is the theorem of Dempster, Laird and Rubin, with the prior added. It gives convergence of FF, since FF 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). zk>1/2z_k > 1/2 exactly when ∑jlog⁡(θj(Xk,j)/θ0(Xk,j))>log⁡((1−λ)/λ)\sum_j \log(\theta_j(X_{k,j}) / \theta_0(X_{k,j})) > \log((1 - \lambda)/\lambda).

Proof. Let rr be the left side. Line L7 gives zk=1/(1+e−(r−log⁡((1−λ)/λ)))z_k = 1/(1 + e^{-(r - \log((1-\lambda)/\lambda))}), and this is above 1/21/2 exactly when the exponent is negative. □\square

So the motif model is a position-specific scoring matrix of log odds, and the threshold for a site depends on λ\lambda. 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 QQ 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 X1,…,XNX_1, \ldots, X_N be windows of length LL over the letters A, C, G, T, let μ(a)>0\mu(a) > 0 and β>0\beta > 0. A parameter ϕ=(θ,θ0,λ)\phi = (\theta, \theta_0, \lambda) has θj\theta_j and θ0\theta_0 in the open simplex of four letters and 0<λ<10 < \lambda < 1. Write p1(x)=∏jθj(xj)p_1(x) = \prod_j \theta_j(x_j) and p0(x)=∏jθ0(xj)p_0(x) = \prod_j \theta_0(x_j), and

F(ϕ)=∑klog⁡(λp1(Xk)+(1−λ)p0(Xk))+β∑aμ(a)(∑jlog⁡θj(a)+log⁡θ0(a)).F(\phi) = \sum_k \log(\lambda p_1(X_k) + (1 - \lambda) p_0(X_k)) + \beta \sum_a \mu(a) \Big(\sum_j \log \theta_j(a) + \log \theta_0(a)\Big).

Lemma 1 (the E step). Line L7 sets zk=λp1(Xk)/(λp1(Xk)+(1−λ)p0(Xk))z_k = \lambda p_1(X_k) / (\lambda p_1(X_k) + (1 - \lambda) p_0(X_k)), the posterior probability that XkX_k comes from the motif component, by Bayes' theorem. The code computes rk=∑jlog⁡(θj(Xk,j)/θ0(Xk,j))−log⁡((1−λ)/λ)r_k = \sum_j \log(\theta_j(X_{k,j})/\theta_0(X_{k,j})) - \log((1 - \lambda)/\lambda) and returns 1/(1+e−rk)1/(1 + e^{-r_k}), which is the same number: divide the numerator and the denominator by λp1(Xk)\lambda p_1(X_k).

Corollary (the site rule). zk>1/2z_k > 1/2 exactly when rk>0r_k > 0, that is, when the log odds score of XkX_k is above log⁡((1−λ)/λ)\log((1 - \lambda)/\lambda), since 1/(1+e−r)1/(1 + e^{-r}) is increasing and equals 1/21/2 at r=0r = 0.

Lemma 2 (the M step maximizes Q). For weights zk∈[0,1]z_k \in [0, 1], let

Q(ϕ′)=∑k[zk(log⁡λ′+log⁡p1′(Xk))+(1−zk)(log⁡(1−λ′)+log⁡p0′(Xk))]+β∑aμ(a)(∑jlog⁡θj′(a)+log⁡θ0′(a)).Q(\phi') = \sum_k \Big[ z_k \big(\log \lambda' + \log p'_1(X_k)\big) + (1 - z_k)\big(\log (1 - \lambda') + \log p'_0(X_k)\big) \Big] + \beta \sum_a \mu(a) \Big(\sum_j \log \theta'_j(a) + \log \theta'_0(a)\Big).

Then lines L8 and L9 give the unique maximizer of QQ, apart from the clamp of λ\lambda.

Proof. QQ is a sum of separate parts. The part in λ′\lambda' is Slog⁡λ′+(N−S)log⁡(1−λ′)S \log \lambda' + (N - S) \log(1 - \lambda') with S=∑kzkS = \sum_k z_k; it is strictly concave and its derivative is 0 at λ′=S/N\lambda' = S/N. The part in θj′\theta'_j is ∑a(cj(a)+βμ(a))log⁡θj′(a)\sum_a (c_j(a) + \beta\mu(a)) \log \theta'_j(a) with cj(a)=∑kzk[Xk,j=a]c_j(a) = \sum_k z_k [X_{k,j} = a]. For positive weights waw_a, the function ∑awalog⁡pa\sum_a w_a \log p_a on the simplex has its unique maximum at pa=wa/∑bwbp_a = w_a / \sum_b w_b: by Gibbs' inequality, ∑awalog⁡(pa/p^a)=(∑bwb)∑ap^alog⁡(pa/p^a)≤0\sum_a w_a \log (p_a / \hat p_a) = (\sum_b w_b) \sum_a \hat p_a \log(p_a/\hat p_a) \le 0 with p^a=wa/∑bwb\hat p_a = w_a/\sum_b w_b, with equality only at p=p^p = \hat p. Here ∑a(cj(a)+βμ(a))=∑acj(a)+β\sum_a (c_j(a) + \beta\mu(a)) = \sum_a c_j(a) + \beta, since ∑aμ(a)=1\sum_a \mu(a) = 1, so the maximum is line L9. The part in θ0′\theta'_0 is the same with c0(a)=∑k(1−zk)#{j:Xk,j=a}c_0(a) = \sum_k (1 - z_k) \#\{j : X_{k,j} = a\}. □\square

Theorem (ascent). Let ϕ\phi be the parameters before an iteration, zz the weights of the E step at ϕ\phi, and ϕ′\phi' the result of the M step. Then F(ϕ′)≥F(ϕ)F(\phi') \ge F(\phi).

Proof. Let zk′z'_k be the E step weight at ϕ′\phi'. For each kk,

log⁡Pϕ′(Xk)=zklog⁡λ′p1′(Xk)zk′+(1−zk)log⁡(1−λ′)p0′(Xk)1−zk′,\log P_{\phi'}(X_k) = z_k \log \frac{\lambda' p'_1(X_k)}{z'_k} + (1 - z_k) \log \frac{(1 - \lambda') p'_0(X_k)}{1 - z'_k},

since λ′p1′(Xk)/zk′=(1−λ′)p0′(Xk)/(1−zk′)=Pϕ′(Xk)\lambda' p'_1(X_k) / z'_k = (1 - \lambda') p'_0(X_k)/(1 - z'_k) = P_{\phi'}(X_k). So F(ϕ′)=Q(ϕ′)−∑khk(zk′)F(\phi') = Q(\phi') - \sum_k h_k(z'_k) with hk(y)=zklog⁡y+(1−zk)log⁡(1−y)h_k(y) = z_k \log y + (1 - z_k) \log (1 - y), and in the same way F(ϕ)=Q(ϕ)−∑khk(zk)F(\phi) = Q(\phi) - \sum_k h_k(z_k). By Gibbs' inequality, hk(y)≤hk(zk)h_k(y) \le h_k(z_k) for all yy. So F(ϕ′)−F(ϕ)≥Q(ϕ′)−Q(ϕ)≥0F(\phi') - F(\phi) \ge Q(\phi') - Q(\phi) \ge 0, the last step by Lemma 2. □\square

Corollary (convergence of the objective). FF is bounded above: each log⁡P(Xk)≤0\log P(X_k) \le 0, and each prior term is at most 0. So the values of FF along the run increase to a limit. The parameters converge to a stationary point of FF 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 λ\lambda in [10−12,1−10−12][10^{-12}, 1 - 10^{-12}]. If the clamp is active, the λ\lambda part of QQ 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 O(NL)O(NL) time and O(N+L)O(N + L) 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 NN products of LL terms, and the M step adds each window's letters with its weight, so an iteration takes O(NL)O(NL) time. Bailey and Elkan give the same linear cost per iteration. The start phase does one iteration for each of at most WW starts, O(WNL)=O(nW2L)O(W N L) = O(n W^2 L), and II main iterations add O(INL)O(I N L).
  • Space. The weights take NN numbers and the models 4L+44L + 4 numbers, so O(N+L)O(N + L) besides the input.
  • In practice. On the BA2F sample the main run takes 35 iterations. On the planted (8,1)(8, 1) runs with G=100G = 100 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 FF, 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 λ\lambda. The start value of λ\lambda 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 NN windows as independent, but they overlap. A strong site makes its shifted windows look like sites too, and λ\lambda 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 β>0\beta > 0.
  • 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 LL probabilities underflows for long motifs. Work with sums of logarithms.
  • Reading λ\lambda as the number of sites. λN\lambda N 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.

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)
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

  1. 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
  2. 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
  3. 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.

LadderLevelWhat the next level needs
Human proofH1 sketch
  • a full proof of time.per_iteration
  • 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