Algorithm Search⌘K

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
Origin
Hélène Touzet, Jean Stéphane Varré, 2007

A position weight matrix gives a score to each word of length LL, and a site is reported when the score reaches a threshold α\alpha. The p-value of α\alpha is the chance that a random word from the background scores at least α\alpha. For small LL you can list all 4L4^L words, but for a matrix of 20 columns this is 101210^{12} words. The method of Touzet and Varré (2007) rounds the matrix entries down to a grid of step ε\varepsilon, 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 EE. A word whose rounded score is at least α\alpha surely passes. A word whose rounded score is below α−E\alpha - E 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 MM with LL columns and one real entry Mj(a)M_j(a) for each column jj and letter aa, a background p(a)≥0p(a) \ge 0 with ∑ap(a)=1\sum_a p(a) = 1, and a threshold α\alpha. The score of a word w=w1⋯wLw = w_1 \cdots w_L is S(w)=∑j=1LMj(wj)S(w) = \sum_{j=1}^{L} M_j(w_j), and the letters of a random word are independent with probabilities pp. Columns are numbered from 1 on this page and from 0 in the code.

Output. P(α)=Pr⁡[S(w)≥α]P(\alpha) = \Pr[S(w) \ge \alpha], or bounds lo≤P(α)≤hi\mathrm{lo} \le P(\alpha) \le \mathrm{hi} when a cap on the rounds is reached.

The algorithm

For a grid step ε>0\varepsilon > 0, let Nj(a)=⌊Mj(a)/ε⌋N_j(a) = \lfloor M_j(a)/\varepsilon \rfloor, an integer, and let the rounded score be Sε(w)=ε∑jNj(wj)S_\varepsilon(w) = \varepsilon \sum_j N_j(w_j). The largest rounding error is E=∑jmax⁡a(Mj(a)−εNj(a))E = \sum_j \max_a (M_j(a) - \varepsilon N_j(a)), with the maximum over the letters with p(a)>0p(a) > 0. Then Sε(w)≤S(w)≤Sε(w)+ES_\varepsilon(w) \le S(w) \le S_\varepsilon(w) + E for every word of positive probability.

  1. PWM-P-VALUE(M, p, α, ε0, rounds)
  2. 1ε ← ε0
  3. 2repeat
  4. 3N_j(a) ← ⌊M_j(a) / ε⌋ for every column j and letter a
  5. 4E ← Σ_j max_a (M_j(a) - ε N_j(a))
  6. 5A ← ⌈α / ε⌉
  7. 6B ← ⌈(α - E) / ε⌉
  8. 7(sure, middle) ← ROUND(N, p, A, B)
  9. 8lo ← sure
  10. 9hi ← sure + Σ_s middle[s]
  11. 10if middle is empty or this was the last allowed round then
  12. 11return lo, hi and whether middle is empty
  13. 12ε ← ε / 10

ROUND is the dynamic programming of line L7. It keeps a table QQ from integer partial scores to probabilities, starting with Q={0:1}Q = \{0 : 1\}. For column jj, each entry (t,q)(t, q) of QQ and each letter aa, it forms t′=t+Nj(a)t' = t + N_j(a) with probability q p(a)q\,p(a). Let bestj\mathrm{best}_j and worstj\mathrm{worst}_j be the largest and the smallest sums of NN over the columns after jj. If t′+worstj≥At' + \mathrm{worst}_j \ge A, every completion reaches AA, so q p(a)q\,p(a) is added to sure. If t′+bestj<Bt' + \mathrm{best}_j < B, no completion reaches BB, and the mass is dropped. Otherwise it is added to the new table at t′t'. After the last column, the table holds exactly the rounded scores ss with B≤s<AB \le s < A, and sure is Pr⁡[∑jNj(wj)≥A]\Pr[\sum_j N_j(w_j) \ge A].

Since εs≥α\varepsilon s \ge \alpha holds exactly when s≥As \ge A for an integer ss, the lower bound is lo=Pr⁡[Sε≥α]≤P(α)\mathrm{lo} = \Pr[S_\varepsilon \ge \alpha] \le P(\alpha), and the upper bound is hi=Pr⁡[Sε≥α−E]≥P(α)\mathrm{hi} = \Pr[S_\varepsilon \ge \alpha - E] \ge P(\alpha). The code starts with ε0=0.1\varepsilon_0 = 0.1, 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 pp is given as fractions.

