n <- 300 # number of DNA sequences
l <- 100 # number of nucleotides for each sequence
motif_len <- 10 # the length of the true motif
set.seed(5)
motif <- sample(1:4, motif_len, TRUE)
motif [1] 2 3 1 3 3 1 1 1 2 3
A motif is the sequence of nucleotides that a DNA binding protein, such as a transcription factor, prefers to bind. As we discussed in class, “binding” here means that amino acid residues of the protein make favorable contacts with nucleotides in the major groove of the DNA double helix, and some sequences of letters make for better contacts than others.
Transcription factor motifs are usually 6-20 bp long. The binding isn’t perfectly specific: a protein will bind to a family of similar sequences, some more strongly than others. So instead of a single sequence, we describe a motif with a position probability matrix, which gives the probability of each nucleotide at each position of the motif. You will also see the position weight matrix (PWM), which is the log of these probabilities divided by the background frequency of each nucleotide. A positive value in the PWM means that nucleotide is more common at that position of the motif than in the genome overall.
Transcription factors find their target genes by binding to instances of their motif in cis-regulatory elements (CREs), such as promoters and enhancers. A CRE typically has binding sites for a number of transcription factors, which together determine whether and when the nearby gene is transcribed. A short motif will also match by chance at a huge number of places in the genome, and most of these are never bound, for example because they are in closed chromatin. This is why we usually look for motifs in regions where there is experimental evidence of binding, such as ChIP-seq peaks, rather than scanning the whole genome.
For most transcription factors, we can’t yet predict the motif from the protein sequence or structure alone. AlphaFold 3 and similar tools can model protein-DNA complexes, but getting an accurate motif out of these is still an open problem. So we learn motifs from data.
The setup is: we have a set of DNA sequences (ChIP-seq peaks, or the promoters of genes that respond to some stimulus), and we want to find a sequence pattern that shows up in many of them. What makes this hard:
The model below deals with the first three, and ignores the rest to keep things simple. EM is a good fit here, with the windows that contain the motif as the latent variable. Keep in mind that what EM finds are candidate binding sites, patterns that are over-represented relative to the background, and these still need to be checked against other evidence.
The code below is a simplified simulation and model, following the setup of the MEME method, which proposed EM for motif finding:
MEME: discovering and analyzing DNA and protein sequence motifs - link
Before we get started, note that EM is not the only way to find these motifs. Another, seemingly more direct approach, would be to tabulate all the k-mers for a value of k that is large, but less than the length of the motif we are looking for. If we look across sequences which should occasionally contain the motif, we will likely find sets of k-mers that occur more than we would expect in “background” DNA sequences.
MEME breaks every sequence into overlapping windows the same width as the motif, and asks of each window: is this a motif or is this background? This is a mixture of two components, just like the mixture of distributions from before:
The hidden variable \(Z_i\) is 1 if window i is a motif and 0 if it is background. This sets up a problem that can be tackled with EM: if we knew the motif, we could find which windows are motifs, and if we knew which windows are motifs, we could easily determine the motif. We start with neither.
The background component is essential. Without it, the model has no way to say “this window doesn’t look like the motif”, and it has to explain every window as a motif. It also lets us account for the fact that the four nucleotides are not in equal abundance in genomes: a window full of common nucleotides should not look like a motif just because those nucleotides are common.
The over-simplifications we will make here, which result in an unrealistic simulation, but are useful for pedagogical purposes:
I begin by defining some parameters and simulating our motif that we want to find. Here I use numbers 1-4 to represent nucleotides A,C,G,T.
n <- 300 # number of DNA sequences
l <- 100 # number of nucleotides for each sequence
motif_len <- 10 # the length of the true motif
set.seed(5)
motif <- sample(1:4, motif_len, TRUE)
motif [1] 2 3 1 3 3 1 1 1 2 3
Now we will embed the motif into some DNA sequences, which here are rows of a matrix x. The vector z keeps track of the start position of the motif in each sequence.
x <- matrix(sample(1:4, n * l, TRUE),nrow=n)
z <- sample(l - motif_len + 1, n, TRUE)
for (i in seq_len(n)) {
x[i, z[i] + 0:(motif_len-1)] <- motif
}
head(z)[1] 39 82 34 86 31 63
x[1,z[1] + 0:(motif_len-1)] [1] 2 3 1 3 3 1 1 1 2 3
The sequence motifs of a DNA binding protein vary across the genome: there are always some, and often many, positions within a motif which allow for a variety of nucleotides. To mimic this, we replace 20% of the nucleotides with a random nucleotide. As the random nucleotide is the same as the original one quarter of the time, about 15% of positions change.
noise <- 0.2
set.seed(1)
mutate_pos <- matrix(runif(n * l) < noise, nrow=n)
x[mutate_pos] <- sample(1:4, sum(mutate_pos), TRUE)
x[1,z[1] + 0:(motif_len-1)] [1] 2 3 1 3 3 1 1 1 2 3
motif [1] 2 3 1 3 3 1 1 1 2 3
Now we redefine the data as MEME does, with one row per window. Each sequence contributes n_win windows, so the window starting at position p of sequence i is in row (i-1) * n_win + p.
w <- motif_len # width of the windows and of theta
n_win <- l - w + 1 # number of windows per sequence
win <- matrix(nrow=n * n_win, ncol=w)
for (i in seq_len(n)) {
for (p in seq_len(n_win)) {
win[(i-1) * n_win + p,] <- x[i, p + 0:(w-1)]
}
}
dim(win)[1] 27300 10
# rows of `win` that hold the true motifs
motif_idx <- z + 0:(n-1) * n_winWe can look at the windows holding the true motifs to see how much they vary (A,C,G,T in green, blue, orange, red):
cols <- c("green3","blue","orange","red")
pheatmap::pheatmap(win[motif_idx,], cluster_rows=FALSE,
cluster_cols=FALSE, show_rownames=FALSE,
color=cols, breaks=0:4 + .5, legend=FALSE)The likelihood of a window under the motif component is the product, over positions, of the probability in \(\theta\) of the nucleotide we see at that position. Under the background component it is the product of the background probabilities of its nucleotides. We estimate \(\theta_{bg}\) once, from the overall frequency of each nucleotide, and hold it fixed.
lik_motif <- function(snip, theta) {
prod(sapply(1:4, function(k) prod(theta[k, snip == k])))
}
lik_bg <- function(snip, theta_bg) {
prod(theta_bg[snip])
}
theta_bg <- tabulate(x, 4) / length(x)
theta_bg[1] 0.2612667 0.2441000 0.2658333 0.2288000
We start with a random guess \(\theta^0\), where each column sums to 1, and with \(\lambda^0\) equal to one motif per sequence.
random_theta <- function(w) {
theta <- matrix(runif(w*4), ncol=w)
sweep(theta, 2, colSums(theta), "/")
}
set.seed(3)
theta <- random_theta(w)
round(theta, 2) [,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9] [,10]
[1,] 0.10 0.37 0.26 0.19 0.06 0.49 0.09 0.27 0.14 0.47
[2,] 0.48 0.37 0.28 0.20 0.35 0.03 0.31 0.37 0.37 0.11
[3,] 0.23 0.08 0.23 0.31 0.45 0.28 0.24 0.18 0.21 0.31
[4,] 0.19 0.18 0.23 0.30 0.14 0.20 0.36 0.18 0.28 0.11
lambda <- 1/n_winIn the E-step, the conditional probability that window i is a motif is the familiar ratio from mixture models:
\[ P(Z_i = 1 | X_i, \theta^t, \lambda^t) = \frac{\lambda^t \, P(X_i | \theta^t)}{\lambda^t \, P(X_i | \theta^t) + (1 - \lambda^t) \, P(X_i | \theta_{bg})} \]
Let’s calculate this for the first window of the first sequence.
snip <- win[1,]
snip [1] 3 3 1 1 4 4 2 4 2 3
f_motif <- lambda * lik_motif(snip, theta)
f_bg <- (1 - lambda) * lik_bg(snip, theta_bg)
f_motif / (f_motif + f_bg)[1] 0.001911944
To compute the motif likelihood for all windows at once, it is much faster to loop over the w columns than over the many rows of win: for column j, theta[cbind(win[,j], j)] picks out the probability of the nucleotide observed at position j in every window. This gives the same answer as applying lik_motif to each row:
lik_motif_all <- function(win, theta) {
lik <- rep(1, nrow(win))
for (j in seq_len(ncol(win))) {
lik <- lik * theta[cbind(win[,j], j)]
}
lik
}
all.equal(lik_motif_all(win, theta),
apply(win, 1, lik_motif, theta=theta))[1] TRUE
As the background likelihood of each window doesn’t change, we only need to compute it once. We then compute the conditional probability for all windows:
lik_bg_win <- apply(win, 1, lik_bg, theta_bg=theta_bg)
f_motif <- lambda * lik_motif_all(win, theta)
f_bg <- (1 - lambda) * lik_bg_win
post_motif <- f_motif / (f_motif + f_bg)
summary(post_motif) Min. 1st Qu. Median Mean 3rd Qu. Max.
2.720e-06 7.569e-04 2.859e-03 1.008e-02 9.713e-03 4.426e-01
We can’t maximize the log likelihood of the observed windows directly, for the same reason as in the mixture of normals: each window’s likelihood is a sum over the two components, \(\lambda P(X_i | \theta) + (1 - \lambda) P(X_i | \theta_{bg})\), so the log can’t be distributed over the positions of \(\theta\) (the log of a sum is not the sum of logs). If we knew \(Z_i\), only one of the two terms would remain and the log would distribute.
In the M-step, we maximize the expected log likelihood, where the expectation is over the conditional distribution of Z given X and the current parameters. The update for \(\lambda\) is the average of the conditional probabilities. The update for each column of \(\theta\) is a weighted frequency of the nucleotides at that position, where each window is weighted by its probability of being a motif. Note that if we knew exactly which windows were motifs (post_motif all 0 or 1), this would simply count the nucleotides at each position across the motifs.
lambda <- mean(post_motif)
counts <- t(sapply(1:4, function(k) colSums(post_motif * (win == k))))
theta <- sweep(counts, 2, colSums(counts), "/")
round(theta, 2) [,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9] [,10]
[1,] 0.11 0.36 0.28 0.19 0.06 0.47 0.11 0.27 0.14 0.45
[2,] 0.45 0.36 0.27 0.21 0.35 0.03 0.29 0.35 0.37 0.11
[3,] 0.22 0.09 0.22 0.30 0.44 0.28 0.24 0.20 0.21 0.32
[4,] 0.21 0.18 0.23 0.30 0.15 0.21 0.36 0.18 0.28 0.12
Now we put these two pieces together within a loop. We also keep track of the log likelihood at each iteration, which EM should never decrease, and the estimate of \(\theta\) at each iteration, so we can plot it.
meme_em <- function(theta, lambda, niter) {
loglik <- numeric(niter)
theta_hist <- list(theta)
for (t in seq_len(niter)) {
# E-step: probability that each window is a motif
f_motif <- lambda * lik_motif_all(win, theta)
f_bg <- (1 - lambda) * lik_bg_win
loglik[t] <- sum(log(f_motif + f_bg)) # log lik at theta^(t-1)
post_motif <- f_motif / (f_motif + f_bg)
# M-step: update the mixing proportion and the motif matrix
lambda <- mean(post_motif)
counts <- t(sapply(1:4, function(k) colSums(post_motif * (win == k))))
theta <- sweep(counts, 2, colSums(counts), "/")
theta_hist[[t + 1]] <- theta
}
list(theta=theta, lambda=lambda, post_motif=post_motif,
loglik=loglik, theta_hist=theta_hist)
}EM finds a local maximum of the likelihood, and which one depends on where we start. So, like MEME, we try a number of starting points and keep the best.
n_starts <- 20
niter <- 60
fits <- lapply(seq_len(n_starts), function(s) {
set.seed(s)
meme_em(random_theta(w), lambda=1/n_win, niter=niter)
})The log likelihood increases over iterations for every start (one line per start), but the starts end up at different values. We plot the log likelihood relative to the highest value seen across all starts, so the top of the plot is 0 (a likelihood ratio of 1 with the best start):
ll <- sapply(fits, `[[`, "loglik")
matplot(ll[-1,] - max(ll), type="l", lty=1, col=1:n_starts,
xlab="iteration", ylab="log likelihood relative to best")Some starts converge to a shifted version of the motif. For each start, we can find the window in each sequence with the highest probability of being a motif, and compare it to the true start position z. The most common offset between the chosen window and z tells us how far the motif was shifted. We then count how many of the true motif locations were recovered, allowing for that shift.
summarize_fit <- function(fit) {
post_mat <- matrix(fit$post_motif, nrow=n, byrow=TRUE)
offset <- apply(post_mat, 1, which.max) - z
shift <- as.numeric(names(which.max(table(offset))))
c(loglik=fit$loglik[niter],
shift=shift,
recovered=sum(offset == shift))
}
res <- t(sapply(fits, summarize_fit))
res loglik shift recovered
[1,] -377679.1 -4 201
[2,] -377223.8 -1 274
[3,] -377010.4 0 286
[4,] -377556.8 -3 231
[5,] -377420.5 2 261
[6,] -377010.4 0 286
[7,] -377223.8 -1 274
[8,] -377223.8 -1 274
[9,] -377678.1 4 213
[10,] -377010.4 0 286
[11,] -377562.8 3 235
[12,] -377562.8 3 235
[13,] -377678.1 4 213
[14,] -377010.4 0 286
[15,] -377420.5 2 261
[16,] -377556.8 -3 231
[17,] -377010.4 0 286
[18,] -377421.9 -2 257
[19,] -377678.1 4 213
[20,] -377556.7 -3 231
Some starts end up at the same values, so we jitter the points slightly, and label each size of shift (left or right) once:
set.seed(1)
jit_x <- jitter(res[,"recovered"], amount=2)
jit_y <- jitter(res[,"loglik"] - max(res[,"loglik"]), amount=10)
plot(jit_x, jit_y, xlim=range(jit_x) + c(-5, 15),
xlab="true motif locations recovered (allowing for shift)",
ylab="final log likelihood relative to best")
abs_shift <- abs(res[,"shift"])
# one label per size of shift, to the right of its group of points
lab_x <- tapply(jit_x, abs_shift, max)
lab_y <- tapply(jit_y, abs_shift, mean)
text(lab_x, lab_y, labels=paste("shift", names(lab_x)), pos=4, cex=.8)The starts with no shift have the highest log likelihood and recover the most motif locations. The larger the shift, the lower the log likelihood, and the fewer of the motif locations are recovered, even after accounting for the shift.
To see this, we define a function to draw an estimate of \(\theta\) as a row of squares, colored by the most likely nucleotide at each position, and more transparent when that nucleotide’s probability is closer to 1/4. The argument shift moves the squares left or right.
drawTheta <- function(theta, y, shift=0) {
theta_max <- apply(theta, 2, which.max)
theta_max_p <- apply(theta, 2, max)
cols_alpha <- sapply(seq_len(ncol(theta)), function(i) {
adjustcolor(cols[theta_max[i]],(theta_max_p[i] - .25)/.75)
})
points(seq_len(ncol(theta)) + shift, rep(y,ncol(theta)),
col=cols_alpha, pch=15, cex=2)
}Drawing the final \(\theta\) from each start, moved by its shift so that it lines up with the true motif at the bottom, with starts ordered by their final log likelihood (highest at the top):
library(rafalib)
ord <- order(res[,"loglik"])
nullplot(min(res[,"shift"]), w + max(res[,"shift"]) + 1, -1, n_starts,
xlab="position relative to true motif",
ylab="starts, ordered by log likelihood")
points(seq_len(w), rep(-1,w), col=cols[motif], pch=15, cex=2)
for (k in seq_len(n_starts)) {
drawTheta(fits[[ord[k]]]$theta, k, shift=res[ord[k],"shift"])
}
abline(v=c(.5, w + .5), lty=2)All of the starts found the same motif. But a \(\theta\) shifted by \(s\) positions only covers \(10 - s\) positions of the motif (inside the dashed lines). Its other \(s\) columns line up with the random sequence next to the motif, so they are close to the background frequencies (the faded squares), and explain the data no better than the background component does. Each position of the motif that falls outside of \(\theta\) is information we are not using, and so the likelihood is lower.
Why doesn’t EM fix the shift? A shifted \(\theta\) is a local maximum that is hard to escape: moving it one position over would mean passing through worse values of the likelihood. MEME deals with this by trying many starting points (derived from substrings of the data rather than random values) and by explicitly trying shifted versions of the motif. Here, we simply keep the start with the highest log likelihood.
best_start <- which.max(ll[niter,])
best <- fits[[best_start]]
round(best$theta, 2) [,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9] [,10]
[1,] 0.05 0.02 0.86 0.06 0.02 0.84 0.86 0.85 0.04 0.04
[2,] 0.85 0.05 0.04 0.02 0.06 0.07 0.03 0.03 0.87 0.03
[3,] 0.03 0.89 0.05 0.85 0.86 0.05 0.06 0.07 0.04 0.89
[4,] 0.06 0.04 0.06 0.07 0.06 0.05 0.06 0.06 0.05 0.05
motif [1] 2 3 1 3 3 1 1 1 2 3
We can follow the estimates of \(\theta\) over the iterations for this start, for the first 20 iterations. The random initialization has no clear motif, and for the first few iterations not much happens. Then a few positions that happen to agree with the motif start to pull the conditional probabilities of the true motif windows upward, and the rest of the motif fills in over a few iterations.
n_show <- 20 # the best start converges well before this
nullplot(0, w + 1, -1, n_show,
xlab="position in motif", ylab="iteration")
points(seq_len(w), rep(-1,w), col=cols[motif], pch=15, cex=2)
for (t in 0:n_show) {
drawTheta(best$theta_hist[[t + 1]], t)
}The estimate of \(\lambda\), converted to motifs per sequence, should be close to 1:
best$lambda * n_win[1] 0.982961
A few remaining differences from MEME: MEME uses pseudocounts (a Dirichlet prior) so that no entry of \(\theta\) becomes exactly 0, it searches both strands, it allows for sequences without the motif, it searches over the width of the motif, and it accounts for the fact that overlapping windows can’t both be motifs. Here we treated the windows as independent, which they are not.
In the M-step we said that we maximize the expected log likelihood, without writing it down. Here we show that the weighted frequencies used above are exactly the maximizer. Let \(x_{ij}\) be the nucleotide at position \(j\) of window \(i\), and let \(N\) be the number of windows. The log likelihood of the complete data, if we knew which windows were motifs, is:
\[ \log P(X, Z | \theta, \lambda) = \sum_{i=1}^N Z_i \left[\log \lambda + \sum_{j=1}^w \sum_{k=1}^4 1(x_{ij}=k) \log \theta_{kj}\right] + (1 - Z_i) \left[\log(1-\lambda) + \log P(X_i | \theta_{bg})\right] \]
This is linear in the \(Z_i\). So the expectation over the conditional distribution of \(Z\) given \(X\) and the current parameters just replaces each \(Z_i\) with its conditional probability \(r_i = P(Z_i = 1 | X_i, \theta^t, \lambda^t)\), which is post_motif in the code:
\[ Q(\theta, \lambda | \theta^t, \lambda^t) = \sum_{i=1}^N r_i \left[\log \lambda + \sum_{j=1}^w \sum_{k=1}^4 1(x_{ij}=k) \log \theta_{kj}\right] + (1 - r_i) \left[\log(1-\lambda) + \log P(X_i | \theta_{bg})\right] \]
No integration over \(Z\) is needed in practice, because of this linearity. The terms involving \(\theta_{bg}\) are held fixed, so they do not affect the maximization. The remaining terms separate into a part with only \(\lambda\) and a part with only \(\theta\).
For \(\lambda\), we maximize \(\sum_i r_i \log \lambda + (1 - r_i) \log(1-\lambda)\). Setting the derivative to zero:
\[ \frac{\sum_i r_i}{\lambda} - \frac{\sum_i (1 - r_i)}{1 - \lambda} = 0 \quad \Rightarrow \quad \lambda = \frac{1}{N} \sum_i r_i \]
which is mean(post_motif).
For \(\theta\), define the weighted counts \(c_{kj} = \sum_i r_i \, 1(x_{ij}=k)\). We maximize \(\sum_j \sum_k c_{kj} \log \theta_{kj}\) subject to each column summing to 1. With a Lagrange multiplier \(\mu_j\) for each column, we set the derivative with respect to \(\theta_{kj}\) to zero:
\[ \frac{c_{kj}}{\theta_{kj}} - \mu_j = 0 \quad \Rightarrow \quad \theta_{kj} = \frac{c_{kj}}{\mu_j} \]
The constraint \(\sum_k \theta_{kj} = 1\) gives \(\mu_j = \sum_k c_{kj}\), so
\[ \theta_{kj} = \frac{c_{kj}}{\sum_{k'} c_{k'j}} \]
This is the weighted frequency of nucleotide \(k\) at position \(j\), the counts matrix divided by its column sums in the code. When every \(r_i\) is 0 or 1, it reduces to the ordinary maximum likelihood estimate: counting the nucleotides at each position across the windows that are motifs.