Algorithmadvanced
WINNOWER
Also called Pevzner-Sze clique motif finding.
Build a graph of l-mers joined when close in Hamming distance and find the planted motif as a large clique after pruning weak edges.
- Solves
- Planted motif problem
- Time
- O(n^2 W^2 L + E^2 n W + W^n) worstO(n^2 W^2 L) buildO(E n W) per_pass
- Space
- O(n W + E) extra
- Where
- E = the number of edges of the graph; G = the length of each sequence; L = the motif length; W = the number of windows per sequence, G - L + 1; d = the number of mismatches; n = the number of sequences
- Model
- Word RAM
- Properties
- deterministicnot exactofflinerecursive
- Evidence
- Proof sketchCode in 1 languages
- Origin
- Pavel A. Pevzner, Sing Hoi Sze, 2000
WINNOWER, of Pevzner and Sze (2000), solves the planted motif problem through graphs. Each window of length of each sequence is a vertex, and two windows of different sequences are joined when their Hamming distance is at most . The planted copies of the motif are within of the motif, so they are within of each other and form a clique with one vertex in each sequence. Random windows give many more edges, but few of them lie in large cliques. WINNOWER removes, again and again, every edge that cannot be part of a clique that reaches all sequences, and then looks for the cliques in the small graph that is left.
In plain words
Draw a dot for every short piece of every sequence. Join two dots of different sequences when the two pieces differ in at most places. The hidden copies of the motif are all close to one word, so each pair of them is joined: they form a group in which every dot is joined to every other, with one dot from each sequence.
Most lines in the drawing join two random pieces that just happen to be similar. Such a line is weak: for some other sequence, no piece there is close to both ends. A line between two real copies is never weak, because every other sequence has a copy close to both. So erase the weak lines, and repeat, since erasing lines can make other lines weak. Only a few lines are left, and among them the real group is easy to find.
The problem
Input. DNA sequences with , each of length , a motif length and a number of mismatches . Each sequence has windows. Positions are 1-based on this page and 0-based in the code.
The graph. The vertices are the pairs , the window of at . An edge joins and for when . The graph is -partite: there are no edges inside a sequence.
Output. The pruned graph and its -cliques, each a choice of one window per sequence with every pair within . Every motif of the input gives such a clique, by the triangle inequality, but not every clique comes from a motif: the condition is necessary, not sufficient.
The algorithm
Call an edge extendable if every sequence other than those of and has a window joined to both and .
WINNOWER(s[1 .. n], L, d)- 1
build the graph: a vertex per window, an edge between windows of different sequences with d_H ≤ 2d - 2
repeat - 3
for each edge (u, v) do - 4
if some sequence p other than those of u and v has no window joined to both u and v then - 5
remove the edge (u, v) - 6
until a pass removes no edge - 7
C ← the n-cliques of the graph that is left, by backtracking over the sequences in order - 8
return the graph and C
Lines L2 to L6 are the winnowing: a pass removes the edges that are not extendable, and the passes go on until every edge is extendable. Line L7 picks a window of , then a window of joined to it, then a window of joined to both, and so on; the code keeps, for each sequence, the set of neighbours of each vertex in that sequence, so the candidates are an intersection of sets.
The general form. Pevzner and Sze call a clique extendable when every other sequence has a window joined to all of its vertices. An edge of a planted -clique lies in cliques of size inside the planted clique, and all of them are extendable. So an edge that lies in fewer extendable -cliques cannot be in the planted clique and can go. The case , where an edge must itself be extendable, is the rule on this page. Larger removes more edges, at a higher cost per pass.
Example
Take the small instance of the planted motif problem page: , and the four sequences TCGAATCACAAC, CTAGTTACTCTT, GCTAGATTACGT and AACTAGTGGGAC, with the motif AATTA planted at the 1-based starts 4, 3, 5 and 1. Each sequence has windows, so the graph has 32 vertices. With the bound , it has 42 edges:
| pair of sequences | 1, 2 | 1, 3 | 1, 4 | 2, 3 | 2, 4 | 3, 4 |
|---|---|---|---|---|---|---|
| edges | 6 | 7 | 5 | 9 | 10 | 5 |
The first pass removes 36 edges, and the second removes none. The 6 edges left join the four windows AATCA (sequence 1, position 4), AGTTA (2, 3), GATTA (3, 5) and AACTA (4, 1): they form one clique, the planted sites, and their consensus is AATTA.
Measured pruning. The test generator plants a motif with exactly changes in each sequence:
| seed | edges before | edges after | passes | cliques | planted clique found | |
|---|---|---|---|---|---|---|
| (8, 100, 11, 2) | 0 | 1872 | 28 | 2 | 1 | yes |
| (10, 100, 12, 3) | 1 | 19,962 | 64 | 3 | 4 | yes |
| (10, 200, 15, 4) | 0 | 90,140 | 126 | 4 | 6 | yes |
| (10, 200, 15, 4) | 1 | 88,543 | 54 | 3 | 2 | yes |
A planted clique with has edges, so in the first row WINNOWER leaves exactly the planted clique. In the rows with several cliques, most of the other cliques share 8 or 9 of their 10 windows with the planted one, but in the third row three of the six cliques share no window with it: they are random cliques that survive the pruning. These are measurements on these seeds.
The (15, 4) challenge. For and there are pairs of windows, and two random 15-letter windows are within distance 8 with probability about 0.0566, so the graph has about random edges against the 190 edges of the planted clique, about 20,000 random edges for each true one. Pevzner and Sze report, in Table 1 of their paper, the mean performance coefficient on 8 such samples, a measure of the overlap of the predicted sites with the planted ones that is 1 for a perfect answer: CONSENSUS 0.07, GibbsDNA 0.12, MEME 0.10, WINNOWER 0.92 and SP-STAR 0.84.
Correctness
WINNOWER is exact in one sense: it never removes an edge of an -clique, so line L7 finds every -clique of the original graph.
Theorem (no clique edge is removed). Every edge of an -clique of the graph built at line L1 is in the graph at the end.
Proof. Let be an -clique with one vertex in each sequence. As long as all edges of are present, each edge of is extendable: for each other sequence , the vertex of in is joined to and to . So line L4 does not remove the first edge of that would be removed, a contradiction.
Theorem (the result is unique). The graph at the end is the largest subgraph of the original graph in which every edge is extendable, and it does not depend on the order of the removals.
Proof. If two subgraphs have only extendable edges, so does their union, since an edge keeps its common neighbours when edges are added. So there is a largest such subgraph . An edge of is extendable in any graph that contains , so by the argument of the first theorem no edge of is ever removed. At the end, every edge is extendable, so the graph at the end is a subgraph with only extendable edges and contains ; by the choice of , it is .
So the set of line L7 is exactly the set of -cliques of the original graph. What WINNOWER does not promise is that contains only the planted motif: random cliques survive too, and the planted clique, if the input has several near motifs, is only one of them. The tests compare with brute force over all choices of windows, check that every remaining edge is extendable and that one more pass removes nothing, and check that a removal in a random order gives the same graph. The proofs are in proofs/correctness.md.
Proof: WINNOWER keeps every n-clique and ends with the unique largest subgraph of extendable edgesfull
Let () be sequences and the graph of line L1: the vertices are the windows , and an edge joins windows of different sequences with Hamming distance at most . For a subgraph with , call an edge extendable in if for every sequence other than the sequences of and there is a vertex of with and . Call closed if every edge of is extendable in .
Lemma 1 (monotone). If and is extendable in , then it is extendable in .
Proof. The common neighbours that witness it in are still neighbours in .
Lemma 2 (a largest closed subgraph). There is a unique closed subgraph that contains every closed subgraph.
Proof. The empty edge set is closed. If and are closed, then each edge of is extendable in and so, by Lemma 1, in ; the same holds for . So the union of closed subgraphs is closed, and is the union of all closed edge sets, which are finitely many.
Lemma 3 (the planted cliques are closed). If is an -clique of (one vertex per sequence), its edge set is closed, so .
Proof. For an edge of and a sequence other than those of and , the vertex of in is joined to both and by edges of .
Theorem. Whatever the order of the removals, lines L2 to L6 end with the edge set .
Proof. Invariant: the current edge set contains . It holds at the start, since . Suppose it holds and line L5 removes . Line L4 found that is not extendable in . If were in , it would be extendable in and, by Lemma 1, in , since . So , and the invariant holds after the removal.
The loop ends: each pass but the last removes at least one edge, and is finite. It ends after a pass that removes no edge, that is, after a pass in which every edge of the current was found extendable. An edge that was checked early in the pass could only lose witnesses through a later removal in the same pass, but that pass made no removal, so at the end every edge of is extendable in , and is closed. By Lemma 2, , and with the invariant, .
Corollary 1 (no clique is lost). By Lemma 3 and the theorem, every edge of every -clique of survives, so the -cliques of the pruned graph are exactly the -cliques of . Removing edges creates no new cliques.
Corollary 2 (idempotent). A second run of lines L2 to L6 on the result makes one pass and removes nothing, since is closed.
Lemma 4 (the clique listing). Line L7 lists every -clique of the pruned graph exactly once.
Proof. The backtracking picks a vertex of and, at depth , a vertex of that is joined to all vertices already picked; these candidates are the intersection of their neighbour sets in . Every -clique is found along the path , since each is a candidate after . Different paths give different tuples, and a tuple at depth has every pair joined.
Planted motifs. If is a string with for every , then by the triangle inequality every pair of these windows is within , so is an -clique of , and by Corollary 1 it is in the output. The converse is false: an -clique need not have a string within of all its windows.
Cost. Line L1 computes distances of each. A pass checks each of at most edges against sequences with a set intersection of , so , and there are at most passes. The listing is in the worst case.
The tests compare the output cliques with brute force over all choices of windows, check that every left edge is extendable and that a second run removes nothing, and check that removing edges one at a time in a random order gives the same edge set.
Complexity
- Building the graph. There are pairs of windows and each distance takes , so time. This is the main cost in practice.
- Winnowing. A pass checks each edge against other sequences, and each check is an intersection of two sets of at most vertices, so a pass takes time. Each pass but the last removes an edge, so there are at most passes; in the measured runs there were 2 to 4.
- Listing cliques. Backtracking over the sequences can take time in the worst case, but after the winnowing the graph is small and the search is fast.
- Space. The graph takes . For the challenge, is in the millions, so the memory of the graph limits the size of the input that WINNOWER can handle.
Properties
- Deterministic and complete for cliques. It finds every -clique of the graph, with no randomness.
- Not a full solution of the planted motif problem. A clique is a necessary condition for a motif, not a sufficient one. The consensus of a clique need not be a valid motif, and a clique can come from random windows.
- Parameter driven. The bound must match the planted motif. A larger bound gives many more edges, a smaller one can lose the planted clique.
- Order independent. By the uniqueness theorem, the pruned graph does not depend on the order of the removals.
Variants and improvements
- Larger cliques for the rule. Use extendable cliques of size , as in the general form above. Pevzner and Sze used this to prune more of the random edges.
- SP-STAR. In the same paper, Pevzner and Sze give SP-STAR, a local search for the sites with a sum of pairs score.
- Missing sites. Allow cliques that miss a few sequences, for inputs in which not every sequence has a site.
- Hashing first. PROJECTION avoids the full graph: it hashes windows into buckets and refines the large buckets, with much less memory.
- Exact pattern enumeration. For small , test all candidate strings, as in the median string search; later exact methods for the planted motif problem use this idea with pruning.
When to use it
Use WINNOWER when the motif is subtle, the planted model with a known fits the data, and the graph fits in memory. It found the motif where the profile based methods of its time failed. For long sequences or many sequences, the graph becomes too large, and PROJECTION is the better choice. When the motif model is a profile and not a string with mismatches, use MEME or the Gibbs motif sampler.
Pitfalls
- Reading a clique as the motif. A clique is a set of windows with small pairwise distances. Check that some string is within of all of them, for example the consensus, before you report it.
- The wrong bound. Use , not , for the edges: two copies of the motif can differ in up to places.
- Memory. The graph has about times the probability of a close pair edges; work it out before you build it.
- Edges inside a sequence. Do not join two windows of the same sequence; the clique must take one window from each sequence.
- Stopping after one pass. A removal can make other edges not extendable, so repeat the passes until nothing changes.
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)
winnower_algorithm.py 113 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/winnower-algorithm/. The authors are listed in prov/561KFN.jsonl.
"""WINNOWER of Pevzner and Sze (2000) in its basic form: build the n-partite
graph of windows joined when their Hamming distance is at most 2d, remove
every edge that has no common neighbor in some other sequence until no such
edge is left, and list the n-cliques of what remains.
Positions are 0-based in this code; the page numbers them from 1. A vertex is
a pair (sequence index, start).
"""
from typing import Dict, List, NamedTuple, Sequence, Set, Tuple
from bioseq import DNA, hamming
Vertex = Tuple[int, int]
class WinnowerResult(NamedTuple):
"""Edge counts before and after, the number of passes of the pruning loop,
the surviving edges, and the n-cliques as tuples of 0-based starts."""
edges_before: int
edges_after: int
passes: int
edges: frozenset
cliques: Tuple[Tuple[int, ...], ...]
def build_graph(seqs: Sequence[str], L: int, d: int) -> Dict[Vertex, List[Set[Vertex]]]:
"""adj[v][p] = the windows of sequence p within Hamming distance 2d of v (p != part of v)."""
n = len(seqs)
wins = [[(i, q) for q in range(len(s) - L + 1)] for i, s in enumerate(seqs)]
adj = {v: [set() for _ in range(n)] for part in wins for v in part}
for i in range(n):
for k in range(i + 1, n):
for u in wins[i]:
a = seqs[i][u[1]:u[1] + L]
for v in wins[k]:
if hamming(a, seqs[k][v[1]:v[1] + L]) <= 2 * d:
adj[u][k].add(v)
adj[v][i].add(u)
return adj
def edge_set(adj) -> frozenset:
return frozenset((u, v) for u in adj for part in adj[u] for v in part if u < v)
def winnow(adj, n: int) -> int:
"""Remove edges with no common neighbor in some other part, in place, until
none is left. Returns the number of passes over the edges."""
passes = 0
while True: # @line L2
passes += 1
removed = False
for u, v in sorted(edge_set(adj)): # @line L3
if v not in adj[u][v[0]]:
continue
if any(adj[u][p].isdisjoint(adj[v][p]) for p in range(n) if p != u[0] and p != v[0]): # @line L4
adj[u][v[0]].discard(v) # @line L5
adj[v][u[0]].discard(u)
removed = True
if not removed: # @line L6
return passes
def cliques(adj, n: int) -> List[Tuple[int, ...]]:
"""All n-cliques with one vertex per part, by backtracking in the order of the parts."""
out = []
def extend(chosen: List[Vertex]) -> None:
p = len(chosen)
if p == n:
out.append(tuple(q for _, q in chosen))
return
cand = set(adj[chosen[0]][p])
for w in chosen[1:]:
cand &= adj[w][p]
for v in sorted(cand):
extend(chosen + [v])
for v in sorted(x for x in adj if x[0] == 0):
extend([v])
return out
def winnower(seqs: Sequence[str], L: int, d: int) -> WinnowerResult:
"""Run WINNOWER: build the graph, prune edges that are not extendable, list the n-cliques.
Cost: O(n^2 W^2 L) to build the graph; each pass of the pruning loop costs
O(|E| n W) with set intersections; listing the cliques is exponential in
the worst case.
"""
if L <= 0 or d < 0:
raise ValueError("L must be positive and d at least 0")
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")
n = len(seqs)
adj = build_graph(seqs, L, d) # @line L1
before = len(edge_set(adj))
passes = winnow(adj, n)
found = cliques(adj, n) # @line L7
edges = edge_set(adj)
return WinnowerResult(before, len(edges), passes, edges, tuple(found)) # @line L8
def consensus(windows: Sequence[str]) -> str:
"""The most common letter of each column (the first in ACGT order on a tie)."""
return "".join(max(DNA, key=lambda a: (col.count(a), -DNA.index(a))) for col in zip(*windows))
test_winnower_algorithm.py 118 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/winnower-algorithm/. The authors are listed in prov/561KFN.jsonl.
import itertools
import random
import pytest
from bioseq import DNA, hamming, random_dna
from winnower_algorithm import build_graph, cliques, consensus, edge_set, winnow, winnower
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 brute_cliques(seqs, L, d):
ranges = [range(len(s) - L + 1) for s in seqs]
out = []
for p in itertools.product(*ranges):
w = [s[q:q + L] for s, q in zip(seqs, p)]
if all(hamming(a, b) <= 2 * d for a, b in itertools.combinations(w, 2)):
out.append(p)
return out
def winnow_in_random_order(seqs, L, d, rng):
"""The same pruning rule, one edge at a time, in a random order, until no edge can go."""
n = len(seqs)
adj = build_graph(seqs, L, d)
while True:
edges = sorted(edge_set(adj))
rng.shuffle(edges)
for u, v in edges:
if any(adj[u][p].isdisjoint(adj[v][p]) for p in range(n) if p not in (u[0], v[0])):
adj[u][v[0]].discard(v)
adj[v][u[0]].discard(u)
break
else:
return edge_set(adj)
def instances():
rng = random.Random(21)
out = []
for _ in range(12):
n, L, d = rng.randint(3, 4), rng.randint(3, 5), rng.randint(0, 1)
if rng.random() < 0.5:
out.append(([random_dna(rng, rng.randint(L, 10)) for _ in range(n)], L, d))
else:
out.append((plant(rng, n, 10, L, d)[1], L, d))
return out
def test_cliques_equal_brute_force():
for seqs, L, d in instances():
r = winnower(seqs, L, d)
assert sorted(r.cliques) == brute_cliques(seqs, L, d)
# Backtracking on the unpruned graph gives the same list.
assert cliques(build_graph(seqs, L, d), len(seqs)) == list(r.cliques)
def test_every_left_edge_is_extendable_and_pruning_is_idempotent():
for seqs, L, d in instances():
n = len(seqs)
adj = build_graph(seqs, L, d)
winnow(adj, n)
for u, v in edge_set(adj):
for p in range(n):
if p not in (u[0], v[0]):
assert adj[u][p] & adj[v][p]
before = edge_set(adj)
assert winnow(adj, n) == 1 and edge_set(adj) == before
def test_result_does_not_depend_on_the_order():
rng = random.Random(5)
for seqs, L, d in instances()[:6]:
assert winnow_in_random_order(seqs, L, d, rng) == winnower(seqs, L, d).edges
def test_planted_clique_survives():
# Measured on seeds 0 to 2 at (n, G, L, d) = (8, 100, 11, 2): about 1900 to
# 2100 edges before and 28 after, and the planted starts are the only clique.
for seed in range(3):
motif, seqs, starts = plant(random.Random(seed), 8, 100, 11, 2)
r = winnower(seqs, 11, 2)
assert r.edges_before > 1800 and r.edges_after == 28
assert r.cliques == (tuple(starts),)
# On these seeds the consensus of the clique is the planted motif (not true for every input).
assert consensus([s[q:q + 11] for s, q in zip(seqs, starts)]) == motif
def test_errors():
with pytest.raises(ValueError):
winnower(["ACGT"], 2, 1)
with pytest.raises(ValueError):
winnower(["ACGT", "AC"], 3, 0)
with pytest.raises(ValueError):
winnower(["ACGT", "ACGT"], 2, -1)
with pytest.raises(ValueError):
winnower(["ACGT", "ACXT"], 2, 0)
History
Pevzner and Sze (2000) posed the planted motif problem as a challenge: 20 sequences of length 600, each with a copy of a 15-letter motif with 4 mismatches. They showed that CONSENSUS, the Gibbs sampler and MEME failed on it, and they gave two new methods, WINNOWER, based on cliques in a graph of windows, and SP-STAR, based on a sum of pairs score. Both did much better on the challenge. Buhler and Tompa (2001, 2002) then gave PROJECTION, which solves the same problems with much less memory.
References
- Combinatorial approaches to finding subtle signals in DNA sequences, the graph of windows, extendable cliques and the WINNOWER pruning, and Table 1 with the performance on the (15, 4) problem
- Jeremy Buhler and Martin Tompa, Finding motifs using random projections, Journal of Computational Biology 9(2), 2002, pp. 225 to 242, the comparison of PROJECTION with WINNOWER and other methods on planted motif problems
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 561KFN Edit this page History Report an error Markdown