Example

Two columns, integer entries. Let L=2L = 2 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 Pr⁡[S=−2]=1/4\Pr[S = -2] = 1/4, Pr⁡[S=−1]=1/4\Pr[S = -1] = 1/4, Pr⁡[S=0]=1/16\Pr[S = 0] = 1/16, Pr⁡[S=1]=1/8\Pr[S = 1] = 1/8, Pr⁡[S=2]=3/16\Pr[S = 2] = 3/16, Pr⁡[S=3]=1/16\Pr[S = 3] = 1/16 and Pr⁡[S=5]=1/16\Pr[S = 5] = 1/16. For α=3\alpha = 3, P(3)=1/16+1/16=1/8P(3) = 1/16 + 1/16 = 1/8, from the words AC (score 5) and TC (score 3). The entries lie on the grid of step 0.1, so E=0E = 0, A=B=30A = B = 30, the middle table is empty, and the first round returns 1/81/8 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 Mj(a)=log⁡2(fj(a)/0.25)M_j(a) = \log_2(f_j(a)/0.25) with fj(a)=(count+0.25)/6f_j(a) = (\text{count} + 0.25)/6. The entries take only the values log⁡2(21/6)=1.807\log_2(21/6) = 1.807, log⁡2(17/6)=1.503\log_2(17/6) = 1.503, log⁡2(13/6)=1.115\log_2(13/6) = 1.115, log⁡2(5/6)=−0.263\log_2(5/6) = -0.263 and log⁡2(1/6)=−2.585\log_2(1/6) = -2.585, for counts 5, 4, 3, 1 and 0. The best score is 11.469, from TCCAGGTG. With the uniform background and α=6\alpha = 6:

round ε\varepsilon EE lo ⋅48\cdot 4^8 hi ⋅48\cdot 4^8 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 P(6)=178/65536≈0.00272P(6) = 178/65536 \approx 0.00272, 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 α=4\alpha = 4 and α=8\alpha = 8, two rounds give the exact values 586/65536586/65536 and 40/6553640/65536.

Correctness

Theorem. In every round, lo≤P(α)≤hi\mathrm{lo} \le P(\alpha) \le \mathrm{hi}. If the middle table is empty, lo=P(α)=hi\mathrm{lo} = P(\alpha) = \mathrm{hi}.

Proof sketch. Each entry is rounded down by less than ε\varepsilon, so Sε(w)≤S(w)≤Sε(w)+ES_\varepsilon(w) \le S(w) \le S_\varepsilon(w) + E. A word with Sε(w)≥αS_\varepsilon(w) \ge \alpha has S(w)≥αS(w) \ge \alpha, so lo≤P(α)\mathrm{lo} \le P(\alpha). A word with S(w)≥αS(w) \ge \alpha has Sε(w)≥α−ES_\varepsilon(w) \ge \alpha - E, so P(α)≤hiP(\alpha) \le \mathrm{hi}. ROUND sends each word of positive probability to exactly one of sure, the dropped mass and the final table, and only words with B≤∑N<AB \le \sum N < A reach the table, so sure and the table give lo\mathrm{lo} and hi−lo\mathrm{hi} - \mathrm{lo}. If the table is empty, every word is either surely at least α\alpha or surely below α−E≤α\alpha - E \le \alpha, so lo=hi\mathrm{lo} = \mathrm{hi}. □\square

The loop stops after a finite number of rounds when no word of positive probability scores exactly α\alpha: once LεL\varepsilon is below the distance from α\alpha to the nearest score, no rounded score can be in [α−E,α)[\alpha - E, \alpha). A word that scores exactly α\alpha 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 MM have columns j=1,…,Lj = 1, \ldots, L with real entries Mj(a)M_j(a), let pp be the background and let Σ+={a:p(a)>0}\Sigma^+ = \{a : p(a) > 0\}. Only words over Σ+\Sigma^+ have positive probability, so all statements below are about these words. Write S(w)=∑jMj(wj)S(w) = \sum_j M_j(w_j) and P(α)=Pr⁡[S(w)≥α]P(\alpha) = \Pr[S(w) \ge \alpha]. Fix a round with step ε>0\varepsilon > 0 and let NN, EE, AA and BB be the values of lines L3 to L6, with the maximum of line L4 over Σ+\Sigma^+. Write T(w)=∑jNj(wj)T(w) = \sum_j N_j(w_j), an integer, and Sε(w)=εT(w)S_\varepsilon(w) = \varepsilon T(w).

