Guide to AI and Data Courses · Lecture Notes

Chapter 39: Bioinformatics

When a bacterium taken from a patient is sequenced, we end up with millions of short DNA fragments, and none of them says where it belongs or which gene it is part of. We have to assemble the fragments into a genome, compare its genes with known sequences in a database, and pick out the genes that really changed among thousands. Bioinformatics is the course about doing this with algorithms and statistics. These notes introduce the course and work through its three core ideas, sequence alignment, genome assembly and multiple testing, with small examples you can compute by hand.

Learning outcomes

Biological data
Model DNA, RNA and proteins as strings of letters; compute the number of k-mers in a sequence.
Sequence alignment
Align two short sequences with Needleman-Wunsch; fill in the score table and trace back.
Genome assembly
Extract k-mers from short reads, build the de Bruijn graph and explain why repeats cause ambiguity.
Multiple testing
Apply the Bonferroni and Benjamini-Hochberg corrections to a small list of p-values.
Place of the course
State what separates bioinformatics from machine learning, data mining, probabilistic models and medical image processing.

39.1What question does the course ask?

How are biological sequences and molecular data analyzed computationally?

Bioinformatics analyzes biological data such as DNA, RNA and protein sequences with algorithms and statistics. The course covers problems such as sequence alignment, genome assembly, gene expression analysis and protein structure prediction, using methods that cope with the size and noise of this data.

The genome of an organism is a very long string over four letters (A, C, G, T): about three billion letters in humans. Proteins are strings over twenty letters (amino acids). Bioinformatics treats these sequences like text, but they differ from ordinary text in two ways. First, similarity between sequences is meaningful: if two sequences are similar, they usually descend from a common ancestor and do similar work. Second, the data is both huge and noisy: a sequencing machine reads short pieces and sometimes reports a wrong letter.

So the question of the course splits into three parts. How do we compare sequences (alignment)? How do we build a whole sequence from short reads (assembly)? Which findings can we trust among thousands of measurements (statistics)? The first two are algorithm and data structure questions; the third is a statistics question. The course joins them in one workflow that runs from sequencing to interpretation.

39.1.1Biology first, computing second

Information flows from DNA to RNA to protein: the DNA sequence of a gene is transcribed into RNA, and every three letters of the RNA specify one amino acid. This summary is enough for the course; the real work is how these sequences are compared and counted on a computer. Biology is a prerequisite, but the weight of the course is on algorithms and statistics.

39.1.2At a glance

CriterionBioinformatics
Approachbiology, algorithms and statistics
InputDNA, protein sequences, expression data
Outputalignment, structure, function prediction
Success measurebiological validity
Math loadmedium-high
Data needshuge sequence datasets

39.2A short history

YearMilestone
1953Watson and Crick, drawing also on Franklin's data, propose the double-helix structure of DNA.
1970Needleman and Wunsch publish a global sequence alignment algorithm based on dynamic programming.
1981Smith and Waterman publish the local sequence alignment algorithm.
1990BLAST is published: fast, heuristic similarity search in large databases.
2003The Human Genome Project is completed; sequencing costs begin to fall rapidly.
2020AlphaFold 2 predicts protein structure at CASP14 with accuracy close to experimental methods.

39.3Core concepts

The rest of the course is built on the concepts below. The following sections work through the most important ones with examples.

ConceptMeaning
Sequence alignmentGlobal and local alignment; scoring matrices.
Sequence databasesGenBank, UniProt, PDB; similarity search.
Hidden Markov modelGene finding and protein family profiles.
Genome assemblyBuilding a genome from short reads; de Bruijn graphs.
Gene expressionMeasuring how active each gene is with RNA-seq.
PhylogeneticsBuilding the family tree of species from sequences.
Protein structurePredicting 3D shape from the amino acid sequence.
Multiple testingControlling the false discovery rate over thousands of genes.

39.4Pairwise sequence alignment: Needleman-Wunsch

To say how similar two sequences are, we place them one above the other letter by letter, and we may insert gaps where letters do not match. Every alignment gets a score: matches are rewarded, mismatches and gaps are penalized. The goal is to find the alignment with the highest score. Trying all alignments is impossible, because their number grows extremely fast with the length of the sequences. The Needleman-Wunsch algorithm solves this with dynamic programming, in a number of operations proportional to the product of the two lengths.

