Algorithm Search⌘K

Algorithmadvanced

Tandem repeat finding

Also called Tandem Repeats Finder, Benson tandem repeat algorithm.

Find approximate tandem repeats with k-tuple matches at a common distance as candidates, then confirm them by wraparound alignment.

Time
O(G^2 m) worstO(G m) averageΘ(G) best
Space
O(G m) extra
Where
G = the length of the sequence; k = the tuple length; m = the largest period searched
Properties
deterministicnot exactofflineiterative
Origin
Gary Benson, 1999

Tandem repeat finding locates the places in a DNA sequence where a short pattern occurs many times in a row, with some substitutions, insertions and deletions between the copies. Benson's method, published with the program TRF, works in two steps. A fast scan with kk-tuple matches finds pairs of equal short words at the same distance dd many times in a small window, which is the sign of a repeat with period dd. Each candidate is then confirmed by wraparound dynamic programming (WDP), an alignment of the sequence with any number of copies of the pattern, and is reported if at least two copies align with a high enough score.

In plain words

A tandem repeat looks like CAGCAGCAGCAG: the same short word again and again, side by side. In real DNA the copies are not perfect, because mutations change, add or remove letters. To find such places, slide along the sequence and look at short words of a few letters. When a word appears again a fixed number of letters later, note that distance. Inside a repeat, the same distance shows up again and again, because every word of one copy appears again in the next copy. When one distance has been seen often enough in a short stretch, take the last copy as a guess of the repeated word, and line it up with the sequence around it, copy after copy. If many copies line up well, report the stretch, the word and the number of copies.

The problem

Input. A DNA sequence ss of length GG, a tuple length kk, a largest period mm, the alignment weights μ\mu (match), σ\sigma (mismatch) and δ\delta (insertion or deletion), all positive, a minimum score, and a match probability pMp_M for the detection test.

Output. A list of approximate tandem repeats. Each report is an interval [a,b)[a, b) of ss, a period d≤md \le m, a consensus pattern PP of length dd, the alignment score of s[a,b)s[a, b) with copies of PP, and the number of copies, which is the number of pattern letters that the alignment uses divided by dd.

A tandem repeat with period dd is a substring that aligns well with Pc=PP⋯PP^c = P P \cdots P for some c≥2c \ge 2. With no errors this is the string period notion, and exact tandem repeats are squares and runs, which the string algorithms on computing runs and the Main-Lorentz algorithm find. DNA repeats have errors, so the definition uses an alignment score, and there is no single correct output: what counts as a repeat depends on the weights and the cutoffs. TRF is a heuristic for this task, not an exact algorithm for a fixed objective. Its confirmation step, WDP, is exact for what it computes.

Positions here are 0-based, and [a,b)[a, b) is half-open, as in the code.

The algorithm

Detection

Keep a history list H[t]H[t] for each kk-tuple tt: the earlier positions where tt starts. At position ii, the tuple t=s[i,i+k)t = s[i, i + k) matches each earlier position jj in H[t]H[t], at distance d=i−jd = i - j. For each distance there is a window list: the matched tuples at distance dd that lie in the last W(d)W(d) positions, with W(d)=max⁡(d,30)W(d) = \max(d, 30) in the code. The sum of heads of the window is the number of positions covered by these matched tuples. If two copies of a repeat are aligned base by base, a position is a head when its base equals the base dd positions before it, and a kk-tuple match at distance dd is a run of kk heads. So the sum of heads counts the heads that lie in runs of at least kk.

Benson models the heads of two true copies as independent coin tosses that come up heads with probability pMp_M. A candidate needs a sum of heads at least as large as the value that 95 percent of true windows reach under this model. Benson gets the threshold from a normal approximation; the code computes the exact quantile with a small dynamic program over the length of the current run.

  1. FIND-TANDEM-REPEATS(s, k, m, p_M, min_score)
  2. 1H ← an empty history list for each k-tuple, R ← an empty list of repeats
  3. 2for i ← 0 to G - k do
  4. 3t ← s[i, i + k), c ← i + k
  5. 4for each j in H[t] with d = i - j ≤ m, nearest first do
  6. 5add i to the window list of d, and drop the tuples that start before c - W(d)
  7. 6if heads(d) ≥ threshold(W(d), k, p_M) and no report of R explains (c - 1, d) then
  8. 7P ← s[c - d, c), align P around c by WDP, then replace P by the consensus and realign
  9. 8u ← the number of pattern letters that the alignment uses
  10. 9if u ≥ 2d and score ≥ min_score then
  11. 10add ([a, b), d, P, score, u / d) to R
  12. 11append i to H[t]
  13. 12return R without the reports that a report with a smaller period dividing theirs covers

A report explains (c−1,d)(c - 1, d) when its period is at most dd and position c−1c - 1 lies inside it or less than one period after its end. Line L6 also tests each distance at most once per window, so a long repeat does not start a new alignment at every position. The window of line L7 starts at 3d+303d + 30 bases on each side of cc, and it grows until the alignment ends at least d+20d + 20 bases from both edges or reaches the end of ss. The consensus takes, for each pattern position, the most common base aligned to it, and the loop of line L7 realigns with the new pattern until it does not change, at most three times.

Wraparound dynamic programming

WDP aligns a text T=t1…tnT = t_1 \ldots t_n with a substring of P∞=PPP⋯P^\infty = P P P \cdots, locally. The table has one row per text position and one column per pattern position. Column 0 is a copy of column dd: the end of one copy is the start of the next. With s(t,p)=μs(t, p) = \mu for t=pt = p and −σ-\sigma otherwise:

  1. WDP(T, P, μ, σ, δ) ▷ T of length n, P of length d
  2. W1 V[0][0 .. d] ← 0
  3. W2 for x ← 1 to n do
  4. W3 for j ← 1 to d do V[x][j] ← max(0, V[x-1][j-1] + s(t_x, p_j), V[x-1][j] - δ, V[x][j-1] - δ)
  5. W4 V[x][0] ← V[x][d] ▷ the wrap
  6. W5 for j ← 1 to d while V[x][j-1] - δ > V[x][j] do V[x][j] ← V[x][j-1] - δ
  7. W6 (x*, j*) ← a cell with the largest value
  8. W7 trace back from (x*, j*) to a cell of value 0, reading column 0 as column d

