Algorithmadvanced
Random projection motif finding
Also called PROJECTION algorithm.
Hash all windows by k random positions into buckets, refine heavily filled buckets with EM, and repeat with new projections.
- Solves
- Planted motif problem
- Time
- O(m (n W k + B I n W L)) worstO(n W k) hashing_per_trial
- Space
- O(n W + L) extra
- Where
- B = the number of buckets refined in a trial; G = the length of each sequence; I = the number of EM iterations per bucket; L = the motif length; W = the number of windows per sequence, G - L + 1; k = the number of projected positions; m = the number of trials; n = the number of sequences
- Model
- Word RAM
- Properties
- randomizednot exactofflineiterative
- Evidence
- Proof sketchCode in 1 languages
- Origin
- Jeremy Buhler, Martin Tompa, 2001
PROJECTION, of Buhler and Tompa (2001, 2002), finds a planted motif by hashing. It picks of the positions of a window at random and puts every window of every sequence into the bucket given by its letters at these positions. A planted copy of the motif lands in the bucket of the motif whenever none of its changed positions is picked, so the bucket of the motif tends to fill up, while random buckets stay small. Each bucket that holds windows from enough sequences is a start for EM, which refines it into a motif model. Many trials with new positions make it very likely that some trial puts enough copies into one bucket.
In plain words
Two copies of the hidden word differ in a few places. If you look at only some of the places, chosen at random, you will often miss all the differences, and then the two copies look the same. So pick a few places at random and sort all the short pieces of all sequences by their letters at those places. Copies of the hidden word that agree at the chosen places end up in the same pile.
A pile with pieces from many sequences is a good lead. Use the pieces in it to make a first guess of the word, and improve the guess with EM over all the data. One choice of places may fail, so repeat with new places many times and keep the best guess.
The problem
Input. DNA sequences , each of length , a motif length , a projection size , a bucket threshold , a number of trials and a seed. Each sequence has windows. Positions are 1-based on this page and 0-based in the code.
Output. A motif model (letter probabilities for each column), its consensus and its most likely site in each sequence. The target is the planted motif problem: find the motif when each sequence holds a copy of with changes.
The algorithm
For a set of positions, the projection of a window is , the letters of at the positions in . This is the bit sampling family of locality sensitive hashing for the Hamming distance: windows that are close agree at more positions, so they land in the same bucket more often.
PROJECTION(s[1 .. n], L, k, s_min, m, rng)- 1
best ← none - 2
for trial ← 1 to m do - 3
I ← k distinct positions drawn uniformly from 1 .. L - 4
put every window x of every sequence into the bucket h_I(x) - 5
for each bucket B that holds windows of at least s_min sequences do - 6
θ ← the letter counts of the windows of B, plus prior counts βμ(a), as probabilities - 7
refine θ by EM with one site per sequence - 8
if the score of θ is above the score of best then best ← θ - 9
return best, its consensus, and the most likely site in each sequence
Line L3 is the only random step: the code draws rng.sample(range(L), k) once per trial from random.Random(seed). Line L7 runs EM for the model with one occurrence per sequence (OOPS) and a fixed background , the letter frequencies of the input. The E step gives each window of the weight , normalized within the sequence; the M step sets . The score of line L8 is the log likelihood ratio of the OOPS model, . The code uses and 10 EM iterations per bucket, and it counts the sequences of a bucket, not its windows, against ; these are the choices of this code.
Example
One copy. Let , and . A copy of the motif with 4 changed positions lands in the motif's bucket when the 7 picked positions avoid the 4 changed ones:
One trial. With sequences, the number of copies in the motif's bucket is when the changed positions are random, so a trial puts at least copies there with probability .
The number of trials. To reach a good bucket with probability at least , PROJECTION needs trials with , so .
Random buckets. For , there are windows and buckets, so a random bucket holds windows on average. A bucket of random windows can still reach the threshold, which is why each candidate is checked by its EM score and not taken as it is.
Measured runs. The test generator plants a motif with exactly changes in each sequence. With , and , the theory gives , and trials for 0.95. Over seeds 0 to 19, the consensus of the result equals the planted motif in 15 of 20 runs, and the sites equal the planted starts in 11; on average 33 buckets per run reach the threshold. These are measurements of this code on these seeds.
A fixed input. The formula for averages over the random changes as well as over the projections. On a fixed input the changes are fixed, and the hits of the copies are no longer independent, because they share one projection. For five inputs with from the test generator (seeds 1 to 5), a count over all 6435 sets of 7 positions gives the chance of at least 4 copies in the motif's bucket as 1.48, 2.00, 1.85, 1.20 and 3.25 percent, against 1.73 percent from the formula. The mean rate per copy is exactly on each input, since every copy has exactly 4 changes.
Correctness
PROJECTION is a heuristic with a probabilistic guarantee for its first stage.
Theorem (the hit probability). If the changed positions of a copy are a uniform random -set and is a uniform random -set, independent of each other, then the copy and the motif have the same projection with probability at least , with equality when every change makes the letter differ from the motif.
Proof. The projections agree when every picked position has the same letter in the copy and the motif, which holds when avoids the changed positions. For a fixed -set, of the choices of avoid it. In the generator every change makes the letter differ, so agreement holds exactly when avoids the set.
Theorem (enough trials). If the copies of the sequences have independent random changes, a trial puts at least copies into the motif's bucket with probability , and independent trials do so at least once with probability .
Proof. For a fixed , each copy hits independently with probability by the first theorem, so the count is for every . The trials use independent projections and are independent.
A good bucket is a good start for EM, not a proof that EM finds the motif; EM can still move to another local optimum, and line L8 can prefer a random bucket with a better score. The OOPS EM step does not lower its score plus the log prior term , by the general ascent property of EM. The tests check by enumeration of all position sets for and by simulation within 4 standard deviations, check the formula for , check that EM does not lower the score with and without the prior term, check the draw order, and measure the planted success rate. The proofs are in proofs/correctness.md.
Proof: The hit probability, the trial count and the EM ascent of PROJECTIONfull
Let be a motif of length and let each sequence hold a copy of that differs from at exactly the positions of a set with . A trial draws a set of positions, uniform among the sets (line L3), and the bucket of a window is (line L4).
Lemma 1 (when a copy hits). if and only if .
Proof. The projections agree when and have the same letter at every . They have the same letter exactly at the positions outside .
Theorem 1 (the hit probability). If is a uniform random -set, independent of , then . The same holds for a fixed and a uniform .
Proof. For a fixed , the sets that avoid it are the -subsets of the other positions, so by Lemma 1 the probability is . This does not depend on , so averaging over a random gives the same value.
When a change may keep the letter (a copy with at most differences), Lemma 1 gives only "if", and is a lower bound.
Theorem 2 (one trial). If are independent uniform -sets, independent of , the number of copies in the bucket is , and a trial gives with probability .
Proof. Condition on . The events are independent, since the are, and each has probability for every fixed , by the count of Theorem 1 with the roles of and exchanged: of the sets , avoid , and , since both equal . So given , is , and the same holds without the condition.
For a fixed input, the are fixed, and the events share the one random , so they are not independent in general. Then can differ from , while still holds by Theorem 1 and linearity.
Theorem 3 (the number of trials). With trials that use independent projections, the chance that at least one trial gives is . The least with , for and , is .
Proof. Under the model of Theorem 2, the trials are independent and each fails with probability . The inequality is the same as , since .
The function trials_needed starts from this value and corrects it by one step up or down against the floating-point test of the inequality, so it returns the least for which the computed inequality holds.
Lemma 2 (the threshold is checked on sequences). Line L5 refines a bucket exactly when its windows come from at least different sequences. If a trial gives , the motif's bucket is refined in that trial.
Proof. The code counts the distinct sequence indices of the members. The copies lie in different sequences.
Lemma 3 (EM does not lower the score). Let and let be the result of one E step and one M step of line L7 with prior counts . Then .
Proof. Up to a constant that does not depend on , is the log likelihood of the model in which each sequence has one site at a uniform position, the site letters follow and the other letters follow . The E step computes the posterior of the site position. The M step maximizes over the columns, and for column the maximum is at , the rule of the code, with the sum since . By the ascent property of EM for a posterior with this Dirichlet prior (Dempster, Laird and Rubin 1977), the penalized log likelihood does not decrease.
The code records without the prior term. The lemma does not promise that this value never falls, so the tests check both: the penalized value of the lemma, step by step from random starts, and the recorded value, which also did not fall on the test inputs. Both checks use a tolerance of .
What is not proved. A good bucket gives a start near the motif, but EM may move to another fixed point, and line L8 may prefer a model from a random bucket with a higher score. So the overall success rate is measured, not proved.
Cost. Line L4 computes keys of letters, . Each refined bucket costs for line L6 and for EM iterations of line L7. So a trial with refined buckets costs , and trials times that. The buckets take space.
Complexity
- Hashing. A trial computes keys of letters, time, and stores them in space.
- Refinement. An EM iteration looks at all windows of letters, . With buckets refined per trial and iterations each, a trial costs , and trials .
- The choice of . A larger makes random buckets smaller, so drops, but it also lowers , so grows. A good keeps the mean size of a random bucket, , below 1 while stays below .
- Space. The buckets take and the model . There is no graph of close pairs, so the memory does not grow with the number of such pairs, as it does in WINNOWER.
Properties
- Randomized. The result depends on the seed. The first stage has the guarantee of the trials theorem; the second does not.
- Locality sensitive hashing. The projection is a hash that sends close windows to the same bucket with a probability that falls with their distance. It is a random projection onto coordinates.
- Independent trials. The trials do not depend on each other, so they can run in parallel.
- Uses EM for the details. The hashing only finds starts. The motif model comes from EM, as in MEME.
Variants and improvements
- Other refinement. Replace EM by a Gibbs motif sampler run or by a local search on the motif string.
- Several motifs or no planted model. Use the same buckets for real data, with a threshold set from the expected size of random buckets.
- Gapped projections. Choose the positions so that they cover the motif evenly, or use structured sets of positions in place of random ones, to raise the hit rate for the same .
- Exact methods. For small , exact algorithms for the planted motif problem enumerate candidate strings with pruning; PROJECTION scales to larger .
When to use it
Use PROJECTION for planted motif problems with subtle motifs, such as or harder, where single windows are poor starts for EM. Work out , and for your before the run, and pick so that random buckets are small. For short motifs with few changes, the median string search is exact and cheap. When the motif is a profile and not a string with a fixed number of changes, run MEME or a Gibbs sampler directly.
Pitfalls
- A that is too large. If , a copy with changes never hits the motif's bucket, and .
- A that is too small. Random buckets fill up, and the refinement runs on many useless buckets.
- Trusting the formula on a fixed input. The trials theorem averages over the planting. On a fixed input the rate can be lower, as the example shows (1.20 percent in place of 1.73); add a margin to .
- Counting windows, not sequences. A bucket with several overlapping windows of one sequence is weak evidence. This code counts sequences.
- Reading the bucket as the answer. The bucket is a start. Report the refined model and its sites, and check them.
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)
random_projection_motif_finding.py 167 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/random-projection-motif-finding/. The authors are listed in prov/24V46J.jsonl.
"""PROJECTION of Buhler and Tompa (2002): hash every window by k random
positions, refine each bucket that holds windows of at least s sequences with
EM under the one occurrence per sequence (OOPS) model, and keep the best
refined model. The planted-model formulas for the number of trials are here
as well.
Positions are 0-based in this code; the page numbers them from 1.
"""
import math
import random
from fractions import Fraction
from math import comb
from typing import Dict, List, NamedTuple, Sequence, Tuple
from bioseq import DNA, kmers
_INDEX = {a: k for k, a in enumerate(DNA)}
class ProjectionResult(NamedTuple):
"""The best refined model: theta[j][a], its consensus, its 0-based site in
each sequence and its OOPS log likelihood ratio; also the number of buckets
refined and the projections drawn (0-based positions, sorted)."""
theta: Tuple[Tuple[float, ...], ...]
consensus: str
sites: Tuple[int, ...]
score: float
buckets_refined: int
projections: Tuple[Tuple[int, ...], ...]
def hit_probability(L: int, d: int, k: int) -> Fraction:
"""P(a planted copy with exactly d changes at uniform positions hashes with the motif) = C(L-d, k) / C(L, k)."""
if not 0 <= d <= L or not 0 <= k <= L:
raise ValueError("need 0 <= d <= L and 0 <= k <= L")
return Fraction(comb(L - d, k), comb(L, k))
def binomial_tail(n: int, p, s: int):
"""P(Bin(n, p) >= s), exact when p is a Fraction."""
return sum(comb(n, i) * p ** i * (1 - p) ** (n - i) for i in range(s, n + 1))
def trials_needed(n: int, L: int, d: int, k: int, s: int, q: float) -> int:
"""The least m with 1 - (1 - P)^m >= q, where P = P(Bin(n, p) >= s) is the
chance that one trial puts at least s planted copies in the motif bucket."""
if not 0 < q < 1:
raise ValueError("q must be in (0, 1)")
P = float(binomial_tail(n, hit_probability(L, d, k), s))
if P <= 0:
raise ValueError("a trial can never succeed with these parameters")
if P >= 1:
return 1
m = math.ceil(math.log(1 - q) / math.log(1 - P))
while m > 1 and 1 - (1 - P) ** (m - 1) >= q:
m -= 1
while 1 - (1 - P) ** m < q:
m += 1
return m
def letter_frequencies(seqs: Sequence[str]) -> List[float]:
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 w in kmers(s, L)] for s in seqs]
def oops_score(X, theta, mu) -> float:
"""The OOPS log likelihood ratio: sum over sequences of log((1/W_i) sum_q prod_j theta_j(x_j) / mu(x_j))."""
lr = [[math.log(theta[j][a] / mu[a]) for a in range(4)] for j in range(len(theta))]
total = 0.0
for rows in X:
v = [sum(lr[j][c] for j, c in enumerate(x)) for x in rows]
m = max(v)
total += m + math.log(sum(math.exp(t - m) for t in v) / len(v))
return total
def oops_em(X, theta, mu, beta: float, iterations: int) -> Tuple[List[List[float]], List[float]]:
"""EM for the OOPS model with fixed background mu; returns theta and the score after each iteration.
E step: z_iq proportional to prod_j theta_j(x_j) / mu(x_j) within each sequence.
M step: theta_j(a) = (sum z [x_j = a] + beta mu(a)) / (n + beta).
"""
L = len(theta)
n = len(X)
history = []
for _ in range(iterations):
lr = [[math.log(theta[j][a] / mu[a]) for a in range(4)] for j in range(L)]
c = [[0.0] * 4 for _ in range(L)]
for rows in X:
v = [sum(lr[j][a] for j, a in enumerate(x)) for x in rows]
m = max(v)
w = [math.exp(t - m) for t in v]
z = sum(w)
for x, wk in zip(rows, w):
for j, a in enumerate(x):
c[j][a] += wk / z
theta = [[(c[j][a] + beta * mu[a]) / (n + beta) for a in range(4)] for j in range(L)]
history.append(oops_score(X, theta, mu))
return theta, history
def projection(seqs: Sequence[str], L: int, k: int, trials: int, s: int = 3, seed: int = 0,
beta: float = 1.0, em_iterations: int = 10) -> ProjectionResult:
"""Run PROJECTION and return the best refined model.
Draw order: random.Random(seed); one rng.sample(range(L), k) per trial.
A bucket is refined when its windows come from at least s different
sequences. The start model of a bucket is its letter counts plus beta mu(a).
Among equal scores the first refined bucket wins.
"""
if L <= 0 or not 1 <= k <= L:
raise ValueError("need L >= 1 and 1 <= k <= L")
if not seqs:
raise ValueError("need at least one sequence")
for x in seqs:
if len(x) < L or set(x) - set(DNA):
raise ValueError("sequences must be over ACGT with length at least L")
if trials < 1 or s < 1 or beta <= 0 or em_iterations < 1:
raise ValueError("trials, s and em_iterations must be at least 1, beta positive")
mu = letter_frequencies(seqs)
if min(mu) == 0:
raise ValueError("every letter must occur in the input")
rng = random.Random(seed)
X = _encode(seqs, L)
best = None # @line L1
refined = 0
projections = []
for _ in range(trials): # @line L2
pos = sorted(rng.sample(range(L), k)) # @line L3
projections.append(tuple(pos))
buckets: Dict[Tuple[int, ...], List[Tuple[int, int]]] = {}
for i, rows in enumerate(X): # @line L4
for q, x in enumerate(rows):
buckets.setdefault(tuple(x[p] for p in pos), []).append((i, q))
for key in sorted(buckets): # @line L5
members = buckets[key]
if len({i for i, _ in members}) < s:
continue
refined += 1
counts = [[beta * mu[a] for a in range(4)] for _ in range(L)] # @line L6
for i, q in members:
for j, a in enumerate(X[i][q]):
counts[j][a] += 1
theta = [[c / sum(row) for c in row] for row in counts]
theta, history = oops_em(X, theta, mu, beta, em_iterations) # @line L7
if best is None or history[-1] > best[0]: # @line L8
best = (history[-1], theta)
if best is None:
raise ValueError("no bucket reached the threshold s; use more trials, a smaller k or a smaller s")
score, theta = best
lr = [[math.log(theta[j][a] / mu[a]) for a in range(4)] for j in range(L)]
sites = []
for rows in X:
v = [sum(lr[j][a] for j, a in enumerate(x)) for x in rows]
sites.append(v.index(max(v)))
cons = "".join(DNA[max(range(4), key=lambda a: (row[a], -a))] for row in theta)
return ProjectionResult(tuple(map(tuple, theta)), cons, tuple(sites), score, refined,
tuple(projections)) # @line L9
test_random_projection_motif_finding.py 130 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/random-projection-motif-finding/. The authors are listed in prov/24V46J.jsonl.
import itertools
import math
import random
from fractions import Fraction
import pytest
from bioseq import DNA, random_dna
from random_projection_motif_finding import (_encode, binomial_tail, hit_probability, letter_frequencies, oops_em,
oops_score, projection, trials_needed)
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 test_hit_probability_by_enumeration():
for L in range(1, 9):
for d in range(L + 1):
for k in range(L + 1):
# Over all k-sets of positions and all d-sets of changed positions.
good = sum(1 for I in itertools.combinations(range(L), k)
for D in itertools.combinations(range(L), d) if not set(I) & set(D))
assert hit_probability(L, d, k) == Fraction(good, math.comb(L, k) * math.comb(L, d))
assert hit_probability(15, 4, 7) == Fraction(330, 6435)
def test_hit_probability_by_simulation():
# Fresh motif copy and fresh projection in every round; tolerance z = 4.
rng = random.Random(77)
L, d, k, n, s, N = 15, 4, 7, 20, 4, 4000
p = float(hit_probability(L, d, k))
P = float(binomial_tail(n, hit_probability(L, d, k), s))
single = enough = 0
for _ in range(N):
pos = set(rng.sample(range(L), k))
hits = sum(1 for _ in range(n) if not pos & set(rng.sample(range(L), d)))
single += hits
enough += hits >= s
assert abs(single / (N * n) - p) <= 4 * math.sqrt(p * (1 - p) / (N * n))
assert abs(enough / N - P) <= 4 * math.sqrt(P * (1 - P) / N)
def test_binomial_tail_and_trials():
p = Fraction(1, 3)
assert binomial_tail(4, p, 0) == 1
assert binomial_tail(4, p, 4) == Fraction(1, 81)
assert binomial_tail(4, p, 3) == 4 * Fraction(2, 81) + Fraction(1, 81)
for (n, L, d, k, s, q) in [(20, 15, 4, 7, 4, 0.95), (8, 10, 2, 5, 4, 0.95), (10, 12, 3, 6, 3, 0.99)]:
m = trials_needed(n, L, d, k, s, q)
P = float(binomial_tail(n, hit_probability(L, d, k), s))
assert 1 - (1 - P) ** m >= q > 1 - (1 - P) ** (m - 1)
assert trials_needed(20, 15, 4, 7, 4, 0.95) == 172
def test_oops_em_never_lowers_the_score():
rng = random.Random(4)
_, seqs, _ = plant(rng, 6, 40, 8, 1)
X = _encode(seqs, 8)
mu = letter_frequencies(seqs)
for _ in range(3):
theta = []
for _ in range(8):
row = [rng.random() + 0.05 for _ in range(4)]
theta.append([x / sum(row) for x in row])
_, history = oops_em(X, theta, mu, 1.0, 15)
assert all(b >= a - 1e-9 for a, b in zip(history, history[1:]))
# The penalized score of the proof, step by step from the random start.
def penalized(t):
return oops_score(X, t, mu) + sum(mu[a] * math.log(t[j][a]) for j in range(8) for a in range(4))
before = penalized(theta)
for _ in range(5):
theta, _ = oops_em(X, theta, mu, 1.0, 1)
after = penalized(theta)
assert after >= before - 1e-9
before = after
def test_draw_order():
_, seqs, _ = plant(random.Random(2), 5, 30, 8, 1)
r = projection(seqs, 8, 3, 4, s=3, seed=9)
rng = random.Random(9)
assert r.projections == tuple(tuple(sorted(rng.sample(range(8), 3))) for _ in range(4))
assert r == projection(seqs, 8, 3, 4, s=3, seed=9)
def test_planted_success_rate():
# (n, G, L, d) = (8, 60, 10, 2), k = 5, s = 4 and the 37 trials that give a
# 0.95 chance of at least one good bucket. Measured on seeds 0 to 4: the
# consensus equals the planted motif in 4 of 5 runs. The test asks for at least 3.
T = trials_needed(8, 10, 2, 5, 4, 0.95)
hits = 0
for seed in range(5):
motif, seqs, _ = plant(random.Random(seed), 8, 60, 10, 2)
hits += projection(seqs, 10, 5, T, s=4, seed=seed).consensus == motif
assert hits >= 3
def test_errors():
with pytest.raises(ValueError):
projection(["ACGT"], 5, 2, 1)
with pytest.raises(ValueError):
projection(["ACGTACGT"], 4, 5, 1)
with pytest.raises(ValueError):
projection(["ACGTACGT"], 4, 2, 0)
with pytest.raises(ValueError):
projection(["ACGTACGT", "TTTTACGA"], 4, 2, 1, s=3)
with pytest.raises(ValueError):
trials_needed(20, 15, 4, 7, 4, 1.0)
with pytest.raises(ValueError):
hit_probability(4, 5, 2)
History
Pevzner and Sze (2000) posed the planted motif challenge and solved it with WINNOWER and SP-STAR. Buhler and Tompa (2001, 2002) then gave PROJECTION, which uses random projections, an idea from locality sensitive hashing, to find good starting points for EM on the challenge and other planted motif problems. Their analysis of the hit probability and of the number of trials is the one on this page.
References
- Jeremy Buhler and Martin Tompa, Finding motifs using random projections, Journal of Computational Biology 9(2), 2002, pp. 225 to 242, the projection, the bucket threshold, the refinement by EM and the analysis of the number of trials
- Jeremy Buhler and Martin Tompa, Finding motifs using random projections, Proceedings of the Fifth Annual International Conference on Computational Biology (RECOMB 2001), ACM, 2001, the conference version of the method
- Combinatorial approaches to finding subtle signals in DNA sequences, the planted (15, 4) motif challenge that PROJECTION addresses
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 24V46J Edit this page History Report an error Markdown