Definition 39.1 (The Needleman-Wunsch recurrence)

F(i, j) is the best alignment score of the first i letters of the first sequence with the first j letters of the second. F(i, j) = max { F(i−1, j−1) + s(ai, bj), F(i−1, j) + g, F(i, j−1) + g }. Here s is the match or mismatch score and g is the gap penalty. Initialization: F(i, 0) = i · g, F(0, j) = j · g.

Example 39.1: Aligning GACTA with GATA

Let a match be +1, a mismatch −1 and a gap g = −2. The rows correspond to the letters of GACTA, the columns to those of GATA.

  1. Borders. The first row is 0, −2, −4, −6, −8 and the first column 0, −2, −4, −6, −8, −10: the cost of matching a whole sequence against gaps.
  2. One cell. For F(1, 1), G matches G: F(0,0) + 1 = 1; the routes through gaps give −2 − 2 = −4. The maximum is 1.
  3. The whole table. Each row starts with F(i, 0):
    G: −2, 1, −1, −3, −5
    A: −4, −1, 2, 0, −2
    C: −6, −3, 0, 1, −1
    T: −8, −5, −2, 1, 0
    A: −10, −7, −4, −1, 2
  4. Result. The bottom right cell is F(5, 4) = 2: the best alignment score.
  5. Traceback. From the bottom right, look in each cell at which neighbor the value came from and walk back to the start. The path gives this alignment:
    GACTA
    GA-TA

    Four matches +4, one gap −2: total 2.

The letter C is left without a partner in the second sequence; in biology this can be read as a deletion of a letter during evolution.

If the two sequences have lengths n and m, the table has n · m cells to fill. Filling this small table by hand is the first exercise of the course; tools such as Biopython do the same job on much longer sequences.

39.4.1Global and local alignment

Needleman-Wunsch aligns the whole of both sequences (global alignment). But two proteins may be similar only in a small region, for example the active site of an enzyme, with the rest unrelated. The Smith-Waterman algorithm (local alignment) clips negative values to zero in the table and looks for the best sub-region. Compare GATA with CCCGACTACCC, which is GACTA with three Cs added on each side (same scores): the global score is −10, the local score is 2. The mismatching flanks penalize the global alignment; the local alignment ignores them. In large databases BLAST uses a fast, heuristic version of local alignment.

Common mistake

Reading a high score directly as biological relatedness. The score depends on the chosen scoring scheme (match, mismatch, gap) and on sequence length; long sequences can reach a high score by chance. This is why BLAST reports a score together with an E-value: how many times a score this high is expected to occur by chance. An alignment score given without its significance is not interpreted.

39.5Genomes from short reads: k-mers and the de Bruijn graph

Sequencing machines cannot read a genome as a whole; they produce millions of reads a few hundred letters long. The genome has to be rebuilt from them like a jigsaw puzzle. The most common method rests on k-mers: consecutive substrings of length k. A sequence of length L contains L − k + 1 k-mers (identical ones counted separately). A k-mer count table is easy to build with a hash table; the course uses its data structures knowledge here.

Definition 39.2 (The de Bruijn graph)

Its nodes are strings of length k − 1. Each k-mer becomes an edge from the node of its first k − 1 letters to the node of its last k − 1 letters. The genome corresponds to a path that uses every edge exactly once, an Eulerian path.

Example 39.2: Rebuilding a ten-letter sequence

Let the true genome be ATGGCGTGCA (10 letters) and k = 3. We do not know the genome; we only see its k-mers.

  1. Number of k-mers. 10 − 3 + 1 = 8: ATG, TGG, GGC, GCG, CGT, GTG, TGC, GCA.
  2. Edges. Each k-mer goes from the node of its first two letters to the node of its last two: AT→TG, TG→GG, GG→GC, GC→CG, CG→GT, GT→TG, TG→GC, GC→CA.
  3. Start. No edge enters AT, so the path starts at AT; no edge leaves CA, so the path ends there.
  4. Following the path. On reaching TG there are two choices: TG→GG or TG→GC. Two paths use all the edges:
    AT, TG, GG, GC, CG, GT, TG, GC, CA → ATGGCGTGCA
    AT, TG, GC, CG, GT, TG, GG, GC, CA → ATGCGTGGCA
  5. Reading. Both paths use all eight edges; two different sequences produce the same set of k-mers.