The move V[x][j−1]−δV[x][j-1] - \delta deletes a pattern letter, and for j=1j = 1 it reads column 0 of the same row, which is only known after the row is done. So each row is a cyclic system. Line W3 solves it without the wrap, line W4 copies the last column into column 0, and line W5 makes a second pass. Two passes are enough, because a run of dd or more deletions in one row returns to the same column with a lower score, so a best path crosses the wrap at most once. The second pass can stop at the first column where it changes nothing.

Example

WDP. Align T=ACGACGCGACGT = \mathrm{ACGACGCGACG}, which is ACG, ACG, CG (a copy with the A deleted) and ACG, with P=ACGP = \mathrm{ACG} and the TRF weights μ=2\mu = 2, σ=7\sigma = 7, δ=7\delta = 7:

xx txt_x j=1j = 1 (A) j=2j = 2 (C) j=3j = 3 (G)
0 0 0 0
1 A 2 0 0
2 C 0 4 0
3 G 0 0 6
4 A 8 1 0
5 C 1 10 3
6 G 5 3 12
7 C 5 7 5
8 G 2 0 9
9 A 11 4 2
10 C 4 13 6
11 G 8 6 15

Row 4 uses the wrap of line W3: V[4][1]=V[3][3]+2=8V[4][1] = V[3][3] + 2 = 8, because column 0 of row 3 is column 3. Row 6 uses the second pass: after the first pass V[6][1]V[6][1] is 0, line W4 sets column 0 to V[6][3]=12V[6][3] = 12, and line W5 sets V[6][1]=12−7=5V[6][1] = 12 - 7 = 5. This is the deleted A. Then V[7][2]=5+2=7V[7][2] = 5 + 2 = 7, V[8][3]=9V[8][3] = 9, and the path goes on to the best cell V[11][3]=15V[11][3] = 15. The traceback gives all 11 letters of TT against 12 letters of P∞P^\infty, with one deletion: 11⋅2−7=1511 \cdot 2 - 7 = 15. The alignment uses 12 pattern letters, so it has 4 copies. A plain local alignment of TT with ACGACGACGACG gives the same score 15, as Theorem 1 of the proof says.

The finder. For s=TTGCAs = \mathrm{TTGCA} followed by ten copies of ACG and then GGTCA, with k=4k = 4, m=50m = 50, pM=0.8p_M = 0.8 and minimum score 50, the scan finds matches at distance 3 from position 8 on. The window for d=3d = 3 has length 30, and its threshold is 9 heads. The first match at distance 3 covers 4 heads, and each later one adds 1, so the test passes at the tuple that starts at position 13 and ends at position 16. The WDP confirms the repeat, and the output is one report: [5,35)[5, 35), period 3, pattern ACG, score 60 (30 matches), 10 copies. The distances 6, 9, and so on also collect matches, but the period-3 report explains them.

The threshold. With pM=0.75p_M = 0.75, k=5k = 5 and a window of 100, Benson's normal approximation gives a threshold of 26 heads. The exact law gives 27: the probability of fewer than 27 heads is at most 0.05, and the probability of fewer than 28 is more.

Correctness

Two parts are exact, and the proof file proves them.

  • WDP is a local alignment with copies. The value V[x][j]V[x][j] is the best score of an alignment that ends at text position xx and at a pattern letter of phase jj, or 0. Each row is the unique solution of its cyclic system, and two passes compute it (a theorem). The best cell gives the same score as a Smith-Waterman alignment of TT with PMP^M for MM large enough, so WDP is a local alignment against any number of copies, in O(nd)O(n d) time instead of O(n⋅n)O(n \cdot n).
  • The threshold is the exact quantile under the model. The dynamic program over (run length capped at kk, count) gives the exact law of the sum of heads for independent heads with probability pMp_M. So a true window that follows the model passes line L6 with probability at least 0.95 (a theorem about the model).

Detection is a heuristic. A real repeat can fail the test because of indels, which move the matches to a nearby distance, or because its mutations cluster. A random sequence can pass it, and then the WDP score decides. So the finder has no guarantee to report every repeat with a score above the cutoff, and TRF does not claim one.

Proof: Wraparound dynamic programming and the sum of heads law are computed exactlyfull

The finder has two parts. The detection part (lines L1 to L6 of the main pseudocode) is a filter that chooses candidates by a statistical test; it has no guarantee to find every repeat, and the page treats it as a heuristic. This file proves the two exact parts that the finder relies on: the wraparound dynamic program (WDP, lines W1 to W7) gives the best local alignment of a text with any number of tandem copies of a pattern, and the threshold of line L6 is the stated quantile of the exact law of the sum of heads.

Wraparound dynamic programming

Let P=p1…pdP = p_1 \ldots p_d be the pattern and T=t1…tnT = t_1 \ldots t_n the text. Let P∞P^\infty be the infinite string p1…pdp1…pd…p_1 \ldots p_d p_1 \ldots p_d \ldots, and write the position qq of P∞P^\infty as having phase ((q−1) mod d)+1((q - 1) \bmod d) + 1. A wraparound alignment is a global alignment of a substring T[a+1…b]T[a+1 \ldots b] with a substring of P∞P^\infty. Its score adds +μ+\mu for a column with two equal letters, −σ-\sigma for a column with two different letters and −δ-\delta for a column with a gap, where μ,σ,δ>0\mu, \sigma, \delta > 0. The empty alignment has score 0.