Lemma 1 (the rounding error). For every word ww over Σ+\Sigma^+, Sε(w)≤S(w)≤Sε(w)+ES_\varepsilon(w) \le S(w) \le S_\varepsilon(w) + E, and 0≤E<Lε0 \le E < L\varepsilon.

Proof. By the definition of the floor, 0≤Mj(a)−εNj(a)<ε0 \le M_j(a) - \varepsilon N_j(a) < \varepsilon. Summing over the columns of ww gives the first inequality, and each term is at most the maximum of its column, which gives the second. EE is a sum of LL numbers in [0,ε)[0, \varepsilon). □\square

Lemma 2 (the integer thresholds). For an integer ss, εs≥α\varepsilon s \ge \alpha if and only if s≥As \ge A, and εs≥α−E\varepsilon s \ge \alpha - E if and only if s≥Bs \ge B. Also B≤AB \le A.

Proof. εs≥α\varepsilon s \ge \alpha means s≥α/εs \ge \alpha/\varepsilon, and for an integer ss this means s≥⌈α/ε⌉=As \ge \lceil \alpha/\varepsilon \rceil = A. The same argument gives the second claim. B≤AB \le A since E≥0E \ge 0. □\square

Lemma 3 (ROUND). ROUND returns sure=Pr⁡[T(w)≥A]\mathrm{sure} = \Pr[T(w) \ge A] and a table with middle[s]=Pr⁡[T(w)=s]\mathrm{middle}[s] = \Pr[T(w) = s] for every ss with B≤s<AB \le s < A and Pr⁡[T(w)=s]>0\Pr[T(w) = s] > 0, and no other keys.

Proof. For a word ww let tj(w)=∑i≤jNi(wi)t_j(w) = \sum_{i \le j} N_i(w_i) and let bestj\mathrm{best}_j, worstj\mathrm{worst}_j be the largest and the smallest sums of NN over the columns after jj, over Σ+\Sigma^+, with bestL=worstL=0\mathrm{best}_L = \mathrm{worst}_L = 0. Say that ww is lumped at jj if jj is the first column with tj(w)+worstj≥At_j(w) + \mathrm{worst}_j \ge A or tj(w)+bestj<Bt_j(w) + \mathrm{best}_j < B, and the first of the two tests holds; dropped at jj if the second holds at that first column; and kept if neither test holds at any column.

The tests at column jj depend only on the prefix w1⋯wjw_1 \cdots w_j. By induction on jj, the table after column jj maps each tt to the total probability of the prefixes of length jj with tj=tt_j = t that are neither lumped nor dropped at a column up to jj, and sure holds the total probability of the prefixes lumped at a column up to jj. The step from j−1j - 1 to jj takes each kept prefix of length j−1j - 1 with its probability qq, extends it by each letter a∈Σ+a \in \Sigma^+ with probability q p(a)q\,p(a), 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 ∑a∈Σ+p(a)=1\sum_{a \in \Sigma^+} p(a) = 1.

If ww is lumped at jj, then T(w)≥tj(w)+worstj≥AT(w) \ge t_j(w) + \mathrm{worst}_j \ge A. If ww is dropped at jj, then T(w)≤tj(w)+bestj<BT(w) \le t_j(w) + \mathrm{best}_j < B. If ww is kept, then at j=Lj = L neither test holds, so B≤T(w)<AB \le T(w) < A. These three cases are disjoint and cover every word. A word with T(w)≥AT(w) \ge A is not dropped, since dropped words have T<B≤AT < B \le A, and is not kept, so it is lumped; a word with B≤T(w)<AB \le T(w) < A is neither lumped nor dropped, so it is kept and lands in the table at T(w)T(w). So sure is Pr⁡[T≥A]\Pr[T \ge A], and the table is the distribution of TT on [B,A)[B, A). Keys come only from words of positive probability. □\square

Theorem 1 (the bracket). lo≤P(α)≤hi\mathrm{lo} \le P(\alpha) \le \mathrm{hi}, where lo\mathrm{lo} and hi\mathrm{hi} are the values of lines L8 and L9.

