Algorithm Search⌘K

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.

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
Properties
randomizednot exactofflineiterative
Origin
Jeremy Buhler, Martin Tompa, 2001

PROJECTION, of Buhler and Tompa (2001, 2002), finds a planted motif by hashing. It picks kk of the LL 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 s1,…,sns_1, \ldots, s_n, each of length GG, a motif length LL, a projection size k≤Lk \le L, a bucket threshold ss, a number of trials mm and a seed. Each sequence has W=G−L+1W = G - L + 1 windows. Positions are 1-based on this page and 0-based in the code.

Output. A motif model θ\theta (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 MM when each sequence holds a copy of MM with dd changes.

The algorithm

For a set II of positions, the projection of a window xx is hI(x)=(xi)i∈Ih_I(x) = (x_i)_{i \in I}, the letters of xx at the positions in II. 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.

  1. PROJECTION(s[1 .. n], L, k, s_min, m, rng)
  2. 1best ← none
  3. 2for trial ← 1 to m do
  4. 3I ← k distinct positions drawn uniformly from 1 .. L
  5. 4put every window x of every sequence into the bucket h_I(x)
  6. 5for each bucket B that holds windows of at least s_min sequences do
  7. 6θ ← the letter counts of the windows of B, plus prior counts βμ(a), as probabilities
  8. 7refine θ by EM with one site per sequence
  9. 8if the score of θ is above the score of best then best ← θ
  10. 9return 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 μ\mu, the letter frequencies of the input. The E step gives each window of sis_i the weight ziq∝∏jθj(xj)/μ(xj)z_{iq} \propto \prod_j \theta_j(x_j)/\mu(x_j), normalized within the sequence; the M step sets θj(a)=(∑ziq[xj=a]+βμ(a))/(n+β)\theta_j(a) = (\sum z_{iq} [x_j = a] + \beta\mu(a))/(n + \beta). The score of line L8 is the log likelihood ratio of the OOPS model, ∑ilog⁡(1W∑q∏jθj(xj)/μ(xj))\sum_i \log(\frac{1}{W} \sum_q \prod_j \theta_j(x_j)/\mu(x_j)). The code uses β=1\beta = 1 and 10 EM iterations per bucket, and it counts the sequences of a bucket, not its windows, against smin⁡s_{\min}; these are the choices of this code.

Example

One copy. Let L=15L = 15, d=4d = 4 and k=7k = 7. 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:

p=(L−dk)(Lk)=(117)(157)=3306435=239≈0.0513.p = \frac{\binom{L - d}{k}}{\binom{L}{k}} = \frac{\binom{11}{7}}{\binom{15}{7}} = \frac{330}{6435} = \frac{2}{39} \approx 0.0513.

One trial. With n=20n = 20 sequences, the number of copies in the motif's bucket is Bin(20,p)\mathrm{Bin}(20, p) when the changed positions are random, so a trial puts at least s=4s = 4 copies there with probability P=Pr⁡[Bin(20,2/39)≥4]≈0.0173P = \Pr[\mathrm{Bin}(20, 2/39) \ge 4] \approx 0.0173.

The number of trials. To reach a good bucket with probability at least 0.950.95, PROJECTION needs mm trials with 1−(1−P)m≥0.951 - (1 - P)^m \ge 0.95, so m=⌈log⁡0.05/log⁡(1−P)⌉=172m = \lceil \log 0.05 / \log(1 - P) \rceil = 172.

Random buckets. For G=600G = 600, there are nW=20⋅586=11,720nW = 20 \cdot 586 = 11{,}720 windows and 47=16,3844^7 = 16{,}384 buckets, so a random bucket holds 0.720.72 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 dd changes in each sequence. With (n,G,L,d)=(8,60,10,2)(n, G, L, d) = (8, 60, 10, 2), k=5k = 5 and s=4s = 4, the theory gives p=56/252=0.222p = 56/252 = 0.222, P≈0.079P \approx 0.079 and m=37m = 37 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 PP 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 (n,G,L,d)=(20,600,15,4)(n, G, L, d) = (20, 600, 15, 4) 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 2/392/39 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 dd changed positions of a copy are a uniform random dd-set and II is a uniform random kk-set, independent of each other, then the copy and the motif have the same projection with probability at least p=(L−dk)/(Lk)p = \binom{L-d}{k}/\binom{L}{k}, 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 II avoids the changed positions. For a fixed dd-set, (L−dk)\binom{L-d}{k} of the (Lk)\binom{L}{k} choices of II avoid it. In the generator every change makes the letter differ, so agreement holds exactly when II avoids the set. □\square

Theorem (enough trials). If the copies of the nn sequences have independent random changes, a trial puts at least ss copies into the motif's bucket with probability P=Pr⁡[Bin(n,p)≥s]P = \Pr[\mathrm{Bin}(n, p) \ge s], and mm independent trials do so at least once with probability 1−(1−P)m1 - (1 - P)^m.

Proof. For a fixed II, each copy hits independently with probability pp by the first theorem, so the count is Bin(n,p)\mathrm{Bin}(n, p) for every II. The trials use independent projections and are independent. □\square

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 β∑j∑aμ(a)log⁡θj(a)\beta \sum_j \sum_a \mu(a) \log \theta_j(a), by the general ascent property of EM. The tests check pp by enumeration of all position sets for L≤8L \le 8 and by simulation within 4 standard deviations, check the formula for mm, 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 MM be a motif of length LL and let each sequence sis_i hold a copy cic_i of MM that differs from MM at exactly the positions of a set DiD_i with ∣Di∣=d|D_i| = d. A trial draws a set II of kk positions, uniform among the (Lk)\binom{L}{k} sets (line L3), and the bucket of a window xx is hI(x)=(xj)j∈Ih_I(x) = (x_j)_{j \in I} (line L4).

Lemma 1 (when a copy hits). hI(ci)=hI(M)h_I(c_i) = h_I(M) if and only if I∩Di=∅I \cap D_i = \emptyset.

Proof. The projections agree when cic_i and MM have the same letter at every j∈Ij \in I. They have the same letter exactly at the positions outside DiD_i. □\square

Theorem 1 (the hit probability). If DiD_i is a uniform random dd-set, independent of II, then Pr⁡[hI(ci)=hI(M)]=p=(L−dk)/(Lk)\Pr[h_I(c_i) = h_I(M)] = p = \binom{L-d}{k}/\binom{L}{k}. The same holds for a fixed DiD_i and a uniform II.

Proof. For a fixed DiD_i, the sets II that avoid it are the kk-subsets of the other L−dL - d positions, so by Lemma 1 the probability is (L−dk)/(Lk)\binom{L-d}{k}/\binom{L}{k}. This does not depend on DiD_i, so averaging over a random DiD_i gives the same value. □\square

When a change may keep the letter (a copy with at most dd differences), Lemma 1 gives only "if", and pp is a lower bound.

Theorem 2 (one trial). If D1,…,DnD_1, \ldots, D_n are independent uniform dd-sets, independent of II, the number HH of copies in the bucket hI(M)h_I(M) is Bin(n,p)\mathrm{Bin}(n, p), and a trial gives H≥sH \ge s with probability P=Pr⁡[Bin(n,p)≥s]P = \Pr[\mathrm{Bin}(n, p) \ge s].

Proof. Condition on II. The events I∩Di=∅I \cap D_i = \emptyset are independent, since the DiD_i are, and each has probability (L−dk)/(Lk)\binom{L-d}{k}/\binom{L}{k} for every fixed II, by the count of Theorem 1 with the roles of II and DiD_i exchanged: of the (Ld)\binom{L}{d} sets DiD_i, (L−kd)\binom{L-k}{d} avoid II, and (L−kd)/(Ld)=(L−dk)/(Lk)\binom{L-k}{d}/\binom{L}{d} = \binom{L-d}{k}/\binom{L}{k}, since both equal (L−k)! (L−d)!L! (L−k−d)!\frac{(L-k)!\,(L-d)!}{L!\,(L-k-d)!}. So given II, HH is Bin(n,p)\mathrm{Bin}(n, p), and the same holds without the condition. □\square

For a fixed input, the DiD_i are fixed, and the events I∩Di=∅I \cap D_i = \emptyset share the one random II, so they are not independent in general. Then Pr⁡[H≥s]\Pr[H \ge s] can differ from PP, while E[H]=np\mathrm{E}[H] = np still holds by Theorem 1 and linearity.

Theorem 3 (the number of trials). With mm trials that use independent projections, the chance that at least one trial gives H≥sH \ge s is 1−(1−P)m1 - (1 - P)^m. The least mm with 1−(1−P)m≥q1 - (1 - P)^m \ge q, for 0<P<10 < P < 1 and 0<q<10 < q < 1, is ⌈log⁡(1−q)/log⁡(1−P)⌉\lceil \log(1 - q)/\log(1 - P) \rceil.

Proof. Under the model of Theorem 2, the trials are independent and each fails with probability 1−P1 - P. The inequality (1−P)m≤1−q(1 - P)^m \le 1 - q is the same as m≥log⁡(1−q)/log⁡(1−P)m \ge \log(1 - q)/\log(1 - P), since log⁡(1−P)<0\log(1 - P) < 0. □\square

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 mm 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 ss different sequences. If a trial gives H≥sH \ge s, the motif's bucket is refined in that trial.

Proof. The code counts the distinct sequence indices of the members. The HH copies lie in HH different sequences. □\square

Lemma 3 (EM does not lower the score). Let ℓ(θ)=∑ilog⁡(1W∑q∏jθj(xiq,j)/μ(xiq,j))\ell(\theta) = \sum_i \log(\frac{1}{W} \sum_q \prod_j \theta_j(x_{iq,j})/\mu(x_{iq,j})) and let θ′\theta' be the result of one E step and one M step of line L7 with prior counts βμ\beta\mu. Then ℓ(θ′)+β∑j∑aμ(a)log⁡θj′(a)≥ℓ(θ)+β∑j∑aμ(a)log⁡θj(a)\ell(\theta') + \beta \sum_j \sum_a \mu(a) \log \theta'_j(a) \ge \ell(\theta) + \beta \sum_j \sum_a \mu(a) \log \theta_j(a).