For 0≤x≤n0 \le x \le n and 1≤j≤d1 \le j \le d, let V∗(x,j)V^*(x, j) be the largest score of a wraparound alignment that is empty, or that ends with text position xx (the last text letter used is txt_x, or no text letter is used and xx is the point before tx+1t_{x+1}) and with a pattern letter of phase jj (the last pattern letter used has phase jj). Every non-empty alignment ends with a text letter or a pattern letter or both, so this is well defined if we also allow alignments with no text letter, which only have gap columns and negative scores. Write j−=j−1j^- = j - 1 for j>1j > 1 and 1−=d1^- = d, and s(t,p)=μs(t, p) = \mu if t=pt = p and −σ-\sigma otherwise.

Lemma 1 (recurrence). V∗(0,j)=0V^*(0, j) = 0, and for x≥1x \ge 1,

V∗(x,j)=max⁡(0,  V∗(x−1,j−)+s(tx,pj),  V∗(x−1,j)−δ,  V∗(x,j−)−δ).V^*(x, j) = \max\big(0,\; V^*(x - 1, j^-) + s(t_x, p_j),\; V^*(x - 1, j) - \delta,\; V^*(x, j^-) - \delta\big).

Proof. Look at the last column of a best non-empty alignment counted in V∗(x,j)V^*(x, j). If it pairs txt_x with a letter of phase jj, the rest is an alignment that ends at x−1x - 1 and phase j−j^-, or is empty. If it pairs txt_x with a gap, the rest ends at x−1x - 1 with the same last pattern phase jj. If it pairs a letter of phase jj with a gap, the rest ends at xx and phase j−j^-. In each case the rest is counted by the term named, and the converse holds by appending the column. The empty alignment gives 0, and so does the case where the rest is empty. With x=0x = 0 only gap columns of the pattern are possible, which score below 0. □\square

The term V∗(x,j−)V^*(x, j^-) is in the same row, and for j=1j = 1 it is V∗(x,d)V^*(x, d), so row xx is a cyclic system. Fix x≥1x \ge 1, and let Aj=max⁡(0,V∗(x−1,j−)+s(tx,pj),V∗(x−1,j)−δ)A_j = \max(0, V^*(x - 1, j^-) + s(t_x, p_j), V^*(x - 1, j) - \delta), the part that uses row x−1x - 1 only. Indices of AA are taken modulo dd in {1,…,d}\{1, \ldots, d\}.

Lemma 2 (solution of a row). V∗(x,j)=max⁡0≤r<d(Aj−r−rδ)V^*(x, j) = \max_{0 \le r < d} (A_{j - r} - r\delta).

Proof. By Lemma 1, V∗(x,j)=max⁡(Aj,V∗(x,j−)−δ)V^*(x, j) = \max(A_j, V^*(x, j^-) - \delta). Unrolling this rr times gives V∗(x,j)≥Aj−r−rδV^*(x, j) \ge A_{j - r} - r\delta for every r≥0r \ge 0. For the other direction, follow from (x,j)(x, j) the term that reaches the maximum: either it is AjA_j, or we step to j−j^- and pay δ\delta. The walk cannot go round the row: after dd steps it would be back at jj with V∗(x,j)=V∗(x,j)−dδV^*(x, j) = V^*(x, j) - d\delta, which is false because δ>0\delta > 0. So it stops after some r<dr < d steps at an index where AA reaches the maximum, and V∗(x,j)=Aj−r−rδV^*(x, j) = A_{j - r} - r\delta. □\square

Lemma 3 (two passes). Lines W3 to W5 set row xx to V∗(x,⋅)V^*(x, \cdot).

Proof. Line W3 computes Fj=max⁡(Aj,Fj−1−δ)F_j = \max(A_j, F_{j-1} - \delta) for j=1,…,dj = 1, \ldots, d, where F0F_0 is the value 0 that the new row holds in column 0 at that time. Since A1≥0>0−δA_1 \ge 0 > 0 - \delta, F1=A1F_1 = A_1, and by induction Fj=max⁡0≤r<j(Aj−r−rδ)F_j = \max_{0 \le r < j} (A_{j - r} - r\delta), the chains that do not cross column 1 going left. Line W4 sets column 0 to FdF_d. Line W5 computes Sj=max⁡(Fj,Sj−1−δ)S_j = \max(F_j, S_{j-1} - \delta) with S0=FdS_0 = F_d. Unrolling, Sj=max⁡(Fj,Fj−1−δ,…,F1−(j−1)δ,Fd−jδ)S_j = \max(F_j, F_{j-1} - \delta, \ldots, F_1 - (j - 1)\delta, F_d - j\delta). Each Fj−i−iδF_{j - i} - i\delta is at most FjF_j by the definition of FF, so Sj=max⁡(Fj,Fd−jδ)S_j = \max(F_j, F_d - j\delta). The term FjF_j covers the chains with r<jr < j, and Fd−jδ=max⁡0≤r<d(Ad−r−(r+j)δ)F_d - j\delta = \max_{0 \le r < d} (A_{d - r} - (r + j)\delta) covers the chains of length r+jr + j that start at index d−r≡j−(r+j)d - r \equiv j - (r + j), that is all lengths from jj to d+j−1d + j - 1. Together they cover all lengths below dd, and the longer ones are at most the value of a shorter chain with the same start, as in Lemma 2. So Sj=V∗(x,j)S_j = V^*(x, j) by Lemma 2.

The loop of line W5 stops at the first jj with Sj−1−δ≤FjS_{j-1} - \delta \le F_j. Then Sj=FjS_j = F_j, and for every later j′j', Sj′−1−δ=Fj′−1−δ≤Fj′S_{j'-1} - \delta = F_{j'-1} - \delta \le F_{j'} by the definition of FF, so Sj′=Fj′S_{j'} = F_{j'}, which is the value already stored. □\square

By induction on xx, the whole table is V∗V^*, and the best score of line W6 is max⁡x,jV∗(x,j)\max_{x, j} V^*(x, j), the best wraparound alignment.