Proof. By Lemmas 2 and 3, lo=Pr⁡[T≥A]=Pr⁡[Sε≥α]\mathrm{lo} = \Pr[T \ge A] = \Pr[S_\varepsilon \ge \alpha] and hi=Pr⁡[T≥B]=Pr⁡[Sε≥α−E]\mathrm{hi} = \Pr[T \ge B] = \Pr[S_\varepsilon \ge \alpha - E]. By Lemma 1, Sε(w)≥αS_\varepsilon(w) \ge \alpha implies S(w)≥αS(w) \ge \alpha, and S(w)≥αS(w) \ge \alpha implies Sε(w)≥S(w)−E≥α−ES_\varepsilon(w) \ge S(w) - E \ge \alpha - E. Take probabilities. □\square

Theorem 2 (exact on an empty table). If the table of line L7 is empty, then lo=P(α)=hi\mathrm{lo} = P(\alpha) = \mathrm{hi}.

Proof. By Lemma 3, an empty table means that no word of positive probability has B≤T(w)<AB \le T(w) < A, so Pr⁡[T≥B]=Pr⁡[T≥A]\Pr[T \ge B] = \Pr[T \ge A], that is, hi=lo\mathrm{hi} = \mathrm{lo}. Theorem 1 then gives the claim. □\square

Lemma 4 (the lower bound does not fall). Let lo\mathrm{lo} be computed with step ε\varepsilon and lo′\mathrm{lo}' with step ε/10\varepsilon/10. Then lo′≥lo\mathrm{lo}' \ge \mathrm{lo}.

Proof. The number ε⌊x/ε⌋\varepsilon \lfloor x/\varepsilon \rfloor is a point of the grid of step ε/10\varepsilon/10 that is at most xx, and (ε/10)⌊10x/ε⌋(\varepsilon/10) \lfloor 10x/\varepsilon \rfloor is the largest such point. So every entry of the finer rounded matrix is at least the coarser one, Sε/10(w)≥Sε(w)S_{\varepsilon/10}(w) \ge S_\varepsilon(w) for every word, and Pr⁡[Sε/10≥α]≥Pr⁡[Sε≥α]\Pr[S_{\varepsilon/10} \ge \alpha] \ge \Pr[S_\varepsilon \ge \alpha]. □\square

Theorem 3 (when the loop stops). Suppose that no word of positive probability has S(w)=αS(w) = \alpha, and let δ>0\delta > 0 be the smallest value of ∣S(w)−α∣|S(w) - \alpha| over these words. In every round with Lε≤δL\varepsilon \le \delta, the table is empty. If some word ww of positive probability has S(w)=αS(w) = \alpha and Sε(w)<αS_\varepsilon(w) < \alpha for every step ε\varepsilon of the rounds, the table is never empty.

Proof. Let Lε≤δL\varepsilon \le \delta. A word with S(w)>αS(w) > \alpha has S(w)≥α+δS(w) \ge \alpha + \delta and, by Lemma 1, Sε(w)>S(w)−Lε≥αS_\varepsilon(w) > S(w) - L\varepsilon \ge \alpha, so T(w)≥AT(w) \ge A. A word with S(w)<αS(w) < \alpha has Sε(w)≤S(w)≤α−δ<α−ES_\varepsilon(w) \le S(w) \le \alpha - \delta < \alpha - E, since E<Lε≤δE < L\varepsilon \le \delta, so T(w)<BT(w) < B. So no word has B≤T(w)<AB \le T(w) < A, and by Lemma 3 the table is empty. For the second claim, such a ww has α−E≤S(w)−E≤Sε(w)<α\alpha - E \le S(w) - E \le S_\varepsilon(w) < \alpha, so B≤T(w)<AB \le T(w) < A by Lemma 2, and ww is in the table by Lemma 3. □\square

Since ε=ε010−(r−1)\varepsilon = \varepsilon_0 10^{-(r-1)} in round rr, the first claim gives at most 1+⌈log⁡10(Lε0/δ)⌉1 + \lceil \log_{10}(L\varepsilon_0/\delta) \rceil rounds when the cap is not reached. The second claim is why the cap exists. A word with S(w)=αS(w) = \alpha whose entries all lie on the grid has Sε(w)=S(w)S_\varepsilon(w) = S(w) and does no harm.