Proof. Up to a constant that does not depend on θ\theta, ℓ\ell is the log likelihood of the model in which each sequence has one site at a uniform position, the site letters follow θ\theta and the other letters follow μ\mu. The E step computes the posterior ziqz_{iq} of the site position. The M step maximizes ∑i,qziq∑jlog⁡θj(xiq,j)+β∑j∑aμ(a)log⁡θj(a)\sum_{i,q} z_{iq} \sum_j \log \theta_j(x_{iq,j}) + \beta \sum_j \sum_a \mu(a) \log \theta_j(a) over the columns, and for column jj the maximum is at θj(a)∝∑i,qziq[xiq,j=a]+βμ(a)\theta_j(a) \propto \sum_{i,q} z_{iq}[x_{iq,j} = a] + \beta\mu(a), the rule of the code, with the sum n+βn + \beta since ∑qziq=1\sum_q z_{iq} = 1. 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. □\square

The code records ℓ\ell 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 10−910^{-9}.

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 nWnW keys of kk letters, O(nWk)O(nWk). Each refined bucket costs O(∣B∣L)O(|B| L) for line L6 and O(I nWL)O(I\,nWL) for II EM iterations of line L7. So a trial with BB refined buckets costs O(nWk+B I nWL)O(nWk + B\,I\,nWL), and mm trials mm times that. The buckets take O(nW)O(nW) space.