Theorem 1 (equivalence with copies). For M≥2n/d+3M \ge 2n/d + 3, the best wraparound alignment score of TT and PP equals the best local alignment score (Smith-Waterman with the same scores and linear gaps) of TT and the finite string PMP^M.

Proof. A local alignment of TT and PMP^M aligns a substring of TT with a substring of PMP^M, which is a substring of P∞P^\infty, so it is a wraparound alignment with the same score. Conversely, take a best wraparound alignment, with score V≥0V \ge 0. If it is empty, both sides are 0. Otherwise it uses u≤nu \le n text letters, ee deletions and at most uu other pattern letters. All columns score at most μ\mu, so its score is at most uμ−eδu\mu - e\delta, and a best alignment has a non-negative score, so e≤uμ/δe \le u\mu/\delta. With μ=2\mu = 2 and δ=7\delta = 7, as in the code and the test, e≤2u/7e \le 2u/7. It uses at most u+e<2nu + e < 2n letters of P∞P^\infty, which fit inside PMP^M from any starting phase when Md≥2n+dMd \ge 2n + d. So it is a local alignment of TT and PMP^M. □\square

Lemma 4 (traceback). Line W7 returns an alignment whose score is the best score.

Proof. From a cell with value v>0v > 0, at least one of the three moves of Lemma 1 has a predecessor whose value plus the column score is vv, because vv is the maximum of those terms or of 0, and it is not 0. Each move appends the matching column, so the sum of the column scores from the stop cell to the start cell is vv minus the value of the stop cell, which is 0. The walk stops: the diagonal and up moves lower xx, and a run of left moves in one row cannot go round the row, by the argument of Lemma 2. □\square

The sum of heads law

Let h1,…,hwh_1, \ldots, h_w be independent with P(hi=1)=pP(h_i = 1) = p. A position ii with hi=1h_i = 1 is a head. The statistic CC counts the heads that lie in a maximal run of at least kk consecutive heads. In a window of ww positions of a tandem repeat with period dd, hi=1h_i = 1 means that the base at position ii equals the base dd positions before it. A kk-tuple match at distance dd is a run of kk heads, so the union of the matched tuples that lie in the window covers exactly the heads counted by CC. The model assumes that the heads are independent with probability pMp_M, which is Benson's model of an alignment of two copies.

Lemma 5. The function heads_distribution(w, k, p) returns the law of CC.

Proof. Scan the positions from left to right, and keep the state (r,c)(r, c), where rr is the length of the current run of heads, capped at kk, and cc is the number of heads counted so far. A tail sets r=0r = 0. A head with r+1<kr + 1 < k sets r←r+1r \leftarrow r + 1 and counts nothing yet. A head with r+1=kr + 1 = k completes a run of kk, so all kk heads of the run are counted: c←c+kc \leftarrow c + k and r=kr = k. A head with r=kr = k extends a counted run: c←c+1c \leftarrow c + 1. A run that ends with fewer than kk heads is never counted. So after the last position c=Cc = C. The states form a Markov chain with the transition probabilities pp and 1−p1 - p, and the code applies them ww times to the start state (0,0)(0, 0) and sums over rr. □\square

Corollary. sum_of_heads_threshold(w, k, p, alpha) returns the largest c≤wc \le w with P(C<c)≤αP(C < c) \le \alpha. So a window of a true repeat whose heads follow the model passes the test C≥cC \ge c of line L6 with probability at least 1−α1 - \alpha. This is a statement about one window under the model; it does not say that the finder reports every repeat, and real repeats with indels or with mutations that cluster do not follow the model.

What the finder returns

Each report comes from line L10 after the WDP of a final pattern P′P' of length dd in a window s[lo,hi)s[\mathit{lo}, \mathit{hi}). By Theorem 1, its score is the best local alignment score of the window with copies of P′P', its interval is the text part of that alignment, and its number of copies is the number of pattern letters used divided by dd. Line L9 reports it only if it uses at least 2d2d pattern letters and its score is at least the minimum score. These facts hold for every report. Which regions are reported, and with which period, depends on the detection filter, the window growth and the consensus rounds, which are heuristics.

Complexity

The model is the word RAM, and a kk-tuple of DNA fits in one word.

  • Scan. Each position appends to one history list and reads the entries within distance mm, from the end, so it costs O(1+ei)O(1 + e_i), where ei≤me_i \le m is the number of matches it finds. Each match costs O(1)O(1) amortized for its window list. In random DNA with uniform bases, eie_i has mean about m/4km / 4^k, so the scan costs O(G(1+m/4k))O(G (1 + m / 4^k)), which is O(Gm)O(G m); for a sequence with no repeated tuples it is Θ(G)\Theta(G).
  • Thresholds. The table for one window length ww takes O(kw2)O(k w^2) time, and there are at most mm different lengths, all cached.
  • Confirmation. A WDP of a window of length nn with a pattern of length dd costs O(nd)O(n d) time and space. Each distance is tested at most once per window length, so the number of tests is at most GG per distance, and a test window can grow to GG. This gives the crude worst case O(G2m)O(G^2 m); on sequences with few repeats the WDP work is small next to the scan.
  • Space. The history lists take O(G)O(G), the window lists O(m2)O(m^2), and a WDP table O(Gm)O(G m) at most.

TRF has the same shape: a linear scan with lists, and WDP on candidates only. For patterns longer than 20, Benson restricts the WDP to a band around the diagonal, which lowers the cost of a test.

Properties

  • Deterministic. There is no randomness; the same input gives the same reports.
  • Not exact. The output depends on the detection test, the window growth and the consensus rounds. Two repeats that differ only by their phase are reported with patterns that are rotations of each other.
  • Period choice. A repeat with period dd also has matches at 2d2d, 3d3d and so on. The code reports the smallest period that explains a region. TRF can report up to three periods for one region, for example when a repeat of period 6 is also a looser repeat of period 3.
  • Consensus. With few copies, a tie in the majority vote keeps the old base, so a mutation in the first guess can stay in the consensus. Rounds of realignment reduce this but do not remove it.
  • Scores. With μ=2\mu = 2 and σ=δ=7\sigma = \delta = 7, one error costs as much as 3.5 matches. A minimum score of 50 needs at least 25 matching bases.