Cost. After jj columns every key tt of the table satisfies ∑i≤jmin⁡aNi(a)≤t≤∑i≤jmax⁡aNi(a)\sum_{i \le j} \min_a N_i(a) \le t \le \sum_{i \le j} \max_a N_i(a), and max⁡aNi(a)−min⁡aNi(a)≤R/ε+1\max_a N_i(a) - \min_a N_i(a) \le R/\varepsilon + 1, so the table has at most j(R/ε+1)+1j(R/\varepsilon + 1) + 1 keys, and also at most cjc^j, one per prefix. Each key is extended by cc letters with O(1)O(1) dictionary work, so a round is O(LcS)O(LcS) with S=O(min⁡(cL,LR/ε))S = O(\min(c^L, LR/\varepsilon)). The arrays best and worst take O(Lc)O(Lc) 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 x1,…,xLx_1, \ldots, x_L and a target tt, let column jj have the entry xjx_j for A and 0 for C, G and T, with the uniform background. The words with S(w)=tS(w) = t are the subsets of the xjx_j that sum to tt, so such a subset exists exactly when P(t)−P(t+1)>0P(t) - P(t + 1) > 0. So an algorithm that computes PP in time polynomial in LL and in the number of bits of the entries would decide SUBSET SUM in polynomial time. The integer entries give E=0E = 0 and A=BA = B, so the first round of this page is exact here, but its cost is polynomial in R/εR/\varepsilon, not in the number of bits of RR, so there is no contradiction.

Complexity

  • One round. ROUND does cc updates for each kept partial score of each column, so O(LcS)O(L c S) time, where SS is the largest table. The table never holds more than cjc^j entries after jj columns.
  • The grid bound. All partial scores after jj columns lie in an integer range of width at most jR/ε+jjR/\varepsilon + j, so S=O(LR/ε)S = O(LR/\varepsilon) and a round costs O(L2cR/ε)O(L^2 c R/\varepsilon). This is pseudo-polynomial: it grows with 1/ε1/\varepsilon, not with log⁡(1/ε)\log(1/\varepsilon).
  • All rounds. Each round makes ε\varepsilon ten times smaller, so the grid bound of the last round dominates the sum, and rr rounds cost O(rLcS)O(r L c S) 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 LL 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 lo\mathrm{lo} 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 p(a)p(a) 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 ∏j∑ap(a)xNj(a)\prod_j \sum_a p(a) x^{N_j(a)}, 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 kk needs the last kk letters in the state of the table, which multiplies the size by ckc^k.
  • One fixed grid. A simpler method scales the matrix to integers once and accepts the rounding error. The bound EE 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 α\alpha and its entries are not on any grid of step 10−r10^{-r}, the bracket never closes. Cap the rounds, or move α\alpha by a small amount.
  • Rounding in floating point. Computing ⌊M/ε⌋\lfloor M/\varepsilon \rfloor and EE in floating point can break the bound Sε≤S≤Sε+ES_\varepsilon \le S \le S_\varepsilon + E 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 EE 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.

bioseq.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Shared helper of the biology pages of https://algorithm.tamnd.com/. The authors are listed in prov/.
"""Small DNA utilities shared by the biology pages.

Conventions:
- DNA is a str over "ACGT", written 5' to 3'. Positions are 0-based.
- Random draws use a random.Random object that the caller passes in, and the
  order of the draws is fixed and written in each docstring, so that a seed
  gives the same output on every run.
- Alignment scores are added: pass match as a positive number and mismatch and
  gap as negative numbers. A CIGAR string uses M (a column with a base of both
  strings, equal or not), I (a base of a, the query, against a gap) and D (a
  base of b, the reference, against a gap).

This module holds no algorithm of a page: no ORF finder, no motif finder and
no caller. The functions are building blocks for the page code and its tests.
"""

from __future__ import annotations

import math
import random
from collections import namedtuple
from typing import Dict, List, Sequence, Tuple, Union

DNA = "ACGT"

_COMPLEMENT = {"A": "T", "C": "G", "G": "C", "T": "A", "N": "N",
               "a": "t", "c": "g", "g": "c", "t": "a", "n": "n"}


def revcomp(seq: str) -> str:
    """The reverse complement of seq. N maps to N; other letters raise KeyError."""
    return "".join(_COMPLEMENT[c] for c in reversed(seq))


