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
- Model
- Word RAM
- Properties
- deterministicnot exactofflineiterative
- Evidence
- Proof sketchCode in 1 languages
- 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 -tuple matches finds pairs of equal short words at the same distance many times in a small window, which is the sign of a repeat with period . 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 of length , a tuple length , a largest period , the alignment weights (match), (mismatch) and (insertion or deletion), all positive, a minimum score, and a match probability for the detection test.
Output. A list of approximate tandem repeats. Each report is an interval of , a period , a consensus pattern of length , the alignment score of with copies of , and the number of copies, which is the number of pattern letters that the alignment uses divided by .
A tandem repeat with period is a substring that aligns well with for some . 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 is half-open, as in the code.
The algorithm
Detection
Keep a history list for each -tuple : the earlier positions where starts. At position , the tuple matches each earlier position in , at distance . For each distance there is a window list: the matched tuples at distance that lie in the last positions, with 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 positions before it, and a -tuple match at distance is a run of heads. So the sum of heads counts the heads that lie in runs of at least .
Benson models the heads of two true copies as independent coin tosses that come up heads with probability . 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.
FIND-TANDEM-REPEATS(s, k, m, p_M, min_score)- 1
H ← an empty history list for each k-tuple, R ← an empty list of repeats - 2
for i ← 0 to G - k do - 3
t ← s[i, i + k), c ← i + k - 4
for each j in H[t] with d = i - j ≤ m, nearest first do - 5
add i to the window list of d, and drop the tuples that start before c - W(d) - 6
if heads(d) ≥ threshold(W(d), k, p_M) and no report of R explains (c - 1, d) then - 7
P ← s[c - d, c), align P around c by WDP, then replace P by the consensus and realign - 8
u ← the number of pattern letters that the alignment uses - 9
if u ≥ 2d and score ≥ min_score then - 10
add ([a, b), d, P, score, u / d) to R - 11
append i to H[t] - 12
return R without the reports that a report with a smaller period dividing theirs covers
A report explains when its period is at most and position 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 bases on each side of , and it grows until the alignment ends at least bases from both edges or reaches the end of . 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 with a substring of , locally. The table has one row per text position and one column per pattern position. Column 0 is a copy of column : the end of one copy is the start of the next. With for and otherwise:
WDP(T, P, μ, σ, δ) ▷ T of length n, P of length dW1 V[0][0 .. d] ← 0W2 for x ← 1 to n doW3 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] - δ)W4 V[x][0] ← V[x][d] ▷ the wrapW5 for j ← 1 to d while V[x][j-1] - δ > V[x][j] do V[x][j] ← V[x][j-1] - δW6 (x*, j*) ← a cell with the largest valueW7 trace back from (x*, j*) to a cell of value 0, reading column 0 as column d
The move deletes a pattern letter, and for 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 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 , which is ACG, ACG, CG (a copy with the A deleted) and ACG, with and the TRF weights , , :
| (A) | (C) | (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: , because column 0 of row 3 is column 3. Row 6 uses the second pass: after the first pass is 0, line W4 sets column 0 to , and line W5 sets . This is the deleted A. Then , , and the path goes on to the best cell . The traceback gives all 11 letters of against 12 letters of , with one deletion: . The alignment uses 12 pattern letters, so it has 4 copies. A plain local alignment of with ACGACGACGACG gives the same score 15, as Theorem 1 of the proof says.
The finder. For followed by ten copies of ACG and then GGTCA, with , , and minimum score 50, the scan finds matches at distance 3 from position 8 on. The window for 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: , 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 , 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 is the best score of an alignment that ends at text position and at a pattern letter of phase , 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 with for large enough, so WDP is a local alignment against any number of copies, in time instead of .
- The threshold is the exact quantile under the model. The dynamic program over (run length capped at , count) gives the exact law of the sum of heads for independent heads with probability . 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 be the pattern and the text. Let be the infinite string , and write the position of as having phase . A wraparound alignment is a global alignment of a substring with a substring of . Its score adds for a column with two equal letters, for a column with two different letters and for a column with a gap, where . The empty alignment has score 0.
For and , let be the largest score of a wraparound alignment that is empty, or that ends with text position (the last text letter used is , or no text letter is used and is the point before ) and with a pattern letter of phase (the last pattern letter used has phase ). 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 for and , and if and otherwise.
Lemma 1 (recurrence). , and for ,
Proof. Look at the last column of a best non-empty alignment counted in . If it pairs with a letter of phase , the rest is an alignment that ends at and phase , or is empty. If it pairs with a gap, the rest ends at with the same last pattern phase . If it pairs a letter of phase with a gap, the rest ends at and phase . 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 only gap columns of the pattern are possible, which score below 0.
The term is in the same row, and for it is , so row is a cyclic system. Fix , and let , the part that uses row only. Indices of are taken modulo in .
Lemma 2 (solution of a row). .
Proof. By Lemma 1, . Unrolling this times gives for every . For the other direction, follow from the term that reaches the maximum: either it is , or we step to and pay . The walk cannot go round the row: after steps it would be back at with , which is false because . So it stops after some steps at an index where reaches the maximum, and .
Lemma 3 (two passes). Lines W3 to W5 set row to .
Proof. Line W3 computes for , where is the value 0 that the new row holds in column 0 at that time. Since , , and by induction , the chains that do not cross column 1 going left. Line W4 sets column 0 to . Line W5 computes with . Unrolling, . Each is at most by the definition of , so . The term covers the chains with , and covers the chains of length that start at index , that is all lengths from to . Together they cover all lengths below , and the longer ones are at most the value of a shorter chain with the same start, as in Lemma 2. So by Lemma 2.
The loop of line W5 stops at the first with . Then , and for every later , by the definition of , so , which is the value already stored.
By induction on , the whole table is , and the best score of line W6 is , the best wraparound alignment.
Theorem 1 (equivalence with copies). For , the best wraparound alignment score of and equals the best local alignment score (Smith-Waterman with the same scores and linear gaps) of and the finite string .
Proof. A local alignment of and aligns a substring of with a substring of , which is a substring of , so it is a wraparound alignment with the same score. Conversely, take a best wraparound alignment, with score . If it is empty, both sides are 0. Otherwise it uses text letters, deletions and at most other pattern letters. All columns score at most , so its score is at most , and a best alignment has a non-negative score, so . With and , as in the code and the test, . It uses at most letters of , which fit inside from any starting phase when . So it is a local alignment of and .
Lemma 4 (traceback). Line W7 returns an alignment whose score is the best score.
Proof. From a cell with value , at least one of the three moves of Lemma 1 has a predecessor whose value plus the column score is , because 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 minus the value of the stop cell, which is 0. The walk stops: the diagonal and up moves lower , and a run of left moves in one row cannot go round the row, by the argument of Lemma 2.
The sum of heads law
Let be independent with . A position with is a head. The statistic counts the heads that lie in a maximal run of at least consecutive heads. In a window of positions of a tandem repeat with period , means that the base at position equals the base positions before it. A -tuple match at distance is a run of heads, so the union of the matched tuples that lie in the window covers exactly the heads counted by . The model assumes that the heads are independent with probability , which is Benson's model of an alignment of two copies.
Lemma 5. The function heads_distribution(w, k, p) returns the law of .
Proof. Scan the positions from left to right, and keep the state , where is the length of the current run of heads, capped at , and is the number of heads counted so far. A tail sets . A head with sets and counts nothing yet. A head with completes a run of , so all heads of the run are counted: and . A head with extends a counted run: . A run that ends with fewer than heads is never counted. So after the last position . The states form a Markov chain with the transition probabilities and , and the code applies them times to the start state and sums over .
Corollary. sum_of_heads_threshold(w, k, p, alpha) returns the largest with . So a window of a true repeat whose heads follow the model passes the test of line L6 with probability at least . 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 of length in a window . By Theorem 1, its score is the best local alignment score of the window with copies of , its interval is the text part of that alignment, and its number of copies is the number of pattern letters used divided by . Line L9 reports it only if it uses at least 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 -tuple of DNA fits in one word.
- Scan. Each position appends to one history list and reads the entries within distance , from the end, so it costs , where is the number of matches it finds. Each match costs amortized for its window list. In random DNA with uniform bases, has mean about , so the scan costs , which is ; for a sequence with no repeated tuples it is .
- Thresholds. The table for one window length takes time, and there are at most different lengths, all cached.
- Confirmation. A WDP of a window of length with a pattern of length costs time and space. Each distance is tested at most once per window length, so the number of tests is at most per distance, and a test window can grow to . This gives the crude worst case ; on sequences with few repeats the WDP work is small next to the scan.
- Space. The history lists take , the window lists , and a WDP table 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 also has matches at , 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 and , 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 for the distances , so that indels do not split the evidence across neighbouring distances. It uses three more tests: a random walk bound that gives , 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 , and filters reports with related periods. The code keeps one , a fixed minimum window, and the simple rule of line L12.
- Parameters of the paper. Benson gives two weight sets, and , two pairs of match and indel probabilities, and , 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 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 , 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 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.
# 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 -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
- 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
- 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
- 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.
| Ladder | Level | What the next level needs |
|---|---|---|
| Human proof | H1 sketch |
|
| Lean | L0 no Lean part |
|
| Code (python) | I0 not checked yet |
|
| Visual | V0 none |
|
| Writing | W2 basic |
|
Tag 3VVNE0 Edit this page History Report an error Markdown