Variants and improvements

  • What the code leaves out. TRF also counts a match at distance dd for the distances d±1,…,d±Δdd \pm 1, \ldots, d \pm \Delta d, so that indels do not split the evidence across neighbouring distances. It uses three more tests: a random walk bound that gives Δd\Delta d, an apparent size test that rejects a distance when a smaller distance explains the same matches, and a waiting time test on the gaps between matches. It chooses the tuple size by the range of pattern sizes, uses banded WDP for patterns longer than 20, builds a consensus whose length can differ from dd, and filters reports with related periods. The code keeps one kk, a fixed minimum window, and the simple rule of line L12.
  • Parameters of the paper. Benson gives two weight sets, (μ,σ,δ)=(2,7,7)(\mu, \sigma, \delta) = (2, 7, 7) and (2,5,7)(2, 5, 7), two pairs of match and indel probabilities, (pM,pI)=(0.80,0.10)(p_M, p_I) = (0.80, 0.10) and (0.75,0.20)(0.75, 0.20), a minimum alignment score of 50, and pattern sizes from 1 to 500.
  • Exact repeats. For repeats with no errors, the string algorithms are exact and fast: all squares by Main-Lorentz in O(nlog⁡n)O(n \log n) time, and all runs in linear time (computing runs, with the runs theorem bound on their number).
  • Alignment with a regular expression. WDP is a special case of the alignment of a sequence with the regular expression P∗P^*, which Myers and Miller (1989) solve in general.
  • Masking. Repeat masking tools run a tandem repeat finder for the simple repeats, and a library search for the interspersed ones.

When to use it

Use it to list microsatellites and minisatellites in a genome or a contig, to mask simple repeats before gene finding or alignment, to choose markers whose copy number varies between individuals, and to check an assembly for collapsed repeats. Use an exact runs algorithm when only perfect repeats matter. For repeat families spread over the genome, such as transposons, use a library search (repeat masking); a tandem repeat finder sees only copies that are next to each other.

Pitfalls

  • Period multiples. A repeat with period 3 is also a repeat with period 6, 9 and so on, with a lower score per copy. Without a rule, the output lists each region many times.
  • Rotations. ACG, CGA and GAC describe the same repeat. Compare patterns up to rotation, and pick a canonical rotation if the reports are merged.
  • Short windows. For small periods a window of length dd holds too few tuples, and the threshold falls to 0, so every match becomes a candidate. The code uses a minimum window of 30; TRF uses smaller tuples for small patterns.
  • Weights in two conventions. TRF writes the mismatch and indel weights as positive penalties. Many alignment libraries add negative scores. Mixing the two turns a penalty into a reward.
  • Low-complexity flanks. A homopolymer next to a repeat aligns with many patterns. Check the reported ends, and mask homopolymers on their own if they matter.
  • Copy number. The copy number is a ratio of aligned pattern letters to the period, so it can be fractional, and the last partial copy may be cut off by the local alignment.

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)
tandem_repeat_finding.py 306 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/tandem-repeat-finding/. The authors are listed in prov/3VVNE0.jsonl.
"""Tandem repeat finding in the style of Benson's Tandem Repeats Finder (TRF).

A small version of the method. It keeps the two main parts of TRF:
- detection: k-tuple matches found with history lists, counted per distance d
  in a sliding window, and a sum of heads test that makes the pair (position,
  d) a candidate;
- confirmation: wraparound dynamic programming (WDP) of the candidate pattern
  against the sequence around it, a majority consensus, a second WDP with the
  consensus, and a report if at least two copies align with a score of at
  least min_score.

It leaves out these parts of TRF (the page says so too): the indel test that
also updates the distances d - 1, ..., d - delta and d + 1, ..., d + delta, the
random walk, apparent size and waiting time tests, the tuple size that depends
on the pattern size, banded WDP for large patterns, a consensus whose length
can differ from d, and the rules that let TRF report up to three periods for
one region. Here a candidate (position, d) is skipped when the position is in a
reported repeat with a period of at most d, or within one period after it, so
each region gets one report, usually with the smallest period.

Positions are 0-based and intervals half-open. Scores use TRF's convention:
match is a positive number and mismatch and indel are positive penalties that
are subtracted. The default weights (2, 7, 7) are those of the TRF paper.
"""

from collections import deque
from typing import Dict, List, NamedTuple, Optional, Sequence, Tuple

Number = float


class Repeat(NamedTuple):
    """A reported tandem repeat: s[start:end] is about copies copies of pattern."""

    start: int
    end: int
    period: int
    pattern: str
    score: int
    copies: float


def heads_distribution(w: int, k: int, p):
    """The law of the number of heads that lie in runs of at least k heads.

    The w positions are independent, each a head with probability p (a float or
    a Fraction). Returns a list q with q[c] = P(count = c) for c = 0..w. The
    state is the length of the current run, capped at k.
    """
    zero = p - p
    one = zero + 1
    # dist[r][c]: run length r (0..k, k means at least k) and count c
    dist = [[zero] * (w + 1) for _ in range(k + 1)]
    dist[0][0] = one
    for _ in range(w):
        new = [[zero] * (w + 1) for _ in range(k + 1)]
        for r in range(k + 1):
            row = dist[r]
            for c in range(w + 1):
                pr = row[c]
                if pr == zero:
                    continue
                new[0][c] += pr * (one - p)
                if r + 1 < k:
                    new[r + 1][c] += pr * p
                elif r + 1 == k:
                    new[k][c + k] += pr * p  # the run reaches k: its k heads count
                else:
                    new[k][c + 1] += pr * p
        dist = new
    return [sum(dist[r][c] for r in range(k + 1)) for c in range(w + 1)]


_THRESHOLDS: Dict[Tuple[int, int, float, float], int] = {}