# NCBI genetic code table 1 (the standard code), in the TCAG order of the NCBI
# listing: the first base changes slowest and the third base fastest.
_AAS = "FFLLSSSSYY**CC*WLLLLPPPPHHQQRRRRIIIMTTTTNNKKSSRRVVVVAAAADDEEGGGG"
_ORDER = "TCAG"
CODON_TABLE: Dict[str, str] = {
    a + b + c: _AAS[16 * i + 4 * j + k]
    for i, a in enumerate(_ORDER)
    for j, b in enumerate(_ORDER)
    for k, c in enumerate(_ORDER)
}
STOPS = frozenset(c for c, aa in CODON_TABLE.items() if aa == "*")


def translate(seq: str, frame: int = 0) -> str:
    """Translate seq[frame:] codon by codon with CODON_TABLE.

    frame is 0, 1 or 2. A stop codon gives "*", a codon with a letter other than
    A, C, G or T gives "X", and a last part shorter than three bases is dropped.
    The function does not look for start or stop codons.
    """
    if frame not in (0, 1, 2):
        raise ValueError("frame must be 0, 1 or 2")
    s = seq.upper()
    out = []
    for i in range(frame, len(s) - 2, 3):
        out.append(CODON_TABLE.get(s[i:i + 3], "X"))
    return "".join(out)


def random_dna(rng: random.Random, n: int, gc: float = 0.5) -> str:
    """n random bases, independent, with P(G) = P(C) = gc/2 and P(A) = P(T) = (1 - gc)/2.

    Draw order: one rng.random() per base, from left to right.
    """
    if not 0.0 <= gc <= 1.0:
        raise ValueError("gc must be in [0, 1]")
    half_gc, cut = gc / 2.0, gc + (1.0 - gc) / 2.0
    out = []
    for _ in range(n):
        u = rng.random()
        if u < half_gc:
            out.append("C")
        elif u < gc:
            out.append("G")
        elif u < cut:
            out.append("A")
        else:
            out.append("T")
    return "".join(out)


def _other_base(rng: random.Random, base: str) -> str:
    """A base other than base, uniform among the other three (one rng.choice)."""
    return rng.choice([b for b in DNA if b != base])


def mutate(rng: random.Random, seq: str, rate: float) -> str:
    """Substitute each base with probability rate, uniformly by one of the other three.

    Draw order: for each position from left to right, one rng.random(); if it is
    below rate, one rng.choice for the new base. Letters other than A, C, G and T
    are kept and use no draw. No insertions or deletions.
    """
    out = []
    for c in seq:
        if c in DNA and rng.random() < rate:
            out.append(_other_base(rng, c))
        else:
            out.append(c)
    return "".join(out)


SimRead = namedtuple("SimRead", ["read", "pos", "strand", "true_seq"])


def simulate_reads(rng: random.Random, genome: str, n: int, length: int,
                   error_rate: float) -> List[SimRead]:
    """n single-end reads of the given length from both strands of genome.

    Each item is SimRead(read, pos, strand, true_seq): pos is the 0-based start
    of the read on the forward strand of genome, strand is "+" or "-", true_seq
    is the error-free read (genome[pos:pos + length], or its reverse complement
    for "-"), and read is true_seq with substitution errors at rate error_rate.

    Draw order for each read: rng.randrange(len(genome) - length + 1) for pos,
    then rng.random() < 0.5 for the "+" strand, then the draws of mutate on
    true_seq.
    """
    if length > len(genome) or length <= 0:
        raise ValueError("need 0 < length <= len(genome)")
    reads = []
    for _ in range(n):
        pos = rng.randrange(len(genome) - length + 1)
        strand = "+" if rng.random() < 0.5 else "-"
        frag = genome[pos:pos + length]
        true_seq = frag if strand == "+" else revcomp(frag)
        reads.append(SimRead(mutate(rng, true_seq, error_rate), pos, strand, true_seq))
    return reads


def phred_to_prob(q: float) -> float:
    """Error probability of the Phred score q: p = 10^(-q/10)."""
    return 10.0 ** (-q / 10.0)


def prob_to_phred(p: float) -> float:
    """Phred score of the error probability p in (0, 1]: Q = -10 log10(p)."""
    if not 0.0 < p <= 1.0:
        raise ValueError("p must be in (0, 1]")
    return -10.0 * math.log10(p)


def hamming(a: Sequence, b: Sequence) -> int:
    """The number of positions where a and b differ; they must have the same length."""
    if len(a) != len(b):
        raise ValueError("hamming needs sequences of equal length")
    return sum(1 for x, y in zip(a, b) if x != y)