The source of the ambiguity is repetition: TG and GC each occur twice. When a repeat is longer than k, the k-mers cannot tell in which order the path should be followed.

Real genomes are full of repeats, so assemblers often return not a single genome but contigs (contiguous pieces) that stop where the ambiguity begins. A larger k separates repeats but yields fewer k-mers from each read; a smaller k tangles the graph.

Common mistake

Assuming the reads have no errors. If one letter is misread during sequencing, every k-mer that covers it is corrupted. If the fifth letter of the sequence above were read as A instead of C (ATGGAGTGCA), GGC, GCG and CGT would disappear from the k-mer set and GGA, GAG and AGT would appear: k = 3 k-mers change. This is why rarely seen k-mers are often treated as errors and removed.

39.6When thousands of genes are tested: multiple testing

In an RNA-seq experiment we test, for each gene, the difference in expression between two groups (say patients and healthy controls) and obtain one p-value per gene. For a single test, p < 0.05 is the usual threshold: even when there is no difference we accept a 5% false alarm rate. But an experiment tests about 20,000 genes. Even if no gene truly changed, 20,000 × 0.05 = 1000 genes would come out "significant". This is the multiple testing problem.

The effect shows up with small numbers too: if 20 independent tests all have no true difference, the probability of at least one false alarm is 1 − 0.9520 ≈ 0.64.

Definition 39.3 (Two corrections)

Bonferroni: with m tests, use the threshold α / m; this protects the probability of making no false discovery at all. Benjamini-Hochberg (BH): sort the p-values from smallest to largest (p(1) ≤ … ≤ p(m)); find the largest i with p(i) ≤ (i / m) · q and declare the first i genes significant. This keeps the false discovery rate (FDR) at the level q.

Example 39.3: Ten genes, two corrections

m = 10 genes with sorted p-values (the values are illustrative): 0.001, 0.008, 0.012, 0.021, 0.034, 0.041, 0.20, 0.35, 0.62, 0.90. α = q = 0.05.

  1. No correction. Six genes have p < 0.05.
  2. Bonferroni. The threshold is 0.05 / 10 = 0.005; only 0.001 is below it. One gene.
  3. BH thresholds. (i / 10) · 0.05: 0.005, 0.010, 0.015, 0.020, 0.025, 0.030, …
  4. Comparison. 0.001 ≤ 0.005 ✓, 0.008 ≤ 0.010 ✓, 0.012 ≤ 0.015 ✓, 0.021 ≤ 0.020 ✗, and the rest ✗ as well. The largest rank that satisfies the condition is i = 3.
  5. Result. BH declares the first three genes significant.

Six, three and one: no correction gives the most discoveries but also the most false alarms; Bonferroni is the most cautious; BH lies between them. BH is very common in genomics because it accepts a few false discoveries in exchange for catching more real findings.

Common mistake

Saying "the p-value is 0.03, so the finding is real with 97% probability". The p-value is the probability of seeing a result this extreme when there is no difference; it is not the probability that the finding is true. Among thousands of tests, some small p-values arise by chance alone, which is why a correction is needed.

39.7How is the course taught?

39.7.1A typical workflow

SequencesequencingmachineClean andassembleQC, genomeassemblyAlignto reference,to databaseAnalyzevariants,expressionInterpretbiologicalfunction
Figure 39.1: A typical workflow in Bioinformatics

A bacterium taken from a patient is sequenced, the short reads are assembled into a genome, and its genes are compared with known sequences in a database using BLAST. If antibiotic resistance genes are found, the physician is told which drugs will not work.

39.7.2Topics over the semester

  1. A molecular biology primer and biological databases
  2. Pairwise alignment: Needleman-Wunsch, Smith-Waterman
  3. Scoring matrices and similarity search with BLAST
  4. Multiple sequence alignment
  5. Hidden Markov models and gene finding
  6. Motif finding
  7. Genome assembly: de Bruijn graphs
  8. Read mapping and variant calling
  9. Phylogenetic trees
  10. Gene expression with RNA-seq; multiple testing
  11. Clustering and classifying gene expression
  12. Protein structure prediction and AlphaFold

This is a typical semester; the order and coverage vary between universities.

39.7.3Skills you will gain

  • handling sequences with Biopython
  • similarity search with BLAST
  • read mapping with BWA and SAMtools
  • expression analysis with Bioconductor
  • implementing an alignment algorithm