def sum_of_heads_threshold(w: int, k: int, p_match: float, alpha: float = 0.05) -> int:
    """The largest c with P(count < c) <= alpha, for the count of heads_distribution.

    A true repeat whose copies match with probability p_match per position passes
    the test count >= c with probability at least 1 - alpha in each window.
    """
    key = (w, k, p_match, alpha)
    if key not in _THRESHOLDS:
        q = heads_distribution(w, k, p_match)
        c, below = 0, 0.0
        while c < w and below + q[c] <= alpha:
            below += q[c]
            c += 1
        _THRESHOLDS[key] = c
    return _THRESHOLDS[key]


def wraparound_table(text: str, pattern: str, match: int = 2, mismatch: int = 7,
                     indel: int = 7) -> List[List[int]]:
    """The WDP table of a local alignment of text with any number of copies of pattern.

    V[x][j] for x = 0..len(text) and j = 0..d is the best score of an alignment
    that ends with text[x - 1] and pattern[j - 1]; column 0 is a copy of column d,
    the end of one copy and the start of the next. Scores are at least 0.
    """
    d = len(pattern)
    if d == 0:
        raise ValueError("the pattern must not be empty")
    V = [[0] * (d + 1) for _ in range(len(text) + 1)]  # @line W1
    for x in range(1, len(text) + 1):  # @line W2
        a, up, row = text[x - 1], V[x - 1], V[x]
        for j in range(1, d + 1):  # @line W3
            diag = up[j - 1] + (match if a == pattern[j - 1] else -mismatch)
            row[j] = max(0, diag, up[j] - indel, row[j - 1] - indel)
        row[0] = row[d]  # @line W4
        for j in range(1, d + 1):  # @line W5
            v = row[j - 1] - indel
            if v <= row[j]:
                break
            row[j] = v
        row[0] = row[d]
    return V


def wraparound_align(text: str, pattern: str, match: int = 2, mismatch: int = 7,
                     indel: int = 7):
    """The best local WDP alignment of text against copies of pattern.

    Returns (score, a, b, cols) where text[a:b] is the aligned part and cols is
    the list of alignment columns from left to right: (x, j) for text[x] against
    pattern[j], (x, None) for text[x] against a gap and (None, j) for pattern[j]
    against a gap. The traceback prefers the diagonal, then a gap in the pattern,
    then a gap in the text, and stops at a cell of score 0. Among best cells the
    first in row order wins. An alignment of score 0 is empty: (0, 0, 0, []).
    """
    d = len(pattern)
    V = wraparound_table(text, pattern, match, mismatch, indel)
    best, bx, bj = 0, 0, 0
    for x in range(1, len(text) + 1):  # @line W6
        row = V[x]
        for j in range(1, d + 1):
            if row[j] > best:
                best, bx, bj = row[j], x, j
    if best == 0:
        return 0, 0, 0, []
    cols: List[Tuple[Optional[int], Optional[int]]] = []
    x, j = bx, bj
    while V[x][j] > 0:  # @line W7
        v = V[x][j]
        pj = j - 1 if j > 1 else d  # the column before j; column 0 is column d
        sub = match if text[x - 1] == pattern[j - 1] else -mismatch
        if V[x - 1][pj] + sub == v:
            cols.append((x - 1, j - 1))
            x, j = x - 1, pj
            continue
        if V[x - 1][j] - indel == v:
            cols.append((x - 1, None))
            x -= 1
            continue
        cols.append((None, j - 1))
        j = pj
    cols.reverse()
    a = x
    return best, a, bx, cols


def consensus(text: str, d: int, cols, old: str) -> str:
    """Majority base for each pattern position over the aligned text bases.

    Positions with no aligned base keep the old base. Ties go to the old base if
    it is among the most common bases, then to the first in the order ACGT.
    """
    counts = [dict() for _ in range(d)]
    for x, j in cols:
        if x is not None and j is not None:
            c = text[x]
            counts[j][c] = counts[j].get(c, 0) + 1
    out = []
    for j in range(d):
        if not counts[j]:
            out.append(old[j])
            continue
        top = max(counts[j].values())
        winners = [c for c in counts[j] if counts[j][c] == top]
        out.append(old[j] if old[j] in winners else min(winners, key="ACGTN".find))
    return "".join(out)


def pattern_length_used(cols) -> int:
    """The number of pattern positions that the alignment uses (matched or deleted)."""
    return sum(1 for _, j in cols if j is not None)


def _covered(reports: Sequence[Repeat], pos: int, d: int) -> bool:
    """True if pos is in a reported repeat with period at most d, or one period after it."""
    return any(r.start <= pos < r.end + r.period and r.period <= d for r in reports)


def _confirm(s: str, c: int, d: int, match: int, mismatch: int, indel: int):
    """WDP of the pattern s[c - d:c] around c, with the window grown as needed.

    The window grows until the alignment ends at least slack = d + 20 bases
    from each window edge (or at the end of s). Then the pattern is replaced by
    the majority consensus and aligned again, for at most max_rounds rounds or
    until the consensus does not change. Returns (score, start, end, cols,
    pattern) in coordinates of s, for the last pattern.
    """
    G = len(s)
    slack, step = d + 20, 3 * d + 30
    lo, hi = max(0, c - step), min(G, c + step)
    pattern = s[c - d:c]
    max_rounds = 3
    for round_ in range(max_rounds + 1):
        while True:
            score, a, b, cols = wraparound_align(s[lo:hi], pattern, match, mismatch, indel)
            grow_left = lo > 0 and a < slack
            grow_right = hi < G and b > hi - lo - slack
            if not (grow_left or grow_right):
                break
            if grow_left:
                lo = max(0, lo - step)
            if grow_right:
                hi = min(G, hi + step)
            step *= 2
        if round_ == max_rounds:
            break
        new = consensus(s[lo:hi], d, cols, pattern)
        if new == pattern:
            break
        pattern = new
    cols = [(None if x is None else x + lo, j) for x, j in cols]
    return score, a + lo, b + lo, cols, pattern


