LSMA

LONDON SCHOOL OF MULTIOMICS & AI

Free course

Free course

0 of 73 lessons

Lesson 1 of 9

Module 4 · Comparing sequences

Why compare sequences

Why compare sequences

Why compare sequences

Comparing sequences is how a gene's history and likely job are worked out. Learn the difference between homology, similarity and identity, tell orthologues from paralogues, and run your first comparison in Python.

⏱ 15 min readModule 4 · Comparing sequencesFree
Lesson at a glance6 steps · about 15 min
  1. Why compare sequences at all
  2. Running the code in this course
  3. Homology is all or nothing
  4. Orthologues and paralogues
  5. A first comparison in Python
  6. What a comparison can and cannot tell you

Why compare sequences at all

Comparing sequences is the most common task in bioinformatics. You find a new gene and want to know what it does. You see a variant in a patient and want to know whether that position has stayed the same across species. You read about a mouse model and want to know how close the mouse protein is to the human one. Each of these questions is answered the same way: line the sequences up and look at where they agree.

The reason this works is evolution. Genes are copied from parent to offspring, and from one gene to a new copy within a genome, with small changes each time. Two sequences that descend from the same ancestor still carry traces of it, and a function worked out for one is a good first guess for the other. Most of what is known about human genes was first learned in yeast, flies, worms or mice and carried across by sequence comparison.

This module, Module 4, is the first in the course with Python code. It builds on Module 2, where you met FASTA files and protein records in UniProt. Here you will compare sequences yourself, first by eye and then with Python.

Module 3, The command line, gave you the tools to handle sequence files: to look inside them, count and filter records, and run the same steps on many samples. Those tools treat a sequence as a line of text. This module asks what the sequences mean. By comparing one sequence with another, you can tell whether two genes are related, which positions matter and what an unknown sequence probably is.

Running the code in this course

You do not need to install anything. The code runs in Google Colab, a free service that gives you a Python notebook in your web browser. A notebook is a page made of cells: you type code into a cell, run it, and the output appears just below.

  1. Open colab.research.google.com and sign in with a Google account.
  2. Choose New notebook. An empty code cell appears.
  3. In the first cell, type !pip install biopython and run it with the play button, or press Shift and Enter together. The ! tells Colab to pass the line to the computer behind the notebook, which downloads Biopython, a free Python library for biological data. It takes a few seconds.
  4. For each code block in a lesson, press Copy, paste it into a new cell (the + Code button), and run it. Run the blocks in order, because later blocks often use names made in earlier ones.

Each lesson says which packages it needs. Some lessons later in the course install others in the same way. If Colab is closed for a while it forgets everything, including the install; just run the cells again from the top. The output shown under each block is the real output we got, so yours should match.

The most common error is a NameError, which means Python was asked to use a name it has not seen. It almost always means an earlier block was skipped, or the notebook was reset; run the earlier blocks again and it goes away. The ! lines are shell commands of the kind you used in Module 3, and pip install plays the same role for Python packages that conda install played in Installing software with conda. Colab is a convenience, not a requirement: the same code runs in any Python 3 set-up where Biopython is installed.

Homology is all or nothing

Three words are used, and often mixed up, when sequences are compared. Getting them straight now will save confusion in every later lesson.

WordWhat it meansHow it is expressed
HomologyThe two sequences descend from a common ancestorYes or no; never a percentage
IdentityThe share of aligned positions with exactly the same letterA percentage, such as 84%
SimilarityThe share of aligned positions with the same or a chemically alike letterA percentage, or a score

How to read this table

The first row is a statement about history; the other two are measurements you make on an alignment. An alignment is the two sequences written one above the other, with gaps added where needed, so that letters thought to come from the same ancestral position sit in the same column. Pairwise alignment: dot plots, scores and gaps shows how alignments are built.

  • Homology is a conclusion about the past. Either two genes share an ancestor or they do not, just as two people either are or are not cousins. So "these proteins are 70% homologous" is a mistake, even though you will see it in print. The correct phrase is "70% identical".
  • Identity is counted, column by column. It needs no knowledge of chemistry: the letters are either the same or not.
  • Similarity also gives credit for swaps that keep the protein's chemistry, such as leucine (L) for isoleucine (I), two greasy amino acids of almost the same shape. Which swaps count as alike is decided by a scoring table, the subject of Scoring matrices: PAM and BLOSUM. For DNA, identity and similarity are usually the same thing.