39.7.4Try it yourself

The Try It: Align Two Gene Fragments slide in the presentation lets you solve a typical problem of this course yourself: How similar are DNA fragments of the same gene in two species? The Needleman-Wunsch table finds the best alignment. Change the sequences and scores, then click a cell to see how it was computed.

39.8Are you ready for this course?

39.8.1Prerequisites

CourseWhy it is needed
Machine Learninggene expression classification, protein structure
Data Miningsequence motifs, clustering
Algorithmsdynamic programming: the method behind sequence alignment
Data Structureshash tables, trees and graphs: k-mer counting and genome assembly
Biologythe basics of DNA, RNA, proteins and gene expression

39.8.2Ask yourself

For every "no", the right-hand column shows where to start. If you can say "yes" to most of them, you are ready.

QuestionIf not, start with
Can you find the longest common subsequence of two strings by dynamic programming?Dynamic programming from an algorithms course
Can you explain how information flows from DNA to RNA to protein?High school biology or a short molecular biology primer
Can you count all substrings of length k in a text with a hash table?Hash tables from a data structures course
Can you train a classifier and interpret the result of a clustering?Machine Learning

39.9Neighboring courses

Machine LearningData MiningGraphical ModelsBioinformatics
subfieldbuilds onshares methodsapplication
Figure 39.2: Neighbors of Bioinformatics and the kind of relation

39.9.1Where it overlaps

RelationCourseShared ground
applicationThis course applies the methods of Machine Learninggene expression classification, protein structure
applicationThis course applies the methods of Data Miningsequence motifs, clustering
shares methodsShares methods with Probabilistic Graphical Modelshidden Markov models for sequence alignment

39.9.2Where it differs

  • Machine Learning: ML develops general-purpose learning methods; this course applies them to sequence and expression data together with biological knowledge.
  • Data Mining: Data mining looks for patterns in any data; this course uses alignment and motif methods specific to DNA and protein sequences.
  • Probabilistic Graphical Models: Probabilistic graphical models are a general framework; this course uses hidden Markov models for gene finding and protein families.
  • Medical Image Processing: Medical image processing analyzes images of organs and tissue; this course analyzes sequence and expression data at the molecular level.

39.10In practice

39.10.1Applications

AreaWhat is done
Personalized medicineChoosing treatment by genetic variants.
Outbreak trackingTracing spread through virus genomes.
Drug discoveryPredicting target protein and molecule interactions.
Cancer genomicsFinding tumor-specific mutations.
AgricultureBreeding productive and resilient crop varieties.
Evolution studiesBuilding species relationships from sequences.

39.10.2Risks and ethics

RiskExplanation
Genetic privacyA genome identifies a person and their relatives; identities have been recovered from genetic data thought anonymous.
Ancestry-biased dataGenomic databases come mostly from people of European ancestry; risk scores are less accurate for other ancestries.
Batch effectsWhen samples are processed on different days or machines, a technical difference can look like a biological finding.
Clinical overinterpretationTreating a variant of uncertain significance as a cause of disease can lead a patient to needless treatment or worry.

These issues are discussed in depth in Explainable AI and AI Ethics.

39.10.3Tools and datasets

Tools: BLAST, Biopython, Bioconductor (R), BWA, SAMtools, HMMER, PyMOL.

Well-known datasets: GenBank, UniProt, Protein Data Bank (PDB), Gene Expression Omnibus (GEO), 1000 Genomes Project, The Cancer Genome Atlas (TCGA).

39.11Common misconceptions

Common mistake

One gene means one trait.

Most traits come from many genes and the environment together; few are set by a single gene.

Common mistake

Once a genome is sequenced, its function is known.

A sequence is only a string of letters; finding what genes do is a separate, hard analysis.

Common mistake

Bioinformatics is only for biologists.

The core of the field is algorithms, data structures and statistics; computer engineers are central.

Common mistake

When thousands of genes are tested, the significant ones are real.

Multiple testing inflates false positives; corrections such as the false discovery rate are needed.

39.12Summary

  • Bioinformatics analyzes DNA, RNA and protein sequences with algorithms and statistics; the data is huge and noisy.
  • Needleman-Wunsch aligns two sequences by dynamic programming with an n · m score table; Smith-Waterman uses the same idea to find a local region, and BLAST speeds this up.
  • A sequence of length L has L − k + 1 k-mers; in genome assembly the k-mers are the edges of a de Bruijn graph and the genome is an Eulerian path.
  • Repeats and read errors make assembly ambiguous; the result is often contigs rather than a single genome.
  • When thousands of genes are tested, uncorrected p-values produce many false alarms; Bonferroni and Benjamini-Hochberg control this.

