MATH 4310 · Computational Bioinformatics
Affine Gaps and Seed-and-Extend
Lesson 5 · 2027-01-27 · Week 3
Core question
How should we score a missing stretch and search many sequences for a match?
Gap opening and extension
Platelet-derived growth factor (PDGF) is a human protein that signals cells to divide. In 1983 two research groups determined partial amino-acid sequences of PDGF and searched the protein records of the day. The closest match was the product of v-sis, the gene that lets a monkey virus cause tumors, which suggested that the virus causes cancer by supplying a growth signal that never switches off.1,2,3 Such a search needs a scoring rule for each proposed correspondence and a strategy for finding useful candidates among many records.
First consider the scoring rule. A single slip during DNA replication or repair can remove or duplicate several consecutive bases, so one run of missing letters often records one event rather than several.3 The linear gap score from earlier lessons charges by the number of missing letters alone: one length-\(\ell\) gap and \(\ell\) separate one-letter gaps both score \(\ell g\). It cannot express a preference for one longer event over several separate events. An affine gap score gives starting a gap a different cost from continuing it.
Once that score is defined, the database creates a second problem. We do not know which record contains a useful match, and filling a complete local-alignment table against every record repeats expensive work. A seed is a short matching word that selects a location for closer comparison. The gap model determines how we rank candidate alignments; the seed rule determines which candidates reach that comparison.
Definition 5.1 Affine gap penalty
For penalties \(d_o>0\) and \(d_e>0\), the cost of a gap of length \(\ell\ge1\) is \[ G(\ell)=d_o+(\ell-1)d_e. \] Here \(d_o\) is the gap-open penalty and \(d_e\) is the gap-extension penalty. Usually \(d_o>d_e\).
We subtract this positive cost from an alignment score, just as a negative gap score \(g\) was added in earlier lessons. With \(d_o=4\) and \(d_e=1\), gaps of lengths 1, 2, and 3 cost 4, 5, and 6, while two separate one-letter gaps cost 8 because each represents its own event and pays its own opening.
The difference is visible even in the toy strings AAAA and AA. Both correspondences in Figure 5.1 have two matches and two gap columns. Linear scoring ties them; affine scoring charges 5 for the single two-letter gap and 8 for the two separate gaps. The repeated A bases leave the correspondence ambiguous, so this preference comes from the gap model rather than from additional letter evidence.
Figure 5.1. Two alignments of AAAA with AA use the same number of gap columns, in one run (left) or two runs (right). With opening penalty 4 and extension penalty 1, their gap costs are 5 and 8, expressing a preference for fewer separate events.
The cost of the next column now depends on the preceding column.
Appending C/- after a paired-letter column costs \(d_o\), while appending it after another
letter/gap column costs only \(d_e\).
Two prefix alignments can therefore have different continuation costs
even when they end at the same \((i,j)\). Keeping only their overall maximum
can discard a lower-scoring prefix whose next extension is cheaper. One
remedy lets a single move cross a whole gap of any length \(\ell\) at cost \(G(\ell)\), but then cell \((i,j)\) compares \(i+j\) possible gaps and the table costs
\(\mathcal O(nm(n+m))\).3
Instead, we retain a best score for each possible ending type.4
Three alignment states
Definition 5.2 Affine alignment states
For prefixes ending at \((i,j)\), let
- \(M(i,j)\) be the best score ending with \(x_i\) aligned to \(y_j\);
- \(I_x(i,j)\) be the best score ending with \(x_i\) aligned to a gap;
- \(I_y(i,j)\) be the best score ending with a gap aligned to \(y_j\).
The recurrences are
Equation (5.1)
\[ \begin{aligned} M(i,j)&=s(x_i,y_j)+\max\{M,I_x,I_y\}(i-1,j-1),\\ I_x(i,j)&=\max\{M(i-1,j)-d_o,\ I_x(i-1,j)-d_e\},\\ I_y(i,j)&=\max\{M(i,j-1)-d_o,\ I_y(i,j-1)-d_e\}. \end{aligned} \]
The first candidate in a gap state opens a gap; the second extends one. Entering \(I_x\) consumes the next letter of \(x\) but none of \(y\), so its predecessors lie at \((i-1,j)\). Entering \(I_y\) consumes only a letter of \(y\), and entering \(M\) consumes one from each. These index changes are the vertical, horizontal, and diagonal moves from Lesson 3, with the ending type now recorded as well.
This version forbids immediate switches between \(I_x\) and \(I_y\); other formulations allow them, and the convention determines which alignments are admissible. The name \(M\) denotes any paired-letter column, match or mismatch.
Figure 5.2. Allowed ending-state transitions for affine alignment. The highlighted loop continues a gap for extension cost rather than paying another opening cost.
For global alignment, set \(M(0,0)=0\), \[ I_x(i,0)=-d_o-(i-1)d_e,\qquad I_y(0,j)=-d_o-(j-1)d_e, \] for \(i,j\geq1\), and set every other border state except \(M(0,0)\) to \(-\infty\). The final global score is \(\max\{M(n,m),I_x(n,m),I_y(n,m)\}\).
Example 5.1 A worse prefix with a better continuation
Use \(x=\texttt{ACG}\), \(y=\texttt{C}\), match \(+1\), mismatch \(-1\), \(d_o=4\), and \(d_e=1\). At \((2,1)\), two endings compete: \[ \begin{array}{c|c|c} \text{alignment of AC and C} & \text{ending state} & \text{score}\\ \texttt{AC}/\texttt{-C} & M & -4+1=-3\\ \texttt{AC}/\texttt{C-} & I_x & -1-4=-5 \end{array} \] The paired-letter prefix wins by two points. But appending G/- opens a new gap after the first alignment and extends the existing gap after the second: \[ I_x(3,1)=\max\{M(2,1)-4,\ I_x(2,1)-1\} =\max\{-7,-6\}=-6. \] Discarding the lower prefix score \(-5\) would lose this better continuation. Scoring the two complete alignments under both gap models shows that the choice of model changes the answer: \[ \begin{array}{c|c|c} \text{alignment} & \text{linear, } g=-4 & \text{affine, } d_o=4,\ d_e=1\\ \hline \texttt{ACG}/\texttt{-C-} & 1-4-4=-7 & 1-4-4=-7\\ \texttt{ACG}/\texttt{C--} & -1-4-4=-9 & -1-5=-6 \end{array} \] Linear gaps prefer ACG/-C-, which keeps the C/C match and pays for two separate one-letter gaps. Affine gaps prefer ACG/C–, accepting a mismatch so that the two missing letters form one run and pay one opening.
The best affine score is \(-6\); ACG/–C also attains it. That tie leaves the placement ambiguous, but both optima use one opening rather than two. The model encodes a preference for one insertion or deletion event; it does not establish which event occurred.
Key idea
With affine gaps, the cost of the next column depends on how the alignment so far ends. Each cell therefore keeps one best score per ending state, because a prefix that scores lower now can still lead to the best complete alignment.
Theorem 5.1 Correctness of the three-state recurrence
For every state and cell, the recurrence in Equation 5.1 gives the best score among alignments of the two prefixes that end in that state.
Proof
Induct on \(i+j\); the border values cover the only alignments available there. Remove the final column of an optimal alignment that ends in a given state at \((i,j)\). What that column adds depends only on how the remaining prefix ends: \[ x_i/y_j\text{ adds }s(x_i,y_j)\text{ after any state};\qquad x_i/-\text{ adds }\begin{cases}-d_o&\text{after }M,\\-d_e&\text{after }I_x,\\\text{not allowed}&\text{after }I_y.\end{cases} \] Once the prefix’s ending state is fixed, so is the added amount, and the prefix must be optimal among prefixes with that ending; a better one would improve the whole alignment. Maximizing over the allowed ending states gives each line of Equation 5.1, with \(I_y\) symmetric to \(I_x\). Appending the indicated column to each optimal prefix shows that every candidate is attained.
Each of the three tables has \((n+1)(m+1)\) entries. An interior entry compares at most three predecessors, so the time and memory costs remain \(\mathcal O(nm)\), rather than the \(\mathcal O(nm(n+m))\) of trying every gap length at each cell.
Algorithm Score a global alignment with affine gaps
Input: strings \(x\) and \(y\) of lengths \(n\) and \(m\), a substitution score \(s\), and gap costs \(d_o\) and \(d_e\).
Output: the best global score with affine gap costs and no direct switch between opposite gap states.
- Create tables \(M\), \(I_x\), and \(I_y\) with rows \(0,\ldots,n\) and columns \(0,\ldots,m\). Initialize every entry to \(-\infty\).
- \(M(0,0)\leftarrow 0\).
// score the empty alignment For\(i=1,\ldots,n\), \(I_x(i,0)\leftarrow -d_o-(i-1)d_e\).// one gap run in yFor\(j=1,\ldots,m\), \(I_y(0,j)\leftarrow -d_o-(j-1)d_e\).// one gap run in xFor\(i=1,\ldots,n\), andfor\(j=1,\ldots,m\) within each row:// fill the interior- \(b\leftarrow\max\{M(i-1,j-1),\) \(I_x(i-1,j-1),\) \(I_y(i-1,j-1)\}\).
// best diagonal score - \(M(i,j)\leftarrow b+s(x_i,y_j)\).
// score the final pair - \(I_x(i,j)\leftarrow\max\{M(i-1,j)-d_o,\)
\(I_x(i-1,j)-d_e\}\).
// open or extend a gap in y - \(I_y(i,j)\leftarrow\max\{M(i,j-1)-d_o,\)
\(I_y(i,j-1)-d_e\}\).
// open or extend a gap in x
- \(b\leftarrow\max\{M(i-1,j-1),\) \(I_x(i-1,j-1),\) \(I_y(i-1,j-1)\}\).
Return\(\max\{M(n,m),I_x(n,m),I_y(n,m)\}\).// allow any ending state
Here gap_in_y implements \(I_x\), because a letter of \(x\) faces a gap in \(y\); gap_in_x implements \(I_y\).
Python Score a global alignment with affine gaps
def affine_global_score(
x: str, y: str, match: int = 1, mismatch: int = -1,
gap_open: int = 4, gap_extend: int = 1,
) -> float:
"""Return a global score with no direct switches between opposite gaps."""
n, m = len(x), len(y)
paired = [[float("-inf")] * (m + 1) for _ in range(n + 1)]
gap_in_y = [[float("-inf")] * (m + 1) for _ in range(n + 1)]
gap_in_x = [[float("-inf")] * (m + 1) for _ in range(n + 1)]
paired[0][0] = 0
for i in range(1, n + 1):
gap_in_y[i][0] = -gap_open - (i - 1) * gap_extend
for j in range(1, m + 1):
gap_in_x[0][j] = -gap_open - (j - 1) * gap_extend
for i in range(1, n + 1):
for j in range(1, m + 1):
substitution = match if x[i - 1] == y[j - 1] else mismatch
paired[i][j] = substitution + max(
paired[i - 1][j - 1],
gap_in_y[i - 1][j - 1],
gap_in_x[i - 1][j - 1],
)
gap_in_y[i][j] = max(
paired[i - 1][j] - gap_open,
gap_in_y[i - 1][j] - gap_extend,
)
gap_in_x[i][j] = max(
paired[i][j - 1] - gap_open,
gap_in_x[i][j - 1] - gap_extend,
)
return max(paired[n][m], gap_in_y[n][m], gap_in_x[n][m])
affine_global_score("ACG", "C"), affine_global_score("ACG", "C", gap_extend=4)For ACG/C, the affine score is \(-6\), as in Example 5.1. Setting the opening and extension costs both to 4 recovers the best linear score of \(-7\) for this pair. Impossible border states remain \(-\infty\) so that they can never win a maximum.
The function returns a score. Recovering the alignment would require traceback that records both a predecessor cell and its state. A pointer to \((i-1,j)\) alone cannot tell whether that step opened a gap from \(M\) or extended it from \(I_x\).
Database search and seeds
If a query has length \(n\) and a database contains total length \(N\), exact dynamic programming takes \(\mathcal O(nN)\) time. For one query this may already mean billions of cell updates. Database search tools first look for short promising matches and run expensive alignment only near those locations.
Definition 5.3 Seed
A seed is a short pattern from the query used to find candidate positions in a target. An exact \(k\)-mer seed requires the same length-\(k\) word in both sequences.
Algorithm Seed and extend
Input: query \(x\) and target \(y\) of lengths \(n\) and \(m\), seed length \(k\geq 1\), substitution and gap scores, a positive score-drop threshold \(D\), a score cutoff \(\tau\), and window padding \(w\geq0\). Use positions starting at zero.
Output: scored candidate alignments between the query and the target.
- Create an index \(J\) of target
starts, with an empty list for each word.
For\(j=0,\ldots,m-k\):- \(u\leftarrow y_j\ldots y_{j+k-1}\).
// read one target word - Append \(j\) to \(J(u)\).
// index its start
- \(u\leftarrow y_j\ldots y_{j+k-1}\).
- Create an empty
list of hits.
For\(i=0,\ldots,n-k\):// scan query words- \(u\leftarrow x_i\ldots x_{i+k-1}\).
// read one query word Foreach \(j\) in \(J(u)\), append \((i,j)\) to the hit list.// record exact seed hits
- \(u\leftarrow x_i\ldots x_{i+k-1}\).
- Write \(s(a,b)\) for the supplied
substitution score. Create an empty list of candidate alignments.
Foreach hit \((i,j)\):- Offset \(\delta\leftarrow j-i\). Seed score \(S_0\leftarrow\sum_{t=0}^{k-1}s(x_{i+t},y_{j+t})\).
// seed diagonal and score Fordirection \(\sigma=-1\) (left) and then \(\sigma=1\) (right):If\(\sigma=-1\), endpoint \(e\leftarrow i\).Otherwise, \(e\leftarrow i+k-1\).// start at the seed edge- Running score \(S\leftarrow 0\), best flank score \(B\leftarrow 0\), and next query position \(p\leftarrow e+\sigma\).
While\(0\leq p<n\), \(0\leq p+\delta<m\), and \(B-S<D\):// stop D below best- \(S\leftarrow S+s(x_p,y_{p+\delta})\).
// score one more column If\(S>B\), \(B\leftarrow S\) and \(e\leftarrow p\).// save the best extension- \(p\leftarrow p+\sigma\).
// advance along the flank
- \(S\leftarrow S+s(x_p,y_{p+\delta})\).
- Record the best flank score \(B_\sigma\leftarrow B\) and endpoint \(e_\sigma\leftarrow e\).
If\(S_0+B_{-1}+B_1\geq\tau\):// filter by ungapped score- Use query
interval \([e_{-1},e_1]\) and target
interval \([e_{-1}+\delta,e_1+\delta]\). Pad each
interval by up to \(w\) bases on each
end, stopping at the string boundaries.
// pad the window - Run local
alignment on these two windows using the supplied scores. Append the
alignment and score, with coordinates in the original strings.
// align with gaps
- Use query
interval \([e_{-1},e_1]\) and target
interval \([e_{-1}+\delta,e_1+\delta]\). Pad each
interval by up to \(w\) bases on each
end, stopping at the string boundaries.
- Offset \(\delta\leftarrow j-i\). Seed score \(S_0\leftarrow\sum_{t=0}^{k-1}s(x_{i+t},y_{j+t})\).
Returnthe list of candidate alignments, reporting identical alignments at the same coordinates once.
The Python function implements the first two steps. Index lookup
avoids considering most query-target position pairs. For query
ACGTAC and target AGGTTC, the 3-mer call
should return no hits. The 2-mer call should return one hit,
[(2, 2)], because GT begins at zero-based position 2 in
both strings.
Python Find shared exact seeds
def exact_seed_hits(query: str, target: str, k: int) -> list[tuple[int, int]]:
"""Return positions of all shared exact length-k words."""
if k < 1:
raise ValueError("k must be positive.")
index = {}
for target_start in range(len(target) - k + 1):
word = target[target_start:target_start + k]
index.setdefault(word, []).append(target_start)
hits = []
for query_start in range(len(query) - k + 1):
word = query[query_start:query_start + k]
for target_start in index.get(word, []):
hits.append((query_start, target_start))
return hits
exact_seed_hits("ACGTAC", "AGGTTC", 3), exact_seed_hits("ACGTAC", "AGGTTC", 2)The function returns pairs of zero-based start positions
(query_start, target_start), not alignments. The difference
target_start - query_start identifies a candidate ungapped
offset, along which extension is cheap because the base pairing is
fixed. An insertion or deletion changes the offset, so gapped extension
must be able to leave that diagonal; a window or band limits the cells
examined, and an alignment that leaves it can still be missed.
To see one extension, take the query TGATACGTAC and the
target CCATACGTTCAG with \(k=4\), scores \(+1\) and \(-1\), and a rule that stops when the
running score falls 2 below its best. The word ACGT hits at
(4, 4). Extending right pairs A/T (running score \(-1\)) and C/C (running 0) before the query
ends, so the right side adds nothing. Extending left pairs T/T and A/A
(running 1, then 2), then G/C and T/C (running 1, then 0); the score is
now 2 below its best, so extension stops and keeps the two matched
letters. The result is ATACGT over ATACGT with score \(4+2+0=6\). The hits of TACG at
(3, 3) and ATAC at (2, 2) lie on the same
offset and extend to the same alignment, so a search reports it
once.
The original BLAST algorithm also admits high-scoring protein words that need not match exactly, then extends its word hits in the same way.4,5
Seed sensitivity
The ungapped ACGTAC/AGGTTC comparison has four matches and two mismatches, scoring 2 under \(+1/-1\). In Figure 5.3, the mismatches split those matches into runs of lengths 1, 2, and 1, so no 3-mer is shared at this offset (and checking all the words shows none at any other). The 3-mer index finds no candidate while the 2-mer index finds GT: a promising final score cannot help if the seed stage never sends the location to extension.
Figure 5.3. Four paired bases match in ACGTAC/AGGTTC, but the two mismatch dots split them into runs of lengths 1, 2, and 1. The exact 3-mer search misses this pair; a 2-mer search finds the central GT run.
Definition 5.4 Seed sensitivity
For a specified class of true alignments, seed sensitivity is the fraction that contain at least one seed accepted by the search rule.
For a tiny sensitivity check, take ACGTAC as the query and suppose the true targets are ACGTTC, ACATAC, AGGTTC, and ATGTTC. The first two contain a shared 3-mer; the last two do not. This class has exact 3-mer sensitivity \(2/4\), while all four contain a shared 2-mer. The fraction refers to this specified class, rather than a universal property of \(k\).
Shorter seeds improve sensitivity, but they also produce more chance hits, and every hit costs an extension. We can count the chance hits under a simple background. If both sequences are independent, uniformly random DNA, two length-\(k\) words agree with probability \(4^{-k}\). A query of length \(n\) and a target of length \(N\), both at least \(k\), offer \((n-k+1)(N-k+1)\) pairs of starting positions. Let \(h\) count the exact seed hits. Adding the agreement probability over all position pairs gives \[ \mathbb E[h]=(n-k+1)(N-k+1)\,4^{-k}. \] The first two factors count the comparisons the index makes implicitly; the last is the chance that any one of them succeeds. Overlapping words make hit events dependent, but an expected count still adds over events. Lengthening the seed by one letter multiplies the expected number of chance hits by \(4^{-(k+1)}/4^{-k}=1/4\), while the number of position pairs barely changes. For a length-100 query against a length-1,000 target, \(k=4\) gives \(97\cdot997/256\approx378\) expected chance hits and \(k=8\) gives \(93\cdot993/65536\approx1.4\).
Python Simulate a shared region and count seed hits
import numpy as np
rng = np.random.default_rng(7)
target = "".join(rng.choice(list("ACGT"), size=1000))
true_offset = 400
# The query copies 100 target bases, substituting each with probability 0.2.
query_letters = []
for base in target[true_offset:true_offset + 100]:
if rng.random() < 0.8:
query_letters.append(base)
else:
query_letters.append(rng.choice([b for b in "ACGT" if b != base]))
query = "".join(query_letters)
hits_by_length = {}
for k in (4, 8):
hits = exact_seed_hits(query, target, k)
true_hits = [(q, t) for q, t in hits if t - q == true_offset]
chance_hits = [(q, t) for q, t in hits if t - q != true_offset]
hits_by_length[k] = (true_hits, chance_hits)Figure 5.4. Exact seed hits for a length-100 query against a random length-1,000 target; the query is a copy of target positions 401 to 500 with about 20% of its bases substituted. Red hits lie on the true offset and grey hits arise by chance. With k = 4 the true diagonal is surrounded by about as many chance hits as the formula predicts; with k = 8 almost all chance hits disappear, and so do the true seeds in stretches where substitutions leave no 8-letter match.
Figure
5.4 runs exact_seed_hits on such a pair, with one
planted region of 80% identity. At \(k=4\) the 376 chance hits agree with the
predicted 378, since off the true diagonal the two sequences are still
unrelated, and each would send the search to an extension that finds
nothing. At \(k=8\) one chance hit
remains, but the true diagonal has lost its seeds wherever substitutions
fall closer together than eight letters. A region with slightly lower
identity could lose all of them, and an alignment containing no accepted
seed is never proposed; unlike full dynamic programming, the search can
miss the best alignment. Doolittle’s search compared one protein against
every record then known; against a modern database, the seed stage
rather than the alignment table decides which matches can be found at
all. Spaced seeds, which require matches only at selected positions
within a longer window, are one way to keep the low chance-hit rate of a
long seed while tolerating some substitutions.
Going deeper a bounded-mismatch guarantee
The expected-hit calculation addresses workload. For sensitivity, a different question is whether mismatches can destroy every accepted word. When there are few of them, they cannot: an ungapped alignment of length \(L\) with \(t<L\) mismatches contains a matching run of length at least \[ \left\lceil\frac{L-t}{t+1}\right\rceil, \] and therefore an exact \(k\)-mer seed for every \(k\) no larger than that bound.
Proof sketch
The \(t\) mismatches cut the alignment into \(t+1\) runs of matches, some possibly empty, whose lengths \(r_1,\ldots,r_{t+1}\) account for every matching position: \[ r_1+r_2+\cdots+r_{t+1}=L-t . \] If every run were shorter than the average \((L-t)/(t+1)\), the sum would fall short of \(L-t\). So some run has \(r_i\geq(L-t)/(t+1)\), and because \(r_i\) is an integer it reaches the ceiling.
For \(L=20\) and \(t=3\), some run has at least five matches, guaranteeing a 5-mer seed. An 8-mer seed has no such guarantee. Read mappers use the same pigeonhole idea: cut a read into \(t+1\) pieces, and any placement with at most \(t\) mismatches matches at least one piece exactly, so exact lookups of the pieces find every such placement.3 Gaps need different accounting because they interrupt the correspondence between positions.
For fixed \(k\), building the index takes \(\mathcal O(N)\) expected time with a hash table, and looking up the query’s words and listing \(h\) hits takes \(\mathcal O(n+h)\) before any extension. Repeated words can make \(h\) as large as \(\mathcal O(nN)\), so the index speeds up typical searches but not every input.
Limitations
- Affine gaps still use a simple duration model. Every extension has the same cost, regardless of gap length or position.
- Seeds can miss real alignments. Distributed mismatches or gaps can destroy every accepted word.
- Repeats flood the candidate list. Common seeds occur at many positions and erase the speed advantage unless the method filters or downweights them.
- Statistical significance depends on the search. The same raw score can be less surprising in a larger database or in repetitive sequence.
Exercises
Exercise 5.1. With \(d_o=5\) and \(d_e=1\), compare the cost of one length-4 gap with four separate length-1 gaps. State the event interpretation.
Exercise 5.2. For the ACG/C example, compute \(M(3,1)\) from its predecessor states. Explain why it ties \(I_x(3,1)\) even though the two alignments pair the target C with different query letters.
Exercise 5.3. Set \(d_o=d_e\). Explain why the score of every gap becomes linear in its length, even though the algorithm still uses three tables. Does changing the penalties also remove the restriction on immediate switches between opposite gap states?
Exercise 5.4. Construct two length-8 strings with a positive ungapped score under match \(+1\), mismatch \(-1\), but no shared exact 3-mer. Mark the mismatches.
Exercise 5.5. A target database is highly repetitive. Predict how decreasing \(k\) affects the number of seed hits, runtime, and sensitivity.
References 6 sources
Cited in the text
Also drawn on