The link between them is this: high identity or similarity is the evidence, and homology is the conclusion. Two proteins of a few hundred amino acids that are 40% identical along their whole length are almost certainly homologous, because chance does not produce that much agreement. Below about 20 to 30% identity, real relatives and chance matches start to look alike; this is often called the twilight zone. A low identity therefore does not prove two proteins are unrelated. It means sequence alone cannot settle the question, and evidence such as 3D structure may be needed.

Protein comparisons see further back in time than DNA comparisons. The genetic code has several codons for most amino acids, so the DNA can change while the protein stays the same, and DNA has only four letters, so two random DNA sequences already match at about one position in four. When you want to find distant relatives of a gene, compare the proteins.

The opposite trap also exists: similarity without homology. Some stretches of protein are made of only a few kinds of amino acid, such as a long run of glutamines or a region rich in prolines and serines. These are called low-complexity regions, and two unrelated proteins can match well across them simply because both are repetitive. Search tools hide such regions by default for this reason, as Searching databases fast: similarity search and E-values explains. A match that rests mainly on a repetitive stretch is weak evidence of shared ancestry, however high its identity.

The rule that homology is not a percentage was set out in Reeck et al. (1987), '"Homology" in proteins and nucleic acids: a terminology muddle and a way out of it', Cell 50:667. The terms orthologue and paralogue come from Fitch (1970), 'Distinguishing homologous from analogous proteins', Systematic Zoology 19:99–113. For the twilight zone, a standard reference is Rost (1999), 'Twilight zone of protein sequence alignments', Protein Engineering 12:85–94. It shows that the identity needed to infer homology depends on the alignment length: short alignments need much higher identity than long ones. Quote a percent identity together with the length it covers, and treat no single cut-off as a hard line.

Orthologues and paralogues

Homologous genes come in two main kinds, depending on the event that separated them.

  • Orthologues were separated by speciation, the splitting of one species into two. Human haemoglobin beta and mouse haemoglobin beta are orthologues: one gene in the common ancestor of humans and mice became one gene in each line. Orthologues usually keep the same job, which is why mouse genes are useful models for human ones.
  • Paralogues were separated by gene duplication, when a stretch of DNA was copied within one genome. Human haemoglobin alpha and human haemoglobin beta are paralogues: an ancient duplication made two globin genes, which then changed in different ways. Paralogues often take on related but different jobs. In adult haemoglobin, two alpha and two beta chains work together.

The figure shows both relationships in one small family tree.

Why compare sequences: homology, similarity and identity · LSMA free course An ancestral globin gene is duplicated into an alpha and a beta gene. Each is then split by the speciation of humans and mice, giving mouse Hba, human HBA, human HBB and mouse Hbb-b1. Human HBA and human HBB are paralogues and share 42.3% identity. Human HBB and mouse Hbb-b1 are orthologues and share 80.3% identity. ONE FAMILY, TWO KINDS OF RELATIVE duplication speciation Ancestral globin gene alpha line beta line mouse Hba human HBA human HBB mouse Hbb-b1 paralogues · 42.3% identical orthologues · 80.3% identical
A duplication (square) made the alpha and beta genes; the later split between the human and mouse lines (circles) gave each species one copy of each. Human HBB, shaded, is compared with its orthologue and with its paralogue in the code below. Schematic; branch lengths do not show time.

Paralogues are a common trap. If a search for a mouse version of a human gene returns several hits, the best match is not always the true orthologue, especially in gene families with many recent copies. Mice, for example, have two adult beta-globin genes, made by a duplication in the mouse's own line after it split from ours; both are orthologues of human HBB. Databases such as Ensembl and NCBI Gene (The main databases: sequences, genomes, proteins, structures) list orthologues worked out from whole gene trees, which is safer than taking the top hit.

Two practical notes. Databases written in American English spell the words ortholog and paralog; they mean exactly the same as the British forms used here, so search for both. And the question "which mouse gene corresponds to this human gene?" comes up whenever a result from a model organism is carried across to people. If the answer is a paralogue rather than the orthologue, the comparison may be between genes with different jobs, and the conclusion may not hold.

Go deeper: one-to-many orthologues and in-paralogues

The terms orthology and paralogy were introduced by Walter Fitch in 1970, and real cases are often not one-to-one. When a gene is duplicated in one species after it split from another, both copies are orthologues of the single gene in the other species. The two mouse adult beta-globin genes are an example: both are orthologues of human HBB, a one-to-many relationship.