def kmers(seq: str, k: int) -> List[str]:
    """All len(seq) - k + 1 substrings of length k, from left to right (with repeats)."""
    if k <= 0:
        raise ValueError("k must be positive")
    return [seq[i:i + k] for i in range(len(seq) - k + 1)]


def gc_content(seq: str) -> float:
    """The fraction of G and C letters in seq (upper or lower case); 0.0 for an empty seq."""
    if not seq:
        return 0.0
    s = seq.upper()
    return (s.count("G") + s.count("C")) / len(s)


Number = Union[int, float]


def _cigar(ops: List[str]) -> str:
    """Run-length code a list of single-letter operations, for example MMMID to 3M1I1D."""
    out = []
    i = 0
    while i < len(ops):
        j = i
        while j < len(ops) and ops[j] == ops[i]:
            j += 1
        out.append(f"{j - i}{ops[i]}")
        i = j
    return "".join(out)


def _fill(a: str, b: str, match: Number, mismatch: Number, gap: Number, free_b_ends: bool):
    """The dynamic programming table of a linear gap alignment of a and b."""
    n, m = len(a), len(b)
    S = [[0] * (m + 1) for _ in range(n + 1)]
    for i in range(1, n + 1):
        S[i][0] = i * gap
    for j in range(1, m + 1):
        S[0][j] = 0 if free_b_ends else j * gap
    for i in range(1, n + 1):
        ai = a[i - 1]
        row, up = S[i], S[i - 1]
        for j in range(1, m + 1):
            diag = up[j - 1] + (match if ai == b[j - 1] else mismatch)
            row[j] = max(diag, up[j] + gap, row[j - 1] + gap)
    return S


def _trace(S, a: str, b: str, i: int, j: int, match: Number, mismatch: Number,
           gap: Number, free_b_ends: bool) -> Tuple[List[str], int]:
    """Trace back from cell (i, j); prefer M, then I, then D. Returns the ops and the start in b."""
    ops: List[str] = []
    while i > 0 or (j > 0 and not free_b_ends):
        if i > 0 and j > 0 and S[i][j] == S[i - 1][j - 1] + (match if a[i - 1] == b[j - 1] else mismatch):
            ops.append("M")
            i, j = i - 1, j - 1
        elif i > 0 and S[i][j] == S[i - 1][j] + gap:
            ops.append("I")
            i -= 1
        else:
            ops.append("D")
            j -= 1
    ops.reverse()
    return ops, j


def global_align(a: str, b: str, match: Number = 1, mismatch: Number = -1,
                 gap: Number = -1) -> Tuple[Number, str]:
    """Needleman-Wunsch alignment of all of a with all of b, with linear gaps.

    Returns (score, cigar). The cigar uses M, I (a base of a only) and D (a base of
    b only); an empty alignment gives "".
    """
    S = _fill(a, b, match, mismatch, gap, False)
    ops, _ = _trace(S, a, b, len(a), len(b), match, mismatch, gap, False)
    return S[len(a)][len(b)], _cigar(ops)


def semiglobal_align(a: str, b: str, match: Number = 1, mismatch: Number = -1,
                     gap: Number = -1, with_start: bool = False):
    """Align all of a (the query) to a substring of b (the reference), with linear gaps.

    Bases of b before and after the aligned part cost nothing and are not in the
    cigar, as in SAM. Returns (score, cigar), or (score, cigar, start) with
    with_start=True, where start is the 0-based position in b of the first
    reference base of the alignment. Among best end columns the leftmost wins.
    """
    S = _fill(a, b, match, mismatch, gap, True)
    n = len(a)
    best_j = max(range(len(b) + 1), key=lambda j: (S[n][j], -j))
    ops, start = _trace(S, a, b, n, best_j, match, mismatch, gap, True)
    if with_start:
        return S[n][best_j], _cigar(ops), start
    return S[n][best_j], _cigar(ops)
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

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

LadderLevelWhat the next level needs
Human proofH1 sketch
  • a full proof of time.grid_bound
  • a full proof of time.per_round
  • a full proof of time.worst
  • a full proof of space.extra
LeanL0 no Lean part
  • name a Lean module in the lean field (07)
Code (python)I0 not checked yet
  • the tests did not run in this build
VisualV0 none
  • add viz/scene.ts or a figure (10)
WritingW2 basic
  • at least three sources
  • a scene preset for the example