def find_tandem_repeats(s: str, k: int = 4, max_period: int = 50, p_match: float = 0.80,
                        min_window: int = 30, min_score: int = 50, match: int = 2,
                        mismatch: int = 7, indel: int = 7) -> List[Repeat]:
    """Find approximate tandem repeats with periods 1 to max_period in s.

    The window for distance d has length w(d) = max(d, min_window); min_window
    must be at least k. A pair (position, d) is a candidate when the number of
    heads (positions covered by k-tuple matches at distance d that lie fully in
    the window) reaches sum_of_heads_threshold(w(d), k, p_match). Distances are
    tried from the smallest. Reports are sorted by start, then by period.
    """
    if min_window < k:
        raise ValueError("min_window must be at least k")
    G = len(s)
    history: Dict[str, List[int]] = {}  # @line L1
    windows: Dict[int, deque] = {}
    covered_count: Dict[int, int] = {}
    next_test: Dict[int, int] = {}
    reports: List[Repeat] = []
    for i in range(G - k + 1):  # @line L2
        t, c = s[i:i + k], i + k  # @line L3
        h = history.setdefault(t, [])
        for idx in range(len(h) - 1, -1, -1):  # @line L4
            d = i - h[idx]
            if d > max_period:
                break
            w = max(d, min_window)
            win = windows.setdefault(d, deque())  # @line L5
            cov = covered_count.get(d, 0)
            gain = k if not win else min(k, i - win[-1][0])
            win.append([i, gain])
            cov += gain
            while win[0][0] < c - w:
                cov -= win.popleft()[1]
                cov += k - win[0][1]
                win[0][1] = k
            covered_count[d] = cov
            if cov < sum_of_heads_threshold(w, k, p_match):  # @line L6
                continue
            if next_test.get(d, 0) > i or _covered(reports, c - 1, d):
                continue
            next_test[d] = i + w
            score, a, b, cols, pattern = _confirm(s, c, d, match, mismatch, indel)  # @line L7
            used = pattern_length_used(cols)  # @line L8
            if used >= 2 * d and score >= min_score:  # @line L9
                reports.append(Repeat(a, b, d, pattern, score, round(used / d, 1)))  # @line L10
                next_test[d] = b
        h.append(i)  # @line L11
    reports = drop_multiples(reports)
    reports.sort(key=lambda r: (r.start, r.period))
    return reports  # @line L12


def drop_multiples(reports: Sequence[Repeat]) -> List[Repeat]:
    """Drop a report when a report with a smaller period that divides its period
    covers at least 90 percent of it with at least the same score."""
    keep = []
    for r in reports:
        length = r.end - r.start
        redundant = False
        for q in reports:
            if q.period < r.period and r.period % q.period == 0 and q.score >= r.score:
                overlap = min(q.end, r.end) - max(q.start, r.start)
                if 10 * overlap >= 9 * length:
                    redundant = True
                    break
        if not redundant:
            keep.append(r)
    return keep


def is_rotation(a: str, b: str) -> bool:
    """True if b is a cyclic rotation of a."""
    return len(a) == len(b) and b in a + a
test_tandem_repeat_finding.py 177 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/tandem-repeat-finding/. The authors are listed in prov/3VVNE0.jsonl.
"""Tests of the tandem repeat finder: WDP against Smith-Waterman on copies of the
pattern, the sum of heads law against enumeration, and planted repeats."""

import itertools
import random
import unittest
from fractions import Fraction

from bioseq import hamming, mutate, random_dna
from tandem_repeat_finding import (Repeat, find_tandem_repeats, heads_distribution,
                                   is_rotation, sum_of_heads_threshold, wraparound_align)

MATCH, MISMATCH, INDEL = 2, 7, 7


def smith_waterman(a, b, match=MATCH, mismatch=MISMATCH, indel=INDEL):
    """Best local alignment score of a and b with linear gaps."""
    prev = [0] * (len(b) + 1)
    best = 0
    for x in range(1, len(a) + 1):
        cur = [0] * (len(b) + 1)
        for y in range(1, len(b) + 1):
            sub = match if a[x - 1] == b[y - 1] else -mismatch
            cur[y] = max(0, prev[y - 1] + sub, prev[y] - indel, cur[y - 1] - indel)
            best = max(best, cur[y])
        prev = cur
    return best


def score_of(text, pattern, cols):
    """The score of an alignment given as columns, and a check of its shape."""
    total, last_x, last_j = 0, None, None
    d = len(pattern)
    for x, j in cols:
        if x is not None:
            assert last_x is None or x == last_x + 1
            last_x = x
        if j is not None:
            assert last_j is None or j == (last_j + 1) % d
            last_j = j
        if x is None or j is None:
            total -= INDEL
        else:
            total += MATCH if text[x] == pattern[j] else -MISMATCH
    return total


def best_rotation_distance(unit, pattern):
    if len(unit) != len(pattern):
        return len(unit) + len(pattern)
    return min(hamming(unit, pattern[r:] + pattern[:r]) for r in range(len(pattern)))


def add_indels(rng, seq, rate):
    """Delete or insert one random base at each position with probability rate.

    Draw order per position: one rng.random(); if it is below rate, one
    rng.random() < 0.5 for a deletion, and for an insertion one rng.choice.
    """
    out = []
    for c in seq:
        if rng.random() < rate:
            if rng.random() < 0.5:
                continue
            out.append(rng.choice("ACGT"))
        out.append(c)
    return "".join(out)