Complexity

  • Hashing. A trial computes nWnW keys of kk letters, O(nWk)O(nWk) time, and stores them in O(nW)O(nW) space.
  • Refinement. An EM iteration looks at all nWnW windows of LL letters, O(nWL)O(nWL). With BB buckets refined per trial and II iterations each, a trial costs O(nWk+BInWL)O(nWk + BInWL), and mm trials O(m(nWk+BInWL))O(m(nWk + BInWL)).
  • The choice of kk. A larger kk makes random buckets smaller, so BB drops, but it also lowers pp, so mm grows. A good kk keeps the mean size of a random bucket, nW/4knW/4^k, below 1 while kk stays below L−dL - d.
  • Space. The buckets take O(nW)O(nW) and the model O(L)O(L). 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 kk 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 kk.
  • Exact methods. For small (L,d)(L, d), exact algorithms for the planted motif problem enumerate candidate strings with pruning; PROJECTION scales to larger LL.

When to use it

Use PROJECTION for planted motif problems with subtle motifs, such as (15,4)(15, 4) or harder, where single windows are poor starts for EM. Work out pp, PP and mm for your (n,L,d)(n, L, d) before the run, and pick kk 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 kk that is too large. If k>L−dk > L - d, a copy with dd changes never hits the motif's bucket, and p=0p = 0.
  • A kk 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 mm.
  • 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.

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)
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 (15,4)(15, 4) 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 (15,4)(15, 4) 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

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

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