Algorithmcore
Gibbs motif sampler
Also called Lawrence Gibbs sampler.
Leave one sequence out, build a profile from the motif sites in the rest, and resample its site with probability given by the profile.
- Solves
- Motif finding
- Time
- O(T n W L) worstO(n W L) per_iteration
- Space
- O(n L + W) extra
- Where
- G = the length of each sequence; L = the motif length; T = the number of iterations; W = the number of windows per sequence, G - L + 1; n = the number of sequences
- Model
- Word RAM
- Properties
- randomizednot exactofflineiterative
- Evidence
- Proof sketchCode in 1 languages
- Origin
- Charles E. Lawrence, Stephen F. Altschul, Mark S. Boguski, Jun S. Liu, Andrew F. Neuwald, John C. Wootton, 1993
The Gibbs motif sampler, or site sampler, of Lawrence and others (1993) solves the motif finding problem with one site per sequence by a random walk over the choices of sites. In each step it takes one sequence out, builds a profile from the sites of the other sequences, gives each window of the left out sequence a weight that compares its probability under the profile with its probability under the background, and draws the new site with probability in proportion to the weight. The walk is a Gibbs sampler for an exact posterior distribution of the sites, and the output is the best state the walk visits.
In plain words
Guess one site in each sequence at random. Now take one sequence out and look at the sites of the others. Count the letters in each column of these sites. For every window of the sequence that you took out, ask how much better the counts explain it than random DNA does. A window that looks like the other sites gets a large weight. Pick the new site of this sequence at random, with chances in proportion to the weights, and put the sequence back. Then do the same for the next sequence, and go on.
A good window does not always win, and that is the point: because a worse window is picked now and then, the walk can leave a poor guess. Over many steps the walk spends most of its time on good choices of sites, and the best choice it visits is the answer.
The problem
Input. DNA sequences with , each of length , a motif length , a number of iterations , a pseudocount , background letter probabilities and a seed. Each sequence has windows. Positions are 1-based on this page and 0-based in the code.
The model. Each sequence has exactly one site, at an unknown start . The letters of the sites in column come from an unknown distribution with a symmetric Dirichlet prior of parameter , and all other letters come from the fixed background . With a uniform prior on the starts, integrating out the gives the posterior
where counts the letter in column of the sites and is the rising factorial. This is the collapsed model of Liu, Neuwald and Lawrence (1995) with one site per sequence.
Output. The state with the largest among the states that the walk visits.
The algorithm
Let be the column counts of the current sites. To update sequence , remove its site from . Then the weight of the window that starts at is
The first factor of each term is the profile of the other sites with pseudocount ; the second is the background.
GIBBS-MOTIF(s[1 .. n], L, T, b, q, rng)- 1
t_i ← a uniform start in 1 .. W, for i ← 1 to n, and c ← the column counts of the sites - 2
best ← t - 3
for it ← 1 to T do - 4
for k ← 1 to n do (i ← k in the systematic scan, i uniform in 1 .. n in the random scan) - 5
remove the letters of the site t_i from c - 6
A_x ← Π_j (c_j(s_i[x + j - 1]) + b) / ((n - 1 + 4b) q(s_i[x + j - 1])) for x ← 1 to W - 7
draw the new t_i = x with probability A_x / Σ_y A_y - 8
add the letters of the new site t_i to c - 9
if log π(t) > log π(best) then best ← t - 10
return best
Line L6 is the predictive update of Lawrence and others, and line L7 is their sampling step. The code works with the logarithms of the weights and subtracts the largest before it takes the exponent, so long motifs do not underflow. Line L9 checks the state once per iteration, that is, once per updates.
Random numbers. The code uses random.Random(seed). Line L1 draws one rng.randrange(W) per sequence, in order. Each update then draws one rng.randrange(n) in the random scan only, and one rng.random() for line L7, compared with the running sum of the weights.
Example
Take the five sequences of Rosalind problem BA2D with , and the uniform background , and let the current sites be CAG, CAG, CAA, CAA and CAA (1-based starts 7, 7, 1, 6 and 1). Update GGCGTTCAGGCA. The other sites CAG, CAA, CAA, CAA have the counts C: 4 in column 1, A: 4 in column 2, and G: 1, A: 3 in column 3. With , each factor of is :
| window | probability | ||
|---|---|---|---|
| 1 | GGC | 1/8 | 0.014 |
| 2 | GCG | 1/4 | 0.028 |
| 3 | CGT | 5/8 | 0.070 |
| 4 | GTT | 1/8 | 0.014 |
| 5 | TTC | 1/8 | 0.014 |
| 6 | TCA | 1/2 | 0.056 |
| 7 | CAG | 25/4 | 0.704 |
| 8 | AGG | 1/4 | 0.028 |
| 9 | GGC | 1/8 | 0.014 |
| 10 | GCA | 1/2 | 0.056 |
The weights sum to , so the site stays at CAG with probability , and moves elsewhere with probability . A strict search, like the randomized motif search, would always take CAG.
The sampler maximizes the posterior, not the motif score. On the sample of Rosalind problem BA2F with , and the letter frequencies of the input as background, runs of 2000 iterations from seeds 0 to 4 all end with the best state GTGTTCAG, GTGTAAGT, GTATACAG, GTGCACGT, GTGCAATG, with and motif score 11. The optimum of the motif score is 9, but the two optimal choices have smaller , 79.210 and 79.411. The sampler did its job; the two goals differ.
Measured success on planted motifs. The test generator plants a motif with exactly changes in each of 10 random sequences. A run counts as a success when the consensus of the best state equals the planted motif. With the systematic scan, , the input letter frequencies as background and seeds 0 to 19:
| 100 | (8, 1) | 7 of 20 | 14 of 20 | 20 of 20 |
| 100 | (10, 2) | 1 of 20 | 7 of 20 | 12 of 20 |
| 200 | (12, 3) | 0 of 20 | 0 of 20 | 1 of 20 |
For and , the best state has at least that of the planted sites in 17 of 20 runs, so in 5 runs the model itself prefers another motif. These are measurements on these seeds, not guarantees. On seeds 0 to 9 with and , the systematic scan succeeds in 7 runs and the random scan in 6.
Correctness
Theorem (the exact full conditional). The probabilities of line L7 are the conditional distribution of given the other sites under .
Proof. Fix for and let be their column counts. If the site of is the window , the count of in column is and the other counts of column are those of . Since , the numerator of is . The first product and the background terms of the other sites do not depend on . So , and the constant in does not change the normalized values.
So each update is a Gibbs step, and by the general theory of Gibbs sampling it leaves invariant: it satisfies detailed balance with respect to . The systematic scan is a product of such steps and the random scan is their average, so both leave invariant. Every weight is positive, so one sweep of either scan can reach every state, the Markov chain is irreducible and aperiodic, and is its unique stationary distribution. The state of the chain converges in distribution to , and since the chain has finitely many states and is irreducible, it visits every state, the mode of too, with probability 1.
These are statements about the limit. They say nothing about how fast the chain mixes, and on real data it can stay in a poor mode for a long time. The tests check the theorem exactly with fractions on a small input, check that both scans leave invariant exactly, check the sampling step with a chi-square test, and measure the planted success rate. The proofs are in proofs/correctness.md.
Proof: The site sampler draws from the exact full conditional and leaves the posterior invariantfull
Let () be DNA sequences, each with windows of length , let , and let for each letter. A state is a tuple of starts. Let be the site of , the number of sites with letter in column , and . Define
with the sum of the fraction over all states.
Where comes from. Let column of the motif have letter probabilities with the Dirichlet prior of density , let all letters outside the sites have the probabilities , and let the starts have a uniform prior. The likelihood of the sequences given and is times the product of over all letters, divided by the product of over the letters of the sites. The Dirichlet integral gives . With and after dropping the factors that do not depend on , the posterior of is .
Lemma 1 (the exact full conditional). For each , each state and each start of , let be with replaced by , and let be the weight of line L6 computed from the counts of the other sites. Then
Proof. Let be the window of at . In , the count of in column is , and every other count is . Since , the numerator of is , where does not depend on . The denominator is , where , the product over the other sites, does not depend on . So . The factor in front is the same for all , so it cancels in the ratio.
Lemma 2 (the code computes these weights). Before line L6 runs for sequence , the counts are .
Proof. Line L1 sets to the counts of all sites. Each update removes the old site of its sequence at line L5 and adds the new one at line L8, so between updates is the count of all current sites. Inside the update for , after line L5, it is the count of the other sites. The code computes , subtracts the largest value and draws with the weights , which have the same normalized values.
Lemma 3 (the draw). If is uniform on and , the function draw returns with probability .
Proof. It returns the first with , which happens exactly when is in , an interval of length in . The last line catches the case in which rounding makes the final sum a little smaller than .
In floating point Lemma 3 holds up to rounding; the tests check it with a chi-square test.
Theorem (invariance and convergence). Let be the kernel of one update of sequence . Then for each . So the systematic scan and the random scan (each repeated times per iteration) leave invariant. Both chains are irreducible and aperiodic on the finite set of states, so is their unique stationary distribution, the distribution of the state converges to , and the chain visits every state with probability 1.
Proof. By Lemmas 1 to 3, , and when differs from outside position . For and that agree outside position , the sum is the same for and , so . This is detailed balance, and summing over gives . A product or an average of kernels that keep keeps .
Every is positive, since and , so is positive on every state and for all . The systematic scan moves from any state to any state in one iteration with positive probability. The random scan does too, since with positive probability its choices of are in order. A chain with a positive one-step kernel on a finite set is irreducible and aperiodic, and the standard limit theorem for finite Markov chains gives the rest.
Corollary (the output). GIBBS-MOTIF returns a state that the chain visited at line L1 or at the end of some iteration, with the largest among these, since line L9 replaces only by a strictly larger value. As , the probability that the output is a mode of tends to 1, because the chain at the end of iterations is itself irreducible and visits every state.
Cost. An update takes for lines L5 and L8 and for line L6 and line L7. An iteration takes updates and for line L9, so , and iterations take . The extra space is .
The theorem is about the limit. It gives no bound on the mixing time, and the measured success rates on the page show that finite runs can fail.
The tests check Lemma 1 exactly with fractions on all 27 states of a small input, check for each and for the random scan exactly, check that differences of equal differences of , check Lemma 3 with a chi-square test, and measure the planted success rate.
Complexity
- Time. An update removes and adds a site in time and computes weights at each, so it takes . An iteration is updates, plus for at line L9, so . iterations take .
- Space. The counts take integers, the sites integers and the weights numbers, so with the windows of the best state.
- Randomness. One draw per update, plus one in the random scan.
Properties
- Randomized and approximate. The output depends on the seed, and a finite run gives no guarantee.
- Never stuck for good. Every window has a positive weight, so the walk can leave any state. A strict local search stops in the first local optimum.
- One site moves at a time. The walk moves slowly, and a shifted copy of the motif, the true motif moved by one or two positions, is a strong trap: most single moves from it lower .
- The background matters. The weights compare the profile with the background. A background that does not match the input, for example a uniform one on GC rich DNA, makes the sampler prefer windows rich in the common letters.
Variants and improvements
- Phase shifts. Lawrence and others added a move that shifts all sites by the same small offset, to escape from a shifted copy of the motif. The code on this page does not include it.
- Zero or one site per sequence. The models of Liu, Neuwald and Lawrence allow sequences with no site and sequences with several sites, with a prior on the number of sites.
- Several motifs. Later samplers extend the model to several motifs at once, to sites on both strands, and to backgrounds that depend on the letters before them.
- Restarts and annealing. Run several chains from different seeds, or raise the weights to a power that grows over time, as in simulated annealing, to find the mode faster.
- The version of Compeau and Pevzner. Their GibbsSampler uses the profile probability without the background, and keeps the state with the best motif score.
When to use it
Use the Gibbs motif sampler when the motif is subtle, the sequences are long, and you want a method that does not stop in the first local optimum. The method works with proteins as well as DNA; proteins were its first use. The code on this page is for DNA. Run several seeds and compare the results; agreement between runs is a good sign. For short motifs on short sequences, an exact median string search is cheaper and certain. For a single soft optimum, MEME is deterministic for a given start. For the planted problem, PROJECTION gives a better start than a uniform one.
Pitfalls
- Reading the last state as the answer. The state at the end of the run is a random draw. Keep the best state, or count how often each site is picked.
- Underflow. The product of ratios can overflow or underflow. Work with logarithms and subtract the largest before the exponent.
- Forgetting to remove the site. The profile at line L6 must not include the site of the sequence being updated, or the current site gets an unfair bonus and the chain does not sample .
- Too few iterations. On the planted data, 20 iterations succeed once in 20 runs and 1000 iterations 12 times. Measure the rate on your data.
- Comparing with the motif score. The sampler maximizes , not the motif score, as the BA2F example shows.
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)
gibbs_motif_sampler.py 153 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/gibbs-motif-sampler/. The authors are listed in prov/2BA89G.jsonl.
"""The site sampler of Lawrence et al. (1993) for one motif site per sequence.
The motif columns have a symmetric pseudocount b on every letter, and the
background letter probabilities q are fixed. Each update removes the site of
one sequence, scores every window of that sequence by
prod_j (c_j(x_j) + b) / ((n - 1 + 4b) q(x_j)) and draws the new site with
probability proportional to the score.
Positions are 0-based in this code; the page numbers them from 1.
"""
import math
import random
from typing import Dict, List, NamedTuple, Optional, Sequence, Tuple
from bioseq import DNA, kmers
_INDEX = {a: k for k, a in enumerate(DNA)}
class GibbsResult(NamedTuple):
"""The best state seen: windows, 0-based starts, log target, and the
iteration (0 for the start) at which it was first seen."""
motifs: Tuple[str, ...]
starts: Tuple[int, ...]
log_target: float
iteration: int
def background_from(seqs: Sequence[str]) -> Dict[str, float]:
"""Letter frequencies over all sequences (a letter that never occurs gets one count)."""
counts = {a: max(1, sum(s.count(a) for s in seqs)) for a in DNA}
total = sum(counts.values())
return {a: counts[a] / total for a in DNA}
def column_counts(windows: Sequence[str], L: int) -> List[List[int]]:
"""counts[j][a] = the number of windows with letter a in column j."""
counts = [[0] * 4 for _ in range(L)]
for w in windows:
for j, a in enumerate(w):
counts[j][_INDEX[a]] += 1
return counts
def site_weights(seq: str, counts: List[List[int]], n_other: int, b, q) -> list:
"""The weight of each window x of seq: prod_j (c_j(x_j) + b) / ((n_other + 4b) q(x_j)).
counts are the column counts of the other n_other sites. With Fraction
values for b and q the weights are exact.
"""
L = len(counts)
denom = n_other + 4 * b
out = []
for w in kmers(seq, L):
v = 1
for j, a in enumerate(w):
v = v * (counts[j][_INDEX[a]] + b) / (denom * q[a])
out.append(v)
return out
def _rising_log(b: float, m: int) -> float:
"""log of b (b + 1) ... (b + m - 1)."""
return math.lgamma(b + m) - math.lgamma(b)
def log_target(seqs: Sequence[str], starts: Sequence[int], L: int, b: float, q) -> float:
"""log pi(starts) up to a constant: sum over columns and letters of the log
rising factorial (b)_c, minus the log background probability of the sites."""
windows = [s[p:p + L] for s, p in zip(seqs, starts)]
v = 0.0
for col in column_counts(windows, L):
v += sum(_rising_log(b, c) for c in col)
for w in windows:
v -= sum(math.log(q[a]) for a in w)
return v
def draw(rng: random.Random, weights: Sequence[float]) -> int:
"""An index drawn with probability weights[k] / sum(weights), using one rng.random()."""
u = rng.random() * sum(weights)
acc = 0.0
for k, w in enumerate(weights):
acc += w
if u < acc:
return k
return len(weights) - 1
def _check(seqs, L, b, q):
if L <= 0:
raise ValueError("L must be positive")
if len(seqs) < 2:
raise ValueError("need at least two sequences")
for s in seqs:
if len(s) < L or set(s) - set(DNA):
raise ValueError("sequences must be over ACGT with length at least L")
if b <= 0:
raise ValueError("the pseudocount b must be positive")
if any(q[a] <= 0 for a in DNA):
raise ValueError("background probabilities must be positive")
def gibbs_motif_sampler(seqs: Sequence[str], L: int, iterations: int, seed: int = 0, b: float = 1.0,
background: Optional[Dict[str, float]] = None,
scan: str = "systematic") -> GibbsResult:
"""Run the site sampler and return the state with the largest log target seen.
Draw order: random.Random(seed); first one rng.randrange(W_i) per sequence
for the start; then for each update one rng.randrange(n) (only when scan is
"random") and one rng.random() for the draw. An iteration is n updates; the
systematic scan updates sequences 1 to n in order. Cost: O(n W L) time per
iteration and O(n L) extra space.
"""
q = background if background is not None else background_from(seqs)
_check(seqs, L, b, q)
if iterations < 0:
raise ValueError("iterations must be at least 0")
if scan not in ("systematic", "random"):
raise ValueError("scan must be 'systematic' or 'random'")
rng = random.Random(seed)
n = len(seqs)
starts = [rng.randrange(len(s) - L + 1) for s in seqs] # @line L1
counts = column_counts([s[p:p + L] for s, p in zip(seqs, starts)], L)
logq = {a: math.log(q[a]) for a in DNA}
log_denom = math.log(n - 1 + 4 * b)
cur = log_target(seqs, starts, L, b, q)
best = GibbsResult(tuple(s[p:p + L] for s, p in zip(seqs, starts)), tuple(starts), cur, 0) # @line L2
for it in range(1, iterations + 1): # @line L3
for k in range(n): # @line L4
i = k if scan == "systematic" else rng.randrange(n)
s = seqs[i]
for j, a in enumerate(s[starts[i]:starts[i] + L]): # @line L5
counts[j][_INDEX[a]] -= 1
logw = []
for x in range(len(s) - L + 1): # @line L6
v = 0.0
for j in range(L):
a = s[x + j]
v += math.log(counts[j][_INDEX[a]] + b) - log_denom - logq[a]
logw.append(v)
top = max(logw)
starts[i] = draw(rng, [math.exp(v - top) for v in logw]) # @line L7
for j, a in enumerate(s[starts[i]:starts[i] + L]): # @line L8
counts[j][_INDEX[a]] += 1
cur = log_target(seqs, starts, L, b, q) # @line L9
if cur > best.log_target:
best = GibbsResult(tuple(s[p:p + L] for s, p in zip(seqs, starts)), tuple(starts), cur, it)
return best # @line L10
test_gibbs_motif_sampler.py 175 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/gibbs-motif-sampler/. The authors are listed in prov/2BA89G.jsonl.
import itertools
import math
import random
from fractions import Fraction
import pytest
from bioseq import DNA, random_dna
from gibbs_motif_sampler import (background_from, column_counts, draw, gibbs_motif_sampler, log_target,
site_weights)
TINY = ["ACGA", "CGAT", "TACG"]
TINY_L = 2
QF = {"A": Fraction(3, 10), "C": Fraction(2, 10), "G": Fraction(2, 10), "T": Fraction(3, 10)}
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 consensus(windows):
return "".join(max(DNA, key=lambda a: (col.count(a), -DNA.index(a))) for col in zip(*windows))
def rising(b, m):
v = Fraction(1)
for k in range(m):
v *= b + k
return v
def exact_target(seqs, starts, L, b, q):
"""pi(starts) up to a constant, exactly: prod over columns and letters of (b)_c, over prod of q of the sites."""
windows = [s[p:p + L] for s, p in zip(seqs, starts)]
v = Fraction(1)
for col in column_counts(windows, L):
for c in col:
v *= rising(b, c)
for w in windows:
for a in w:
v /= q[a]
return v
def states(seqs, L):
return list(itertools.product(*[range(len(s) - L + 1) for s in seqs]))
def conditional(seqs, L, b, q, state, i):
"""The full conditional of the site of sequence i from site_weights, normalized."""
others = [s[p:p + L] for k, (s, p) in enumerate(zip(seqs, state)) if k != i]
w = site_weights(seqs[i], column_counts(others, L), len(others), b, q)
total = sum(w)
return [x / total for x in w]
def chi2_sf_df4(x):
# Survival function of the chi-square distribution with 4 degrees of freedom.
return math.exp(-x / 2) * (1 + x / 2)
@pytest.mark.parametrize("b", [Fraction(1), Fraction(1, 2)])
def test_site_weights_are_the_exact_full_conditional(b):
pi = {t: exact_target(TINY, t, TINY_L, b, QF) for t in states(TINY, TINY_L)}
for t in pi:
for i in range(len(TINY)):
row = [pi[t[:i] + (x,) + t[i + 1:]] for x in range(len(TINY[i]) - TINY_L + 1)]
total = sum(row)
assert conditional(TINY, TINY_L, b, QF, t, i) == [r / total for r in row]
def test_both_scans_leave_the_target_invariant():
b = Fraction(1)
S = states(TINY, TINY_L)
pi = {t: exact_target(TINY, t, TINY_L, b, QF) for t in S}
z = sum(pi.values())
pi = {t: v / z for t, v in pi.items()}
n = len(TINY)
kernels = []
for i in range(n):
K = {}
for t in S:
for x, p in enumerate(conditional(TINY, TINY_L, b, QF, t, i)):
K[t, t[:i] + (x,) + t[i + 1:]] = p
kernels.append(K)
# Each single-site update (so the systematic scan, their product) keeps pi.
for K in kernels:
out = {u: sum(pi[t] * K.get((t, u), 0) for t in S) for u in S}
assert out == pi
# The random scan kernel is the average of the single-site kernels.
out = {u: sum(pi[t] * sum(K.get((t, u), 0) for K in kernels) / n for t in S) for u in S}
assert out == pi
def test_log_target_matches_the_weights():
rng = random.Random(4)
seqs = [random_dna(rng, 12) for _ in range(5)]
L, b = 4, 1.0
q = background_from(seqs)
for _ in range(20):
t = [rng.randrange(9) for _ in seqs]
i = rng.randrange(5)
others = [s[p:p + L] for k, (s, p) in enumerate(zip(seqs, t)) if k != i]
w = site_weights(seqs[i], column_counts(others, L), 4, b, q)
x, y = rng.randrange(9), rng.randrange(9)
tx, ty = t[:i] + [x] + t[i + 1:], t[:i] + [y] + t[i + 1:]
diff = log_target(seqs, tx, L, b, q) - log_target(seqs, ty, L, b, q)
assert abs(diff - (math.log(w[x]) - math.log(w[y]))) < 1e-9
def test_draw_follows_the_weights():
rng = random.Random(2024)
weights = [1.0, 2.0, 3.0, 4.0, 5.0]
N = 20000
counts = [0] * 5
for _ in range(N):
counts[draw(rng, weights)] += 1
expected = [N * w / 15 for w in weights]
x = sum((c - e) ** 2 / e for c, e in zip(counts, expected))
assert chi2_sf_df4(x) > 0.001
def test_start_draw_order_and_best_state():
rng = random.Random(5)
seqs = [random_dna(rng, 20) for _ in range(4)]
r0 = gibbs_motif_sampler(seqs, 5, 0, seed=8)
replay = random.Random(8)
assert r0.starts == tuple(replay.randrange(16) for _ in seqs) and r0.iteration == 0
r = gibbs_motif_sampler(seqs, 5, 30, seed=8)
q = background_from(seqs)
assert r.log_target == log_target(seqs, r.starts, 5, 1.0, q) >= r0.log_target
assert r == gibbs_motif_sampler(seqs, 5, 30, seed=8)
assert all(s[p:p + 5] == m for s, p, m in zip(seqs, r.starts, r.motifs))
def test_planted_success_rate():
# Measured on seeds 0 to 9 with 100 iterations of the systematic scan: the
# consensus equals the planted motif in 7 of 10 runs. The test asks for at least 5.
hits = 0
for seed in range(10):
motif, seqs, _ = plant(random.Random(seed), 10, 100, 8, 1)
hits += consensus(gibbs_motif_sampler(seqs, 8, 100, seed=seed).motifs) == motif
assert hits >= 5
def test_errors():
with pytest.raises(ValueError):
gibbs_motif_sampler(["ACGT"], 2, 1)
with pytest.raises(ValueError):
gibbs_motif_sampler(["ACGT", "AC"], 3, 1)
with pytest.raises(ValueError):
gibbs_motif_sampler(["ACGT", "ACGT"], 2, 1, b=0)
with pytest.raises(ValueError):
gibbs_motif_sampler(["ACGT", "ACGT"], 2, 1, scan="other")
with pytest.raises(ValueError):
gibbs_motif_sampler(["ACGT", "ACGT"], 2, -1)
History
Lawrence, Altschul, Boguski, Liu, Neuwald and Wootton (1993) introduced the site sampler to align subtle motifs in protein sequences. Their method alternates a predictive update, the profile of the other sites, with a sampling step. Liu, Neuwald and Lawrence (1995) set the method in a Bayesian model with Dirichlet priors, in which the update draws from the exact conditional of the collapsed model, and compared several sampling strategies. Compeau and Pevzner (2015) present a simple form of it after the randomized motif search.
References
- Charles E. Lawrence, Stephen F. Altschul, Mark S. Boguski, Jun S. Liu, Andrew F. Neuwald and John C. Wootton, Detecting subtle sequence signals, a Gibbs sampling strategy for multiple alignment, Science 262(5131), 1993, pp. 208 to 214, the predictive update step and the sampling step of the site sampler
- Jun S. Liu, Andrew F. Neuwald and Charles E. Lawrence, Bayesian models for multiple local sequence alignment and Gibbs sampling strategies, Journal of the American Statistical Association 90(432), 1995, pp. 1156 to 1170, the Bayesian model with Dirichlet priors and the collapsed sampler
- Phillip Compeau and Pavel Pevzner, Bioinformatics Algorithms, An Active Learning Approach, Volume I, 2nd edition, Active Learning Publishers, 2015, Chapter 2, Section 2.9, Gibbs sampling
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 2BA89G Edit this page History Report an error Markdown