Skillversitas

Pairwise Sequence Alignment

Pairwise alignment compares two sequences and finds the best correspondence between them, using substitution scores and gap penalties. Modern Biopython implements this in Bio.Align.PairwiseAligner (the new API, replacing the old Bio.pairwise2) with built-in scoring matrices for proteins and nucleotides.

Basic Nucleotide Alignment

from Bio.Align import PairwiseAligner

aligner = PairwiseAligner()
aligner.mode = "global"
aligner.substitution_matrix = "NUC.4.4"   # +1 match, -1 mismatch
aligner.open_gap_score = -10
aligner.extend_gap_score = -0.5

seq1 = "AATGGCCTA"
seq2 = "AGGCTTA"
for aln in aligner.align(seq1, seq2):
    print(aln.score)
    print(aln[0].seq)
    print(aln[0])
    print(aln[1].seq)

Protein Alignment with BLOSUM

from Bio.Align import PairwiseAligner
from Bio import SubstitutionMatrix

aligner = PairwiseAligner()
aligner.mode = "local"
aligner.substitution_matrix = SubstitutionMatrix.read(
    "BLOSUM62.mat", "iupac", 20)
# or simply: aligner.substitution_matrix = "BLOSUM62"

p1 = "MKTAYIAKQRQISFVKSHFSR"
p2 = "MKTAYIAKQRQISFVKSHF"
for aln in aligner.align(p1, p2):
    print(round(aln.score, 2))
    print(aln[0])

Global vs Local

ModeAlignsUse when
globalentire length of both sequencessequences are similar overall (orthologs)
localbest-matching sub-regionsyou expect conserved domains amid divergence

Gap Penalties Matter

open_gap_score penalizes starting a gap; extend_gap_score penalizes each additional gap position. A large open penalty produces fewer, longer gaps - usually the right default for homologous sequences. Tune both if your results are too gappy or too rigid.

Identity and Distance

aln = aligner.align(p1, p2)[0]
print(aln.identity / aln.shape[1])  # fraction of identical columns
print(aln.distance)                 # normalized distance metric

Summary

Use Bio.Align.PairwiseAligner for pairwise alignment: set mode to global or local, choose a substitution matrix (NUC.4.4, BLOSUM62), tune gap penalties, and iterate aligner.align(a, b) for the top hits. Report score, identity, and distance to quantify how related two sequences are.