39.13Test Yourself

  1. With match +1, mismatch −1 and gap −2, align AGCT with AGT using Needleman-Wunsch. What are the score and the alignment?

    Answer

    The table (rows A, G, C, T; the first value of each row is the border column): A: −2, 1, −1, −3; G: −4, −1, 2, 0; C: −6, −3, 0, 1; T: −8, −5, −2, 1. The score is F(4, 3) = 1. The alignment is AGCT / AG-T: three matches +3, one gap −2, total 1.

  2. In a Needleman-Wunsch table, the diagonal neighbor of a cell is 3, the cell above is 2 and the cell to the left is 1. The two letters of the cell mismatch (score −1); a gap is −2. What is the value of the cell?

    Answer

    max { 3 − 1, 2 − 2, 1 − 2 } = max { 2, 0, −1 } = 2. The value comes from the diagonal, that is, through the mismatch.

  3. How many k-mers with k = 3 does GATTACA contain, and which are they? If the fourth letter (T) were misread, how many k-mers would be affected?

    Answer

    7 − 3 + 1 = 5 k-mers: GAT, ATT, TTA, TAC, ACA. The k-mers covering the fourth letter are ATT, TTA and TAC (those starting at positions two, three and four); so three k-mers are affected (k = 3).

  4. An RNA-seq experiment tests 5000 genes with α = 0.05. What is the Bonferroni threshold? If no gene truly changes, how many genes are expected to come out "significant" without correction?

    Answer

    The threshold is 0.05 / 5000 = 0.00001 (10−5). Without correction the expected number of false alarms is 5000 × 0.05 = 250 genes.

  5. Five genes have sorted p-values 0.004, 0.010, 0.030, 0.040, 0.300; q = α = 0.05. How many genes do Bonferroni and BH declare significant?

    Answer

    The Bonferroni threshold is 0.05 / 5 = 0.01: 0.004 and 0.010 are at or below it, so two genes. The BH thresholds are 0.01, 0.02, 0.03, 0.04, 0.05: 0.004 ≤ 0.01, 0.010 ≤ 0.02, 0.030 ≤ 0.03, 0.040 ≤ 0.04 hold, 0.300 ≤ 0.05 does not. The largest rank is 4, so four genes.

  6. If two proteins are similar only in a small region in the middle, should global or local alignment be used? Why?

    Answer

    Local alignment. Global alignment also penalizes the dissimilar flanks; in the example of GATA and CCCGACTACCC in these notes the global score is −10 and the local score is 2. Local alignment finds the shared region independently of the flanks.

39.14After this course

Bioinformatics brings machine learning, data mining and probabilistic models together in one application area. After this course, computational genomics, structural biology and protein language models, or neighboring health courses such as medical image processing, are natural next steps.

Related careers: Bioinformatician, Computational biologist, Genomics data scientist, Biostatistician, AI researcher in drug discovery.

39.15Further reading

  • N. C. Jones and P. A. Pevzner, An Introduction to Bioinformatics Algorithms (2004): teaches alignment, genome assembly and motif finding from an algorithmic point of view, step by step.
  • P. Compeau and P. Pevzner, Bioinformatics Algorithms: An Active Learning Approach (3rd ed., 2018): treats genome assembly with de Bruijn graphs in more detail than the example in these notes.
  • R. Durbin, S. Eddy, A. Krogh and G. Mitchison, Biological Sequence Analysis (1998): presents sequence alignment and hidden Markov models in a probabilistic framework.

39.16References

  1. Durbin, Eddy, Krogh and Mitchison, Biological Sequence Analysis, Cambridge University Press, 1998.
  2. Jones and Pevzner, An Introduction to Bioinformatics Algorithms, MIT Press, 2004.
  3. Compeau and Pevzner, Bioinformatics Algorithms: An Active Learning Approach, 3rd ed., Active Learning Publishers, 2018.
  4. Altschul et al., "Basic Local Alignment Search Tool", Journal of Molecular Biology 215(3), 1990.

Related pages: Slides · Slides (PDF) · Course page