def planted(rng, d, sub_rate, indel_rate, flank=200):
    unit = random_dna(rng, d)
    left, right = random_dna(rng, flank), random_dna(rng, flank)
    rep = add_indels(rng, mutate(rng, unit * max(4, 120 // d), sub_rate), indel_rate)
    return unit, left + rep + right, flank, flank + len(rep)


def found(unit, d, reports, a, b, max_dist):
    for r in reports:
        overlap = min(r.end, b) - max(r.start, a)
        if r.period == d and overlap >= 0.8 * (b - a) and best_rotation_distance(unit, r.pattern) <= max_dist:
            return True
    return False


class TestWraparound(unittest.TestCase):
    def test_equals_smith_waterman_on_copies(self):
        rng = random.Random(11)
        for trial in range(250):
            alphabet = "AC" if trial % 2 else "ACGT"
            d = rng.randint(1, 6)
            pattern = "".join(rng.choice(alphabet) for _ in range(d))
            text = "".join(rng.choice(alphabet) for _ in range(rng.randint(0, 28)))
            score, a, b, cols = wraparound_align(text, pattern)
            copies = pattern * (2 * len(text) // d + 3)
            self.assertEqual(score, smith_waterman(text, copies))
            self.assertEqual(score_of(text, pattern, cols), score)
            used = [x for x, _ in cols if x is not None]
            self.assertEqual(used, list(range(a, b)))

    def test_tandem_example(self):
        score, a, b, cols = wraparound_align("TTACGACGACGTTT", "ACG")
        self.assertEqual((score, a, b), (18, 2, 11))
        self.assertEqual([j for _, j in cols], [0, 1, 2] * 3)

    def test_indel_in_a_copy(self):
        # ACG ACG AG ACG ACG: 14 matches and one deleted C
        score, a, b, cols = wraparound_align("ACGACGAGACGACG", "ACG")
        self.assertEqual((score, a, b), (14 * MATCH - INDEL, 0, 14))
        self.assertIn((None, 1), cols)


class TestSumOfHeads(unittest.TestCase):
    def test_distribution_against_enumeration(self):
        for w in range(1, 11):
            for k in range(1, 5):
                p = Fraction(3, 4)
                exact = [Fraction(0)] * (w + 1)
                for bits in itertools.product((0, 1), repeat=w):
                    count, run = 0, 0
                    for t in range(w + 1):
                        if t < w and bits[t]:
                            run += 1
                            continue
                        if run >= k:
                            count += run
                        run = 0
                    ones = sum(bits)
                    exact[count] += p ** ones * (1 - p) ** (w - ones)
                self.assertEqual(heads_distribution(w, k, p), exact)

    def test_threshold_is_the_lower_quantile(self):
        c = sum_of_heads_threshold(100, 5, 0.75)
        self.assertEqual(c, 27)
        q = heads_distribution(100, 5, Fraction(3, 4))
        self.assertLessEqual(sum(q[:c]), Fraction(1, 20))
        self.assertGreater(sum(q[:c + 1]), Fraction(1, 20))


class TestFinder(unittest.TestCase):
    def test_perfect_repeat(self):
        s = "TTGCA" + "ACG" * 10 + "GGTCA"
        self.assertEqual(find_tandem_repeats(s), [Repeat(5, 35, 3, "ACG", 60, 10.0)])

    def test_planted_substitutions(self):
        hits = 0
        periods = [2, 3, 5, 7, 11, 15, 20, 25, 33, 45]
        for seed in range(30):
            rng = random.Random(1000 + seed)
            d = periods[seed % len(periods)]
            unit, s, a, b = planted(rng, d, 0.05, 0.0)
            hits += found(unit, d, find_tandem_repeats(s), a, b, 2)
        self.assertGreaterEqual(hits, 29)

    def test_planted_with_indels(self):
        hits = 0
        periods = [3, 7, 12, 20, 30]
        for seed in range(20):
            rng = random.Random(2000 + seed)
            d = periods[seed % len(periods)]
            unit, s, a, b = planted(rng, d, 0.03, 0.01)
            hits += found(unit, d, find_tandem_repeats(s), a, b, 2)
        self.assertGreaterEqual(hits, 17)

    def test_random_dna_has_no_repeats(self):
        for seed in range(5):
            rng = random.Random(seed)
            self.assertEqual(find_tandem_repeats(random_dna(rng, 2000)), [])

    def test_rotation(self):
        self.assertTrue(is_rotation("ACG", "GAC"))
        self.assertFalse(is_rotation("ACG", "AGC"))


if __name__ == "__main__":
    unittest.main()

History

Benson (1999) described the program TRF in Nucleic Acids Research. It joins a fast filter based on kk-tuple matches at a common distance, with criteria drawn from a probabilistic model of two aligned copies, with wraparound dynamic programming to confirm and align each candidate. Wraparound dynamic programming goes back to the alignment of sequences with regular expressions by Myers and Miller (1989) and to the search for periodic occurrences of a template by Fischetti, Landau, Schmidt and Sellers (1992). TRF became the standard tool for simple repeats, and repeat masking pipelines call it for that part of the work.

References

  1. Gary Benson, Tandem repeats finder, a program to analyze DNA sequences, Nucleic Acids Research 27(2), 1999, pp. 573 to 580; the k-tuple history and distance lists, the sum of heads, random walk, apparent size and waiting time criteria, wraparound dynamic programming, the consensus pattern, and the default weights and parameters
  2. Eugene W. Myers and Webb Miller, Approximate matching of regular expressions, Bulletin of Mathematical Biology 51(1), 1989, pp. 5 to 37; alignment of a sequence with a regular expression, which includes a pattern repeated any number of times
  3. V. A. Fischetti, G. M. Landau, J. P. Schmidt and P. H. Sellers, Identifying periodic occurrences of a template with applications to protein structure, Combinatorial Pattern Matching (CPM 1992), Lecture Notes in Computer Science 644, pp. 111 to 120, the wraparound dynamic program for the alignment of a text with tandem copies of a template

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.average
  • a full proof of time.best
  • a full proof of time.worst
  • a full proof of space.extra
LeanL0 no Lean part
  • name a Lean module in the lean field (07)
Code (python)I0 not checked yet
  • the tests did not run in this build
VisualV0 none
  • add viz/scene.ts or a figure (10)
WritingW2 basic
  • a scene preset for the example