Skip to content

Sequence alignment

Score global, local, and affine-gap sequence alignments with Needleman-Wunsch, Smith-Waterman, and Gotoh.

NeedlemanWunsch, SmithWaterman, and Gotoh are scoring APIs, not distance or similarity measures. They expose two methods:

  • score(s0, s1) returns the optimal alignment score as a raw float. Scores may be negative, and no normalization is applied.
  • alignment(s0, s1) returns the alignment as a list of (op, source, target) tuples. op is "match", "substitute", "insert", or "delete". A gap is represented by "" on the missing side.

Higher scores mean better alignments. Because the values are unnormalized, do not compare them across different scoring parameters or interpret them as percentages. The classes do not provide distance() or similarity() methods.

For Needleman-Wunsch and Gotoh, applying the tuples in order walks both full strings: joining the non-empty source elements reconstructs s0, and joining the non-empty target elements reconstructs s1. Smith-Waterman returns only the best local alignment, so the same reconstruction yields contiguous substrings of the inputs rather than the full strings.

Defaults and construction

All three classes accept keyword arguments:

NeedlemanWunsch(match_score=1.0, mismatch_score=-1.0, gap_cost=1.0)
SmithWaterman(match_score=1.0, mismatch_score=-1.0, gap_cost=1.0)
Gotoh(match_score=1.0, mismatch_score=-1.0, gap_open=1.0, gap_extend=0.5)
  • match_score is added for every pair of equal characters.
  • mismatch_score is added for every pair of unequal characters and is normally negative.
  • gap_cost is subtracted for every gap column in Needleman-Wunsch and Smith-Waterman.
  • gap_open and gap_extend define the affine gap cost in Gotoh: a gap run of length L costs gap_open + (L - 1) * gap_extend.

All scores must be finite, and gap parameters must be finite and non-negative. Invalid values raise ValueError. The constructor values are available as read-only attributes: match_score, mismatch_score, and gap_cost (or gap_open and gap_extend for Gotoh).

Needleman-Wunsch

Needleman-Wunsch performs global alignment with a linear gap penalty. Every character of both strings is either aligned with a character of the other string or paired with a gap.

For strings s0 and s1 of lengths m and n, the dynamic-programming matrix is filled with:

S[i][j] = max(
    S[i - 1][j - 1] + substitution(s0[i - 1], s1[j - 1]),
    S[i - 1][j] - gap_cost,
    S[i][j - 1] - gap_cost,
)

substitution is match_score for equal characters and mismatch_score for unequal characters. The first row and column are initialized to -j * gap_cost and -i * gap_cost, and the final score is S[m][n].

Example

from strsimpy import NeedlemanWunsch

nw = NeedlemanWunsch()
print(nw.score("GATTACA", "GCATGCU"))
print(nw.score("", "abc"))
print(nw.alignment("CAT", "CUT"))

will produce:

0.0
-3.0
[('match', 'C', 'C'), ('substitute', 'A', 'U'), ('match', 'T', 'T')]

An empty input is aligned with one gap per character of the other string, so "" versus "abc" scores -3.0.

Smith-Waterman

Smith-Waterman performs local alignment with a linear gap penalty. It finds the best-scoring alignment of a contiguous substring of s0 with a contiguous substring of s1, ignoring unrelated prefixes and suffixes.

The recurrence is the Needleman-Wunsch recurrence with every cell clamped at zero:

S[i][j] = max(
    0,
    S[i - 1][j - 1] + substitution(s0[i - 1], s1[j - 1]),
    S[i - 1][j] - gap_cost,
    S[i][j - 1] - gap_cost,
)

The score is the maximum cell anywhere in the matrix, not the bottom-right cell. It is therefore always non-negative. If no positive-scoring local alignment exists, the score is 0.0 and alignment() returns an empty list. Otherwise the returned operations cover contiguous substrings of both inputs.

Example

from strsimpy import SmithWaterman

sw = SmithWaterman()
print(sw.score("AGACTAGTTAC", "CGAGACGT"))
print(sw.score("abc", "xyz"))
print(sw.alignment("abc", "xyz"))

will produce:

4.0
0.0
[]

The best local alignment matches the substring AGAC in both strings, scoring four matches. Some reference implementations, including TextDistance, return the bottom-right matrix cell instead of the maximum and therefore report 1.0 for this pair. That is not the Smith-Waterman local-alignment score used here.

Gotoh

Gotoh performs global alignment with affine gap penalties. A gap run of length L costs:

gap_open + (L - 1) * gap_extend

The first gap column costs gap_open, and every additional column in the same run costs gap_extend. The defaults are gap_open=1.0 and gap_extend=0.5. The implementation keeps three dynamic-programming states: aligned character pairs, a gap in the target, and a gap in the source.

Example

from strsimpy import Gotoh

gotoh = Gotoh()
print(gotoh.score("GATTACA", "GCATGCU"))
print(gotoh.score("", "abc"))
print(gotoh.score("a", "aaaa"))

will produce:

0.0
-2.0
-1.0

For "" versus "abc", the whole string is one gap run of length three: -(1.0 + 2 * 0.5) = -2.0. For "a" versus "aaaa", one match plus a three-character gap run gives 1.0 - (1.0 + 2 * 0.5) = -1.0.

Empty strings are handled explicitly: the entire non-empty input is a single gap run. TextDistance, by contrast, raises IndexError for Gotoh with an empty input.

gap_extend=0 is not a linear gap

Affine scoring with zero extension still charges gap_open once per gap run, so it does not reduce to Needleman-Wunsch’s per-character gap cost:

from strsimpy import Gotoh, NeedlemanWunsch

gotoh = Gotoh(gap_open=1.0, gap_extend=0.0)
nw = NeedlemanWunsch(gap_cost=1.0)

print(gotoh.score("a", "aaaa"))
print(nw.score("a", "aaaa"))

will produce:

0.0
-2.0

Gotoh pays one match (+1.0) and one gap run (-1.0) for 0.0. Needleman-Wunsch pays three gap characters (-3.0) for -2.0. The two models agree only when every gap run has length one.

Cost and tie-breaking

  • All three algorithms run in O(m * n) time for strings of lengths m and n.
  • score() keeps rolling rows, so it uses O(min(m, n)) memory. Gotoh keeps three rolling rows and still uses O(min(m, n)) memory.
  • alignment() builds the full traceback matrix, so it uses O(m * n) memory.
  • Ties are resolved deterministically:
    • Needleman-Wunsch traces back from the bottom-right cell and prefers the diagonal move (match or substitution), then deletion (up), then insertion (left).
    • Smith-Waterman starts at the first maximum cell in row-major order and uses the same preference while tracing.
    • Gotoh prefers the paired state at the final cell, then a gap in the target, then a gap in the source. Gap states prefer opening a new run from a paired state over extending an existing run.

Repeated calls therefore return the same alignment. Other libraries may choose a different optimal alignment with the same score when ties occur.

Limitations

  • Only a single match_score and a single mismatch_score are supported. There is no API for an arbitrary substitution matrix with per-character scores.
  • alignment() emits one operation per gap character. Consecutive insertions or deletions are not grouped into gap runs, even for Gotoh, so a three-character gap appears as three tuples. Group adjacent gap operations yourself if you need runs.
  • The classes implement scoring only. There is no normalized distance or similarity, and the returned values are not comparable across different scoring parameters.

Type to search…

↑↓ navigate↵ selectEsc close