Algorithmadvanced
Weight matrix score p-value
Also called PWM score distribution, motif match p-value.
Compute the exact distribution of a weight matrix score under a background model by dynamic programming over rounded scores.
- Time
- O(r L c S) worstO(L^2 c R / h) grid_boundO(L c S) per_round
- Space
- O(S + L c) extra
- Where
- L = the number of columns; R = the largest entry minus the smallest entry of the matrix; S = the largest number of partial scores kept after a column; c = the alphabet size, 4 for DNA; h = the grid step of the last round; r = the number of rounds
- Properties
- deterministicnot exactofflineiterative
- Evidence
- Proof sketchCode in 1 languages
- Origin
- Hélène Touzet, Jean Stéphane Varré, 2007
A position weight matrix gives a score to each word of length , and a site is reported when the score reaches a threshold . The p-value of is the chance that a random word from the background scores at least . For small you can list all words, but for a matrix of 20 columns this is words. The method of Touzet and Varré (2007) rounds the matrix entries down to a grid of step , computes the distribution of the rounded score by convolution one column at a time, and gets a lower and an upper bound on the p-value. When no rounded score is near the threshold, the two bounds are equal and the answer is exact; otherwise it makes the grid ten times finer and tries again.
In plain words
The score of a word is a sum, one term per column. If each term can take only a few values, you can build the table of all possible sums and their chances, one column at a time, like adding dice. Real matrix entries are arbitrary numbers, so the table can grow to one entry per word.
So round every entry down to a multiple of a small step. Now the sums lie on a grid, and the table stays small. Rounding moves each score down by at most a known amount . A word whose rounded score is at least surely passes. A word whose rounded score is below surely fails. Only the words in between are in doubt. If there are none, the answer is exact. If there are some, use a finer step.
The problem
Input. A matrix with columns and one real entry for each column and letter , a background with , and a threshold . The score of a word is , and the letters of a random word are independent with probabilities . Columns are numbered from 1 on this page and from 0 in the code.
Output. , or bounds when a cap on the rounds is reached.
The algorithm
For a grid step , let , an integer, and let the rounded score be . The largest rounding error is , with the maximum over the letters with . Then for every word of positive probability.
PWM-P-VALUE(M, p, α, ε0, rounds)- 1
ε ← ε0 - 2
repeat - 3
N_j(a) ← ⌊M_j(a) / ε⌋ for every column j and letter a - 4
E ← Σ_j max_a (M_j(a) - ε N_j(a)) - 5
A ← ⌈α / ε⌉ - 6
B ← ⌈(α - E) / ε⌉ - 7
(sure, middle) ← ROUND(N, p, A, B) - 8
lo ← sure - 9
hi ← sure + Σ_s middle[s] - 10
if middle is empty or this was the last allowed round then - 11
return lo, hi and whether middle is empty - 12
ε ← ε / 10
ROUND is the dynamic programming of line L7. It keeps a table from integer partial scores to probabilities, starting with . For column , each entry of and each letter , it forms with probability . Let and be the largest and the smallest sums of over the columns after . If , every completion reaches , so is added to sure. If , no completion reaches , and the mass is dropped. Otherwise it is added to the new table at . After the last column, the table holds exactly the rounded scores with , and sure is .
Since holds exactly when for an integer , the lower bound is , and the upper bound is . The code starts with , as in the paper, and stops after 8 rounds at most. It turns the matrix entries and the threshold into exact fractions, so the rounding and the bounds have no floating-point error; the probabilities are exact when is given as fractions.
Example
Two columns, integer entries. Let with the uniform background and
| A | C | G | T | |
|---|---|---|---|---|
| column 1 | 2 | -1 | -1 | 0 |
| column 2 | -1 | 3 | 0 | -1 |
The sums of one entry from each column give the distribution , , , , , and . For , , from the words AC (score 5) and TC (score 3). The entries lie on the grid of step 0.1, so , , the middle table is empty, and the first round returns as exact.
A log-odds matrix. Take the five sites TCTCGGGG, CCAAGGTG, TACAGGCG, TTCAGGTG and TCCACGTG, the answer of the Rosalind BA2F sample, and form with . The entries take only the values , , , and , for counts 5, 4, 3, 1 and 0. The best score is 11.469, from TCCAGGTG. With the uniform background and :
| round | lo | hi | exact | ||
|---|---|---|---|---|---|
| 1 | 0.1 | 0.251869 | 133 | 178 | no |
| 2 | 0.01 | 0.056503 | 133 | 178 | no |
| 3 | 0.001 | 0.006503 | 133 | 178 | no |
| 4 | 0.0001 | 0.000538 | 178 | 178 | yes |
So , which a count of all 65,536 words confirms. The cause of the slow rounds is that 45 words, such as AACAGGTG, score 6.00267, just above the threshold. Their rounded score falls below 6 until the rounding error is under 0.00267, in round 4. For and , two rounds give the exact values and .
Correctness
Theorem. In every round, . If the middle table is empty, .
Proof sketch. Each entry is rounded down by less than , so . A word with has , so . A word with has , so . ROUND sends each word of positive probability to exactly one of sure, the dropped mass and the final table, and only words with reach the table, so sure and the table give and . If the table is empty, every word is either surely at least or surely below , so .
The loop stops after a finite number of rounds when no word of positive probability scores exactly : once is below the distance from to the nearest score, no rounded score can be in . A word that scores exactly with an entry off every grid keeps the bracket open, which is why the code has a cap on the rounds. The full proof, with the invariant of ROUND, is in proofs/correctness.md. The tests compare the results with a count over all words for up to 5 columns, check the bracket in every round, check ROUND against the full distribution, and check the BA2F values above.
Proof: The rounded dynamic programming brackets the p-value and is exact when its middle table is emptyfull
Let have columns with real entries , let be the background and let . Only words over have positive probability, so all statements below are about these words. Write and . Fix a round with step and let , , and be the values of lines L3 to L6, with the maximum of line L4 over . Write , an integer, and .
Lemma 1 (the rounding error). For every word over , , and .
Proof. By the definition of the floor, . Summing over the columns of gives the first inequality, and each term is at most the maximum of its column, which gives the second. is a sum of numbers in .
Lemma 2 (the integer thresholds). For an integer , if and only if , and if and only if . Also .
Proof. means , and for an integer this means . The same argument gives the second claim. since .
Lemma 3 (ROUND). ROUND returns and a table with for every with and , and no other keys.
Proof. For a word let and let , be the largest and the smallest sums of over the columns after , over , with . Say that is lumped at if is the first column with or , and the first of the two tests holds; dropped at if the second holds at that first column; and kept if neither test holds at any column.
The tests at column depend only on the prefix . By induction on , the table after column maps each to the total probability of the prefixes of length with that are neither lumped nor dropped at a column up to , and sure holds the total probability of the prefixes lumped at a column up to . The step from to takes each kept prefix of length with its probability , extends it by each letter with probability , and applies the two tests in order, which is the rule of ROUND. A prefix lumped or dropped earlier is not extended, and its probability is the sum of the probabilities of all its completions, since the letters are independent and .
If is lumped at , then . If is dropped at , then . If is kept, then at neither test holds, so . These three cases are disjoint and cover every word. A word with is not dropped, since dropped words have , and is not kept, so it is lumped; a word with is neither lumped nor dropped, so it is kept and lands in the table at . So sure is , and the table is the distribution of on . Keys come only from words of positive probability.
Theorem 1 (the bracket). , where and are the values of lines L8 and L9.
Proof. By Lemmas 2 and 3, and . By Lemma 1, implies , and implies . Take probabilities.
Theorem 2 (exact on an empty table). If the table of line L7 is empty, then .
Proof. By Lemma 3, an empty table means that no word of positive probability has , so , that is, . Theorem 1 then gives the claim.
Lemma 4 (the lower bound does not fall). Let be computed with step and with step . Then .
Proof. The number is a point of the grid of step that is at most , and is the largest such point. So every entry of the finer rounded matrix is at least the coarser one, for every word, and .
Theorem 3 (when the loop stops). Suppose that no word of positive probability has , and let be the smallest value of over these words. In every round with , the table is empty. If some word of positive probability has and for every step of the rounds, the table is never empty.
Proof. Let . A word with has and, by Lemma 1, , so . A word with has , since , so . So no word has , and by Lemma 3 the table is empty. For the second claim, such a has , so by Lemma 2, and is in the table by Lemma 3.
Since in round , the first claim gives at most rounds when the cap is not reached. The second claim is why the cap exists. A word with whose entries all lie on the grid has and does no harm.
Cost. After columns every key of the table satisfies , and , so the table has at most keys, and also at most , one per prefix. Each key is extended by letters with dictionary work, so a round is with . The arrays best and worst take to build.
Hardness. Touzet and Varré prove that the problem is NP-hard by a reduction from SUBSET SUM. A simple reduction of this kind: given positive integers and a target , let column have the entry for A and 0 for C, G and T, with the uniform background. The words with are the subsets of the that sum to , so such a subset exists exactly when . So an algorithm that computes in time polynomial in and in the number of bits of the entries would decide SUBSET SUM in polynomial time. The integer entries give and , so the first round of this page is exact here, but its cost is polynomial in , not in the number of bits of , so there is no contradiction.
Complexity
- One round. ROUND does updates for each kept partial score of each column, so time, where is the largest table. The table never holds more than entries after columns.
- The grid bound. All partial scores after columns lie in an integer range of width at most , so and a round costs . This is pseudo-polynomial: it grows with , not with .
- All rounds. Each round makes ten times smaller, so the grid bound of the last round dominates the sum, and rounds cost at most.
- Pruning. Partial scores that are sure to pass or sure to fail leave the table. For thresholds in the far tail, where p-values are small, most partial scores are dropped early.
- Hardness. Touzet and Varré show by a reduction from the subset sum problem that the exact p-value is NP-hard to compute when the entries are given as arbitrary numbers. So no method is polynomial in and in the number of digits of the entries unless P = NP.
Properties
- Exact when it stops. An empty middle table proves the answer. With the cap reached, the result is a proven bracket.
- Floating-point free bounds. The code rounds exact fractions, so the bracket holds for the matrix as given, not for a nearby one.
- The lower bound never falls. Each grid divides the previous one, so a finer grid rounds each entry down by less, and cannot go down from one round to the next. The upper bound has no such guarantee.
- Any background of independent letters. The background enters only as the factor in ROUND.
- The same table gives all thresholds. Without the pruning, the final table is the whole distribution of the rounded score, so a run can answer many thresholds at once.
Variants and improvements
- The full distribution. Drop the pruning and keep all partial scores. This is the generating function , and the code has it as
score_distribution. - The threshold for a p-value. The inverse problem asks for the smallest threshold whose p-value is at most a given level. The full rounded distribution answers it by a scan from the top, with the same bracket on the result.
- Markov backgrounds. A background of order needs the last letters in the state of the table, which multiplies the size by .
- One fixed grid. A simpler method scales the matrix to integers once and accepts the rounding error. The bound of this page tells how large that error can be.
When to use it
Use it to turn matrix scores into p-values when you scan sequences for sites, so that thresholds mean the same for matrices of different lengths and contents. A p-value of a single window does not account for the number of windows scanned; correct for the multiple comparisons, for example with the false discovery rate. For a fixed matrix and many thresholds, compute the distribution once. To judge the quality of a matrix itself, look at its information content.
Pitfalls
- A threshold equal to a score. If some word scores exactly and its entries are not on any grid of step , the bracket never closes. Cap the rounds, or move by a small amount.
- Rounding in floating point. Computing and in floating point can break the bound by a rounding error. The code uses exact fractions for this reason.
- Letters with zero probability. Take the maximum error over the letters that can occur, or is larger than it needs to be.
- Rounding to the nearest point. Rounding to the nearest grid point, not down, gives errors of both signs, and then the bracket needs the error in each direction.
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)
pwm_score_p_value.py 151 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/pwm-score-p-value/. The authors are listed in prov/YNZJ2F.jsonl.
"""The p-value of a weight matrix score, after Touzet and Varre (2007).
The score of a word w = w_1 .. w_L is sum_j M[j][w_j]. Under a background in
which the letters are independent with probabilities p(a), the p-value of a
threshold alpha is P(score >= alpha). The code rounds the matrix down to a
grid of step eps, computes the distribution of the rounded score by dynamic
programming, and gets a lower and an upper bound. When no rounded score falls
between alpha - E and alpha, where E is the largest total rounding error, the
two bounds are equal and the answer is exact. Otherwise eps is divided by 10.
Matrix entries and the threshold are turned into exact fractions (a float
becomes its exact binary value), and eps0 is read as a decimal, so the
rounding and the bounds have no floating-point error. The probabilities keep
the type of p: exact for Fraction, floating point for float.
Columns are 0-based in this code; the page numbers them from 1.
"""
import math
from fractions import Fraction
from typing import Dict, List, NamedTuple, Sequence
from bioseq import DNA
class PValueResult(NamedTuple):
"""lo <= P(score >= alpha) <= hi; exact is True when lo == hi is proved.
eps is the last grid step, error the bound E of that round and rounds the
number of rounds run."""
lo: object
hi: object
exact: bool
eps: Fraction
error: Fraction
rounds: int
def _fraction(x) -> Fraction:
"""The exact value of x as a Fraction (for a float, its exact binary value)."""
if isinstance(x, float) and not math.isfinite(x):
raise ValueError("matrix entries and the threshold must be finite")
return Fraction(x)
def _check(M: Sequence[Sequence], p: Sequence) -> None:
if not M:
raise ValueError("the matrix needs at least one column")
if any(len(row) != len(p) for row in M):
raise ValueError("every column needs one entry per letter")
if any(x < 0 for x in p) or abs(sum(p) - 1) > 1e-9:
raise ValueError("the background must be a probability vector")
def score_distribution(M: Sequence[Sequence], p: Sequence) -> Dict[Fraction, object]:
"""The full distribution {score: probability} of sum_j M[j][w_j], with the
scores as exact fractions. It has at most |alphabet|^L entries."""
_check(M, p)
Q: Dict[Fraction, object] = {Fraction(0): 1}
for row in M:
R: Dict[Fraction, object] = {}
for s, q in Q.items():
for a, w in enumerate(row):
if p[a] > 0:
t = s + _fraction(w)
R[t] = R.get(t, 0) + q * p[a]
Q = R
return Q
def pvalue_round(N: Sequence[Sequence[int]], p: Sequence, A: int, B: int):
"""One round on an integer matrix N with B <= A.
Returns (sure, middle): sure = P(sum N >= A) and middle = {s: P(sum N = s)}
for the scores B <= s < A. Partial scores that reach A whatever the next
letters are moved into sure; those that cannot reach B are dropped.
"""
L = len(N)
best = [0] * (L + 1)
worst = [0] * (L + 1)
for j in range(L - 1, -1, -1):
allowed = [N[j][a] for a in range(len(p)) if p[a] > 0]
best[j] = best[j + 1] + max(allowed)
worst[j] = worst[j + 1] + min(allowed)
sure = 0
Q: Dict[int, object] = {0: 1}
for j in range(L):
R: Dict[int, object] = {}
for s, q in Q.items():
for a in range(len(p)):
if p[a] == 0:
continue
t = s + N[j][a]
if t + worst[j + 1] >= A:
sure += q * p[a]
elif t + best[j + 1] >= B:
R[t] = R.get(t, 0) + q * p[a]
Q = R
return sure, Q
def pwm_score_p_value(M: Sequence[Sequence], p: Sequence, alpha, eps0="0.1",
max_rounds: int = 8) -> PValueResult:
"""Bounds on P(score >= alpha) for a matrix M[j][a] and background p.
eps starts at eps0 and is divided by 10 after each round that does not
prove the answer exact, for at most max_rounds rounds.
"""
_check(M, p)
if max_rounds < 1:
raise ValueError("max_rounds must be at least 1")
F = [[_fraction(w) for w in row] for row in M]
alpha = _fraction(alpha)
eps = Fraction(repr(eps0)) if isinstance(eps0, float) else Fraction(eps0) # @line L1
if eps <= 0:
raise ValueError("eps0 must be positive")
rounds = 0
while True: # @line L2
rounds += 1
N = [[math.floor(w / eps) for w in row] for row in F] # @line L3
E = sum(max(w - eps * n for w, n, pa in zip(row, nrow, p) if pa > 0) # @line L4
for row, nrow in zip(F, N))
A = math.ceil(alpha / eps) # @line L5
B = math.ceil((alpha - E) / eps) # @line L6
sure, middle = pvalue_round(N, p, A, B) # @line L7
lo = sure # @line L8
hi = sure + sum(middle.values()) # @line L9
if not middle or rounds == max_rounds: # @line L10
return PValueResult(lo, hi, not middle, eps, E, rounds) # @line L11
eps /= 10 # @line L12
def log_odds_matrix(sites: Sequence[str], p: Sequence[float], pseudo: float = 1.0) -> List[List[float]]:
"""M[j][a] = log2(((count + pseudo p(a)) / (n + pseudo)) / p(a)) from aligned sites over ACGT."""
if not sites or len({len(s) for s in sites}) != 1:
raise ValueError("need aligned sites of one length")
n = len(sites)
M = []
for j in range(len(sites[0])):
col = [s[j] for s in sites]
M.append([math.log2(((col.count(a) + pseudo * p[i]) / (n + pseudo)) / p[i]) for i, a in enumerate(DNA)])
return M
def score(M: Sequence[Sequence], word: str):
"""The score sum_j M[j][word_j] of a word over ACGT."""
if len(word) != len(M):
raise ValueError("the word length must equal the number of columns")
return sum(M[j][DNA.index(c)] for j, c in enumerate(word))
test_pwm_score_p_value.py 173 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/pwm-score-p-value/. The authors are listed in prov/YNZJ2F.jsonl.
import itertools
import math
import random
from fractions import Fraction
import pytest
from bioseq import DNA
from pwm_score_p_value import (log_odds_matrix, pvalue_round, pwm_score_p_value, score, score_distribution)
BA2F_SITES = ["TCTCGGGG", "CCAAGGTG", "TACAGGCG", "TTCAGGTG", "TCCACGTG"]
UNIFORM = [Fraction(1, 4)] * 4
def brute_force(M, p, alpha):
"""P(score >= alpha) by listing all words, in exact arithmetic."""
alpha = Fraction(alpha)
total = 0
for w in itertools.product(range(4), repeat=len(M)):
if sum(Fraction(M[j][a]) for j, a in enumerate(w)) >= alpha:
pr = 1
for a in w:
pr *= p[a]
total += pr
return total
def random_matrix(rng, L, integer=False):
if integer:
return [[rng.randint(-3, 3) for _ in range(4)] for _ in range(L)]
return [[rng.uniform(-3, 2) for _ in range(4)] for _ in range(L)]
def random_background(rng):
w = [Fraction(rng.randint(1, 9)) for _ in range(4)]
return [x / sum(w) for x in w]
def test_small_example():
M = [[2, -1, -1, 0], [-1, 3, 0, -1]]
dist = score_distribution(M, UNIFORM)
assert dist == {-2: Fraction(1, 4), -1: Fraction(1, 4), 0: Fraction(1, 16), 1: Fraction(1, 8),
2: Fraction(3, 16), 3: Fraction(1, 16), 5: Fraction(1, 16)}
r = pwm_score_p_value(M, UNIFORM, 3)
assert r.exact and r.lo == r.hi == Fraction(1, 8) and r.rounds == 1 and r.error == 0
def test_against_brute_force():
# Real matrices, exact backgrounds, thresholds at random and at word scores.
rng = random.Random(1)
for _ in range(40):
L = rng.randint(1, 5)
M = random_matrix(rng, L)
p = random_background(rng)
words = ["".join(rng.choice(DNA) for _ in range(L)) for _ in range(2)]
for alpha in [rng.uniform(-3 * L, 2 * L)] + [score(M, w) for w in words]:
truth = brute_force(M, p, alpha)
r = pwm_score_p_value(M, p, alpha, max_rounds=12)
assert r.lo <= truth <= r.hi
if r.exact:
assert r.lo == r.hi == truth
def test_every_round_brackets_the_truth():
rng = random.Random(2)
for _ in range(25):
L = rng.randint(2, 5)
M = random_matrix(rng, L)
alpha = rng.uniform(-L, 2 * L)
truth = brute_force(M, UNIFORM, alpha)
last_lo = 0
for k in range(1, 5):
r = pwm_score_p_value(M, UNIFORM, alpha, max_rounds=k)
assert r.lo <= truth <= r.hi
assert r.error < L * r.eps
# The finer grid rounds each entry down by less, so lo cannot fall.
assert r.lo >= last_lo
last_lo = r.lo
if r.exact:
break
def test_integer_matrix_is_exact_in_one_round():
rng = random.Random(3)
for _ in range(20):
M = random_matrix(rng, rng.randint(1, 5), integer=True)
alpha = rng.randint(-6, 8)
r = pwm_score_p_value(M, UNIFORM, alpha)
assert r.exact and r.rounds == 1 and r.error == 0
assert r.lo == brute_force(M, UNIFORM, alpha)
def test_pruned_round_equals_full_distribution():
# pvalue_round drops and lumps partial scores; the result must match the full table.
rng = random.Random(4)
for _ in range(30):
N = random_matrix(rng, rng.randint(1, 6), integer=True)
p = random_background(rng)
B = rng.randint(-8, 6)
A = B + rng.randint(0, 4)
sure, middle = pvalue_round(N, p, A, B)
dist = score_distribution(N, p)
assert sure == sum(q for s, q in dist.items() if s >= A)
assert middle == {int(s): q for s, q in dist.items() if B <= s < A}
def test_distribution_sums_to_one_and_p_value_falls():
rng = random.Random(5)
M = random_matrix(rng, 4)
p = random_background(rng)
dist = score_distribution(M, p)
assert sum(dist.values()) == 1
scores = sorted(dist)
tail = 1
for s in scores:
# P(score >= s) from the table, and the algorithm at the same threshold.
# A word scores exactly s and its entries are off the grid, so the
# bracket cannot close; two rounds are enough to check it.
r = pwm_score_p_value(M, p, s, max_rounds=2)
assert r.lo <= tail <= r.hi
assert not r.exact
tail -= dist[s]
assert tail == 0
values = [pwm_score_p_value(M, p, a / 4).hi for a in range(-48, 32)]
assert all(x >= y for x, y in zip(values, values[1:]))
def test_ba2f_log_odds():
M = log_odds_matrix(BA2F_SITES, [0.25] * 4)
assert abs(M[0][DNA.index("T")] - math.log2((4.25 / 6) / 0.25)) < 1e-12
truth = {4.0: Fraction(586, 65536), 6.0: Fraction(178, 65536), 8.0: Fraction(40, 65536)}
rounds = {4.0: 2, 6.0: 4, 8.0: 2}
for alpha, value in truth.items():
r = pwm_score_p_value(M, UNIFORM, alpha)
assert r.exact and r.lo == value and r.rounds == rounds[alpha]
count = sum(1 for w in itertools.product(DNA, repeat=8) if score(M, "".join(w)) >= 6.0)
assert count == 178
def test_zero_background_letter():
M = [[1, 5, 0, 0], [2, 0, 7, 0]]
p = [Fraction(1, 2), 0, Fraction(1, 2), 0]
r = pwm_score_p_value(M, p, 4)
assert r.exact and r.lo == brute_force(M, p, 4) == Fraction(1, 2)
def test_float_background():
rng = random.Random(6)
M = random_matrix(rng, 4)
p = [0.1, 0.4, 0.3, 0.2]
r = pwm_score_p_value(M, p, 0.5, max_rounds=12)
truth = brute_force(M, [Fraction(x) for x in p], 0.5)
assert r.exact and abs(r.lo - truth) < 1e-12
def test_errors():
with pytest.raises(ValueError):
pwm_score_p_value([], UNIFORM, 0)
with pytest.raises(ValueError):
pwm_score_p_value([[1, 2, 3]], UNIFORM, 0)
with pytest.raises(ValueError):
pwm_score_p_value([[1, 2, 3, 4]], [0.5, 0.5, 0.5, 0.5], 0)
with pytest.raises(ValueError):
pwm_score_p_value([[1, 2, 3, 4]], UNIFORM, 0, eps0=0)
with pytest.raises(ValueError):
pwm_score_p_value([[1, 2, 3, 4]], UNIFORM, 0, max_rounds=0)
with pytest.raises(ValueError):
pwm_score_p_value([[1, 2, float("inf"), 4]], UNIFORM, 0)
with pytest.raises(ValueError):
log_odds_matrix(["ACG", "AC"], [0.25] * 4)
History
Staden (1989) gave methods for the probability of finding a pattern in a random sequence. Touzet and Varré (2007) rounded the weight matrix to a grid, bounded the error of the rounded matrix, used the bound to decide when the rounded answer is exact, refined the grid when it is not, and showed that the general problem is NP-hard.
References
- Hélène Touzet and Jean-Stéphane Varré, Efficient and accurate P-value computation for Position Weight Matrices, Algorithms for Molecular Biology 2, article 15, 2007, the rounded matrix, the bound on the rounding error, the stopping rule, the cost of the dynamic programming and the NP-hardness by a reduction from SUBSET SUM
- Rodger Staden, Methods for calculating the probabilities of finding patterns in sequences, Computer Applications in the Biosciences 5(2), 1989, pp. 89 to 96, the probability of a pattern match in a random sequence
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 YNZJ2F Edit this page History Report an error Markdown