Dynamic programming

Day 3

Rust for bioinformaticians

What this lecture is

Some recursions redo the same work over and over. We’ll see one (alignment) and the fix (remember answers in a table).

Sequence alignment — the problem

Given two sequences — two proteins, two reads, or a read against a reference — find the best way to line them up character-by-character so similar regions stack, allowing substitutions, insertions, and deletions.

A small example: align CACGT against CAGT.

  C A C G T
  | |   | |
  C A - G T          score: 4 matches, 1 gap

Why we care: detecting orthologous genes, calling mutations from sequencing reads, searching a database for similar proteins, mapping reads to a reference genome — all variants of “find the best alignment”.

The naive recursion — what we’d write first

Follow the English: at each step, align the last two characters, drop one from a, or drop one from b. Take the best of the three.

The key insight: an alignment of a against b reads from left to right and ends somewhere. The very last column of any alignment falls into exactly one of three cases:

  1. Match or mismatch — the last character of a is aligned with the last character of b. Both prefixes [the parts of each sequence up to that point] shrink by 1.
  2. Gap in b — the last character of a is aligned with - (a gap). Only a’s prefix shrinks.
  3. Gap in a — b’s last character is aligned with -. Only b’s prefix shrinks.

So the optimal score for the full alignment is the maximum of three smaller-prefix problems plus the appropriate score for that last column. That is what the function below computes — recursively.

fn align_naive(a: &[u8], b: &[u8]) -> i32 {
    if a.is_empty() || b.is_empty() {
        return missing(a, b);
    }
    max3(
        align_naive(&a[..a.len()-1], &b[..b.len()-1]) + score(a, b),
        align_naive(&a[..a.len()-1], b) + GAP,
        align_naive(a, &b[..b.len()-1]) + GAP,
    )
}

Each call makes three more calls. The same little subproblem is recomputed over and over — that’s the explosion.

The function is correct because it covers exactly those three cases; what makes it slow is that the same sub-prefix gets computed over and over.

Why naive recursion is too slow

The naive approach: try every possible alignment, return the highest score.

A length-\(n\) alignment can independently choose match, insert, or delete at each position — the number of alignments of two length-\(n\) sequences grows roughly like \(3^n\).

\(n\) \(3^n\)
10 59 049
20 3.5 × 10⁹
50 7.2 × 10²³

For \(n = 50\), that’s about 7 × 10²³ alignments — longer than the age of the universe in nanoseconds.

We need a smarter approach. The smarter approach is dynamic programming.

Dynamic programming — the idea

Observation: many of those exponential alignments share subproblems. The optimal alignment of CAC vs CA is computed once but reused thousands of times in the naive recursion.

Idea: define score[i][j] = the score of the best alignment of a[..i] against b[..j]. Compute each cell exactly once, in dependency order. This is called memoisation [storing computed answers in a table so you never compute the same subproblem twice].

Each cell depends on three neighbours (diagonal, up, left).

For two length-50 sequences:

  • Naive recursion: about 7 × 10²³ alignments — longer than the age of the universe.
  • DP table: about 2500 cells, each cheap.

Where else this trick shows up

The same recipe — define one subproblem per table cell, fill the table once — reappears in:

  • edit distance — how many single-character edits separate two strings
  • longest common subsequence — the diff algorithm
  • RNA secondary structure prediction
  • shortest path in a directed acyclic graph
  • Viterbi decoding for HMMs — basecalling, gene finding

Once you’ve seen DP, you’ll recognise it everywhere.

The rule for filling one cell

A 2x2 grid showing four cells [i-1][j-1], [i-1][j], [i][j-1] in grey as predecessors, with the cell [i][j] highlighted in orange as the target. Three arrows from the predecessors converge on the target.

Fill once in dependency order; each subproblem solved exactly once.

Three small alignment diagrams shown side by side. Each shows the last column of an alignment: case 1 is the last character of a stacked over the last character of b with a match-or-mismatch score; case 2 shows the last character of a stacked over a gap dash; case 3 shows a gap dash stacked over the last character of b. Each case is labelled with which DP neighbour cell it corresponds to (diagonal, up, left).

The three cases the rule chooses among: align the last two characters (match or mismatch), align a’s last with a gap, or align b’s last with a gap.

Three options for filling cell [i][j]:

  • diagonal: score[i-1][j-1] + s(a[i], b[j]) — match/mismatch
  • up: score[i-1][j] + gap — a[i] aligns to a gap in b
  • left: score[i][j-1] + gap — b[j] aligns to a gap in a

score[i][j] = the maximum of the three. CS jargon for this rule: the recurrence.

Filling the edges first

Before we apply the rule to the interior cells, we have to fill row 0 and column 0 by hand. They represent aligning a prefix of a against the empty string (or vice versa), and the only way to do that is with gaps.

For column 0 (aligning a[..i] against empty b): i gaps in b, total score i * gap.

For row 0 (aligning empty a against b[..j]): j gaps in a, total score j * gap.

A 5×5 grid representing the DP matrix. Row 0 (top) and column 0 (left) are highlighted in yellow with the values 0, -1, -2, -3, -4 along each. Annotation arrows on row 0 and column 0 indicate the cumulative gap penalty pattern. The interior cells are blank.

Row 0 and column 0 of the DP matrix filled with cumulative gap penalties (0, −1, −2, −3, …). These are the base cases that the recursive rule on the next slide will reference.

Once the edges are filled, the recurrence rule on the next slide fills every interior cell from its three already-computed neighbours.

The filled matrix

A worked Needleman-Wunsch matrix for a = ACGT and b = ACT with scoring match +1, mismatch -1, gap -1.

The filled matrix for ACGT vs ACT. Each cell maxes three neighbours.

For the highlighted cell score[3][2] (row G, column C):

  • diagonal: 0 + (-1) = -1 (G vs C, mismatch)
  • up: 2 + (-1) = 1 (gap in b) ← chosen
  • left: -1 + (-1) = -2 (gap in a)

So score[3][2] = 1. The bottom-right cell holds the score of the best alignment.

Traceback — recovering the alignment

The score alone tells you how good the alignment is, not what it actually is.

Trick: at each cell, also remember which neighbour won the max. Walking those back-pointers from the bottom-right cell to the top-left reproduces the alignment — this walk is called the traceback.

Same matrix, now read backwards: trace arrows from bottom-right to top-left.

Traceback — the path

The path through the matrix for CACGT vs CAGT, each step labelled by which neighbour won:

                    ε  C  A  G  T
                ε   0  ←  ←  ←  ←       legend
                C   ↑  ↘  .  .  .         ↘  diagonal (match/mismatch)
                A   ↑  .  ↘  .  .         ↑  up   (gap in b)
                C   ↑  .  .  ↓  .         ←  left (gap in a)
                G   ↑  .  .  .  ↘
                T   ↑  .  .  .  ↘

Reading chosen arrows along the path bottom-right → top-left:

walk:   ↘ ↘ ↓ ↘ ↘
align:  C A C G T
        | |   | |
        C A - G T

What else is DP good for?

The same skeleton — “define one subproblem per table cell, fill the table once” — powers:

  • Edit distance — how many single-character edits separate two strings (spell-checking, fuzzy matching)
  • RNA secondary structure prediction — fold an RNA sequence to minimum free energy
  • Viterbi decoding for HMMs — most likely hidden-state sequence; used in basecalling and gene finding

Once you’ve seen DP, you’ll recognise it everywhere.

To the exercise

cd day3/ex-alignment
cargo test