Copies made after the speciation you are looking at are called in-paralogues; copies made before it, like alpha and beta globin, are out-paralogues. Orthology databases label such cases one-to-many or many-to-many. A third kind of relative, the xenologue, arises when a gene moves between species by horizontal gene transfer, which is common in bacteria. Its gene tree then disagrees with the species tree.

A first comparison in Python

This lesson needs only Biopython. The first block compares the first 50 amino acids of human and mouse haemoglobin beta, copied from their UniProt records (P68871 and P02088). The two fragments are the same length and have no insertions or deletions between them, so they can be compared position by position without building an alignment.

Python
from Bio.Seq import Seq

# First 50 amino acids of haemoglobin beta (UniProt P68871 human, P02088 mouse)
human = Seq("MVHLTPEEKSAVTALWGKVNVDEVGGEALGRLLVVYPWTQRFFESFGDLS")
mouse = Seq("MVHLTDAEKAAVSCLWGKVNSDEVGGEALGRLLVVYPWTQRYFDSFGDLS")
print(len(human), len(mouse))

same = sum(1 for h, m in zip(human, mouse) if h == m)
print(same, "identical positions out of", len(human))
print(round(100 * same / len(human), 1), "% identity")

marks = "".join("|" if h == m else "." for h, m in zip(human, mouse))
print(human)
print(marks)
print(mouse)

What this does

  • from Bio.Seq import Seq loads Biopython's sequence object. A Seq behaves like a string of letters but also knows biological operations, such as translating DNA, which later lessons use.
  • len(...) gives the number of amino acids in each fragment: both should be 50.
  • zip(human, mouse) walks along both sequences together, handing over one pair of letters at a time. The line starting same = adds 1 for every pair where the letters are equal.
  • Dividing by the length and multiplying by 100 gives the percent identity; round(..., 1) keeps one decimal place.
  • The last part builds a line of marks, | for a match and . for a mismatch, and prints it between the two sequences.
50 50 42 identical positions out of 50 84.0 % identity MVHLTPEEKSAVTALWGKVNVDEVGGEALGRLLVVYPWTQRFFESFGDLS |||||..||.||..||||||.||||||||||||||||||||.|.|||||| MVHLTDAEKAAVSCLWGKVNSDEVGGEALGRLLVVYPWTQRYFDSFGDLS

Reading the output

Both fragments have 50 amino acids, and 42 positions match, so the fragments are 84.0% identical. The marks line shows where the 8 differences fall. Several are swaps between alike amino acids, such as F (phenylalanine) for Y (tyrosine) at position 42 and E (glutamate) for D (aspartate) at position 44, so the two fragments are more similar than the identity alone suggests. The long unbroken run from position 22 to 41 is a stretch that has not changed at all since the two lines split.

Real comparisons rarely come in equal lengths. The second block fetches the full sequences from UniProt and lets Biopython's aligner line them up, adding gaps where needed. For now, treat the aligner as a black box; the next three lessons, from Pairwise alignment: dot plots, scores and gaps to Scoring matrices: PAM and BLOSUM, open it up. It needs an internet connection, which Colab has.

Python
import io, urllib.request
from Bio import SeqIO, Align

def uniprot(acc):
    url = f"https://rest.uniprot.org/uniprotkb/{acc}.fasta"
    text = urllib.request.urlopen(url).read().decode()
    return SeqIO.read(io.StringIO(text), "fasta").seq

hbb_human = uniprot("P68871")   # haemoglobin beta, human
hbb_mouse = uniprot("P02088")   # haemoglobin beta-1, mouse
hba_human = uniprot("P69905")   # haemoglobin alpha, human

aligner = Align.PairwiseAligner(scoring="blastp")
for name, other in [("mouse beta", hbb_mouse), ("human alpha", hba_human)]:
    aln = aligner.align(hbb_human, other)[0]
    c = aln.counts()
    pid = 100 * c.identities / aln.length
    print(f"human beta vs {name}: {c.identities} identical,",
          f"{c.gaps} gap positions, length {aln.length}, {pid:.1f}% identity")

What this does

  • The function uniprot builds the web address of a UniProt entry in FASTA format, downloads it, and reads it with SeqIO.read, which expects exactly one record. .seq keeps just the sequence. io.StringIO lets the downloaded text be read as if it were a file.
  • Three proteins are fetched: human beta, its mouse orthologue and its human paralogue, alpha.
  • PairwiseAligner(scoring="blastp") makes an aligner with the same scoring settings that the protein search tool BLAST uses. aligner.align(...)[0] takes the best alignment.
  • aln.counts() counts identical columns, mismatched columns and gap positions. aln.length is the number of columns in the alignment, gaps included.
  • The f"..." strings fill in the numbers; :.1f prints one decimal place.
human beta vs mouse beta: 118 identical, 0 gap positions, length 147, 80.3% identity human beta vs human alpha: 63 identical, 9 gap positions, length 149, 42.3% identity

Reading the output

Human and mouse beta are both 147 amino acids long and line up with no gaps; 118 of 147 positions match, 80.3%. Human alpha is 142 long. To line it up with beta, the aligner needs 9 gap positions, giving 149 columns, and 63 of them match, 42.3%. Both pairs are homologous. The orthologue, separated by a speciation tens of millions of years ago, is far closer than the paralogue, separated by a duplication hundreds of millions of years earlier.

Worked example · one alignment, three percentages

identical columns = 63 · alignment length = 149 · gap positions = 9
63 ÷ 149 = 42.3% (all columns)
63 ÷ 140 = 45.0% (columns without a gap)
63 ÷ 142 = 44.4% (length of the shorter protein)

Percent identity always means identical positions divided by something. Which something must be stated.

Step by step. Start from the beta and alpha alignment above: 63 identical columns in an alignment of 149 columns. Dividing by all 149 columns gives 42.3%; this counts each gap as a difference. Removing the 9 gap columns leaves 140 columns where both proteins have a letter, and 63 ÷ 140 gives 45.0%. Dividing by the length of the shorter protein, alpha with 142 amino acids, gives 44.4%.

What the answer means. The same pair of proteins can be reported as 42%, 44% or 45% identical, and all three are correct for their own definition. Tools differ in the one they use. When you compare figures from two papers or two programs, check how each was calculated, and check that the alignment covers the whole protein: 90% identity over a 20-residue stretch is far weaker evidence than 45% over 140 residues.

What a comparison can and cannot tell you

A comparison can show that two sequences are related and which positions have stayed the same. Positions that are identical across many species are usually important for the protein's job; a variant that changes one is more likely to cause harm. It cannot, on its own, prove that two proteins do the same job. Paralogues can drift to new roles, and a single change at a key position can alter function even when the rest is identical. Treat sequence comparison as strong evidence for relatedness and as a first guess about function.

The two blocks above also show why a pair is rarely enough. Comparing human and mouse beta tells you which positions differ between two species, but not whether a given position is free to change or is held fixed. That needs many sequences at once, which Multiple alignment and conserved regions covers. A position that is the same in fish, birds and mammals has resisted change for a very long time, and that is far stronger evidence of importance than agreement between two close relatives.

The rest of this module follows one thread. Pairwise alignment: dot plots, scores and gaps, Global and local alignment, without heavy maths and Scoring matrices: PAM and BLOSUM show how an alignment is built and scored, Searching databases fast: similarity search and E-values how a database is searched quickly, Multiple alignment and conserved regions and Trees from sequences how many sequences are lined up and turned into a tree, and Variants: what a change in sequence does, and how it is annotated what a single change in sequence does. The project at the end puts these steps together on an unknown sequence.

Key point

Homology is a yes-or-no statement about shared ancestry; identity and similarity are percentages measured on an alignment and are the evidence for it. Orthologues were split by speciation, paralogues by duplication. Always say how a percent identity was calculated.

A second example: a paper says a fish protein is "35% homologous" to a human one. Read it as "35% identical", find out over what length, and remember that 35% across a full protein usually does mean the two are homologous, while 35% over a short stretch may be chance.

Further reading · Module 4Google Colab: frequently asked questions. · Biopython tutorial: pairwise sequence alignment. · UniProt help: retrieving entries through the API. · All reading for this course

Check your understanding

1. A report says two proteins are "62% homologous". What is the best way to read this?

2. Humans have both HBA and HBB, made by an ancient gene duplication. How are human HBA and mouse HBB related?

3. Two tools report 42% and 45% identity for the same pair of proteins. What is the most likely reason?

Up next

Lesson 2

Pairwise alignment: dot plots, scores and gaps

Ask BioTutor

Create a free website with Framer, the website builder loved by startups, designers and agencies.