Level 2 · Code & compute · Topic 3 of 6

Python for biological data

Variables, loops, functions and files, then algorithms such as k-mer counting and ORF finding.

  • About 120 minutes
  • 11 code cells · 7 checked exercises
  • 10-question check
  • Runs in your browser

What you will learn

  • Store and manipulate sequences as Python strings, and convert between 1-based biological coordinates and 0-based Python slices.
  • Use lists, dictionaries, loops and conditions to count and summarise sequences.
  • Write small, tested functions, such as translate and reverse_complement, and check them against real database entries.
  • Read and write FASTA, FASTQ (including gzip-compressed files) and GFF3 with plain Python.
  • Implement k-mer counting and an open reading frame finder, and compare their results with a genome annotation.
  • Use a cumulative GC skew to locate the origin of replication of a bacterial genome.

Before you start: Level 1, especially the genetic code, genes and coordinates (Topics 1.1 and 1.2). Topics 2.1 and 2.2 help but are not required. No previous programming is assumed: Python runs in your browser, so there is nothing to install.

Why Python?

The command line joins existing programs together; Python lets you write your own. It is the most widely used language in bioinformatics because it reads almost like English, it is free, and it has excellent libraries for nearly every task: Biopython for sequences and file formats, pysam for alignments, pandas for tables, scikit-learn for machine learning. Most new methods papers come with Python code.

This topic deliberately uses Python on its own, with no extra libraries, so that you see how the algorithms work. Each section ends with code you run on real data: the SARS-CoV-2 genome, the human beta-globin gene, Illumina reads and the E. coli chromosome. By the end you will have written a translator, a reverse-complement function, a FASTQ quality summary, a k-mer counter and a gene finder, and checked each one against published annotation.

Values, variables and strings

A variable is a name for a value: sequence = "ATGGTG". The value has a type: text is a string (str), whole numbers are integers (int), decimals are floats (float) and True or False are Booleans. A DNA sequence is naturally a string, and strings come with useful methods: len(s) is the length, s.count("G") counts, s.find("ATG") finds, s.upper() and s.replace("T", "U") make changed copies.

The most important thing to learn about strings is indexing. Python numbers positions from 0, so s[0] is the first character, and a slice s[start:end] runs from start up to but not including end. Biological files usually number bases from 1 and include both ends. So bases 1 to 3 of a gene are s[0:3], and in general a 1-based range start..end is the slice s[start - 1:end]. Getting this wrong by one is the most common bug in bioinformatics.

A 12-base plus strand, numbered 1 to 12 in 1-based coordinates and 0 to 11 as 0-based indices. The highlighted feature is bases 4 to 9 in GFF3, VCF and SAM, which include both ends, and start 3, end 9 in BED and Python, where the end is excluded. On the minus strand the same bases are read right to left; reverse-complementing seq[3:9] gives ATGTAA, read 5′ to 3′.
Swipe sideways to see the whole figure. The same three bases in 1-based, inclusive coordinates (as in GFF and VCF files) and in 0-based, half-open coordinates (as in Python slices and BED files). The length is end − start + 1 in the first system and end − start in the second. Open full size
Example

A sequence is a string

The first 33 bases of the human beta-globin (HBB) coding sequence. Change the slices and run it again.

sequence = "ATGGTGCATCTGACTCCTGAGGAGAAGTCTGCC"   # the start of the human HBB coding sequence
length = len(sequence)
gc = sequence.count("G") + sequence.count("C")

print("Length:", length, "bases")
print(f"G + C: {gc} bases ({gc / length:.1%})")
print("First codon:", sequence[0:3])          # positions 0, 1 and 2
print("Codon 7:", sequence[18:21])            # the codon changed in sickle-cell disease
print("Last five bases:", sequence[-5:])      # negative positions count from the end
print("As RNA:", sequence.replace("T", "U"))
What you should see

33 bases, 18 of them G or C (54.5%). Codon 7 is GAG, glutamate; in sickle-cell disease its middle base, A, is changed to T, making GTG, valine.

Exercise

Cut the spike gene out of the genome

The annotation (NC_045512.2.gff3) places the spike gene at positions 21563 to 25384: 1-based, both ends included. Fix the slice so that spike holds exactly the gene.

Data: NC_045512.2.fasta

def read_fasta(path):
    """Return (header, sequence) for a FASTA file holding one record."""
    with open(path) as handle:
        header = handle.readline().strip()
        return header, "".join(line.strip() for line in handle)

header, genome = read_fasta("NC_045512.2.fasta")
print(header)
print(len(genome), "bases")

spike = genome[21563:25384]     # TODO: convert 1-based, inclusive 21563..25384 to a Python slice

print(len(spike), "bases:", spike[:12], "...", spike[-12:])
print("First codon:", spike[:3], " last codon:", spike[-3:])

Lists, dictionaries and loops

Programs work on many values at once. A list, [3, 1, 2], keeps values in order; append adds to it and sorted sorts it. A dictionary, {"A": 8954, "C": 5492}, maps keys to values and finds any key instantly, which makes it the natural home for a codon table or a set of counts. A set, {"TAA", "TAG", "TGA"}, holds distinct values and answers "is this in it?" quickly.

A for loop runs the same code for each item: for each character of a string, each element of a list, or each key of a dictionary. if, elif and else choose what to do, and range(start, stop, step) produces numbers, which with step 3 walks through a sequence codon by codon. Two shortcuts save a lot of typing: a comprehension, such as [len(s) for s in sequences], builds a list in one line, and collections.Counter counts anything.

Example

Counting the bases of a genome, twice

First with a dictionary and a loop, so you can see the idea; then with Counter, as you would in practice.

Data: NC_045512.2.fasta

from collections import Counter
def read_fasta(path):
    """Return (header, sequence) for a FASTA file holding one record."""
    with open(path) as handle:
        header = handle.readline().strip()
        return header, "".join(line.strip() for line in handle)

_, genome = read_fasta("NC_045512.2.fasta")

counts = {}                          # a dictionary: base -> count
for base in genome:
    counts[base] = counts.get(base, 0) + 1
print("With a loop:   ", counts)

counts = Counter(genome)             # the same, with the standard library
print("With Counter:  ", dict(counts))
for base in "ACGT":
    print(f"{base}: {counts[base]:>5}  {counts[base] / len(genome):.1%}")
print(f"GC content: {(counts['G'] + counts['C']) / len(genome):.2%}")
What you should see

A 8,954, C 5,492, G 5,863 and T 9,594: 37.97% GC. The genome is AT-rich, as coronaviruses generally are.

Functions: translating and reverse-complementing

A function packages code under a name so you can reuse it and test it: def gc_content(sequence): followed by an indented body that ends with return. A short docstring under the def line says what it does. Good functions do one thing, take their inputs as arguments rather than reading global variables, and can be checked with a few known answers using assert, which stops the program with a message if a condition is false.

Two functions turn up in almost every sequence analysis. Translation reads a coding sequence three bases at a time and looks each codon up in the genetic code. The reverse complement gives the other strand of DNA, read in its own 5′ to 3′ direction: complement each base (A↔T, C↔G) and reverse the order. Genes on the minus strand of a chromosome appear reverse-complemented in the reference sequence, which is written for the plus strand.

Exercise

Translate beta-globin

Write translate, then check it on real data: the coding sequence of the HBB mRNA (RefSeq NM_000518.5, positions 51 to 494) should translate to exactly the protein sequence in UniProt (P68871).

Data: NM_000518.5.fasta P68871.fasta

def read_fasta(path):
    """Return (header, sequence) for a FASTA file holding one record."""
    with open(path) as handle:
        header = handle.readline().strip()
        return header, "".join(line.strip() for line in handle)

BASES = "TCAG"
AMINO_ACIDS = "FFLLSSSSYY**CC*WLLLLPPPPHHQQRRRRIIIMTTTTNNKKSSRRVVVVAAAADDEEGGGG"
CODON_TABLE = {a + b + c: AMINO_ACIDS[16 * i + 4 * j + k]          # the standard genetic code
               for i, a in enumerate(BASES) for j, b in enumerate(BASES) for k, c in enumerate(BASES)}

def translate(dna):
    """Translate DNA codon by codon with the standard genetic code; '*' marks a stop."""
    protein = ""
    # TODO: step through dna three bases at a time, adding CODON_TABLE[codon] to protein
    return protein

_, mrna = read_fasta("NM_000518.5.fasta")
cds = mrna[50:494]                  # positions 51-494 of the mRNA, from its GenBank record
protein = translate(cds)
_, uniprot = read_fasta("P68871.fasta")
print(protein)
print(len(cds) // 3, "codons; matches UniProt P68871:", protein.rstrip("*") == uniprot)
Exercise

Find HBB on the minus strand

Write reverse_complement, then use it to find the first exon of HBB in the sequence of chromosome 11, which is written for the plus strand.

Data: NM_000518.5.fasta NC_000011.10_5220001-5300000.fasta

def read_fasta(path):
    """Return (header, sequence) for a FASTA file holding one record."""
    with open(path) as handle:
        header = handle.readline().strip()
        return header, "".join(line.strip() for line in handle)

def reverse_complement(dna):
    """The other strand of a DNA sequence, read 5' to 3'."""
    return dna      # TODO: complement each base (A<->T, C<->G), then reverse the order

print(reverse_complement("GATTACA"))

_, mrna = read_fasta("NM_000518.5.fasta")
_, region = read_fasta("NC_000011.10_5220001-5300000.fasta")   # chromosome 11, from position 5,220,001
exon1 = mrna[:142]                                   # exon 1 is mRNA positions 1-142
print("On the plus strand:", region.find(exon1))     # find gives -1 when there is no match
index = region.find(reverse_complement(exon1))
print("Reverse complement found at chromosome 11 positions", 5220001 + index, "to", 5220001 + index + 141)

Reading and writing files

Real data live in files. with open(path) as handle: opens a file and closes it again when the block ends, even if an error occurs; looping over handle gives one line at a time, so even a file of many gigabytes uses almost no memory. line.strip() removes the newline and surrounding spaces, and line.split("\t") splits a tab-separated line into fields. Open a file with "w" to write it, and gzip.open(path, "rt") reads a gzip-compressed file as text, without unpacking it first.

A function that yields values instead of returning a list is a generator: it hands back one record at a time, which is how good file parsers are written. Libraries such as Biopython provide well-tested parsers for every common format, and in real projects you should use them; writing a small parser yourself once shows you what they do and what can go wrong.

Example

A FASTA parser, and a table of results

A parser for files with any number of records, used to write a small tab-separated table of three proteins.

Data: P68871.fasta P00722.fasta P02920.fasta

def read_fasta(path):
    """Yield (name, sequence) for every record in a FASTA file."""
    name, parts = None, []
    with open(path) as handle:
        for line in handle:
            line = line.strip()
            if line.startswith(">"):
                if name is not None:
                    yield name, "".join(parts)
                name, parts = line[1:].split()[0], []
            elif line:
                parts.append(line)
    if name is not None:
        yield name, "".join(parts)

with open("proteins.tsv", "w") as out:
    out.write("id\tlength\tstart\n")
    for path in ["P68871.fasta", "P00722.fasta", "P02920.fasta"]:
        for name, sequence in read_fasta(path):
            out.write(f"{name}\t{len(sequence)}\t{sequence[:10]}\n")

with open("proteins.tsv") as table:
    print(table.read())
What you should see

Three rows: human beta-globin (147 amino acids), E. coli beta-galactosidase, LacZ (1,024), and lactose permease, LacY (417). The file you wrote, proteins.tsv, is ordinary text that a spreadsheet, R or pandas can read.

Exercise

Summarise a gzipped FASTQ file

Read the 10,000 Illumina reads from the Lenski experiment, straight from the compressed file. Count the reads and their bases, the reads that contain an undetermined base, N, and the bases with a Phred quality of 30 or more (a 1 in 1,000 chance of being wrong). A quality character's score is its character code minus 33.

Data: SRR2584863_1.first10k.fastq.gz

import gzip

reads = 0
bases = 0
reads_with_n = 0
high_quality = 0          # bases with a quality of 30 or more
with gzip.open("SRR2584863_1.first10k.fastq.gz", "rt") as handle:
    for number, line in enumerate(handle):
        line = line.rstrip("\n")
        if number % 4 == 1:       # line 2 of each record: the bases
            pass                  # TODO: count the read and its bases, and whether it contains an N
        elif number % 4 == 3:     # line 4: one quality character per base
            pass                  # TODO: count the bases whose quality, ord(character) - 33, is 30 or more

print(reads, "reads")
print(f"Mean length: {bases / reads:.1f} bases")
print(reads_with_n, "reads contain an N")
print(f"Bases with quality 30 or more: {high_quality / bases:.1%}")

Algorithms 1: counting k-mers

A k-mer is a substring of length k. Sliding a window of width k along a sequence, one base at a time, gives every k-mer it contains: a sequence of length n has n − k + 1 of them, and there are 4k possible DNA k-mers. Counting k-mers is one of the most used operations in genomics: genome assemblers build graphs from them, error-correction tools find rare k-mers caused by sequencing errors, tools such as Kraken assign reads to species by their k-mers, and comparing k-mer counts compares genomes without aligning them.

Counts of short k-mers also reveal biology. If bases occurred independently, a dinucleotide such as CG would appear about as often as the frequencies of C and G predict. In vertebrate genomes CG is rare, because methylated CG mutates readily to TG; many RNA viruses of vertebrates are CG-poor too.

Interactive

k-mer sliding window

The window slides along the first 60 bases of the SARS-CoV-2 genome, adding each k-mer to the counts. Change k, step through, or paste your own sequence.

Exercise

K-mers and CpG in SARS-CoV-2

Write count_kmers, then count the 3-mers of the SARS-CoV-2 genome and measure how under-represented CG is.

Data: NC_045512.2.fasta

from collections import Counter
def read_fasta(path):
    """Return (header, sequence) for a FASTA file holding one record."""
    with open(path) as handle:
        header = handle.readline().strip()
        return header, "".join(line.strip() for line in handle)

def count_kmers(sequence, k):
    """Count every substring of length k, in overlapping windows."""
    return Counter()     # TODO: one k-mer for each window start, from 0 to len(sequence) - k

_, genome = read_fasta("NC_045512.2.fasta")
print(count_kmers("GATTACA", 2))
threes = count_kmers(genome, 3)
print(len(threes), "different 3-mers of", 4 ** 3, "possible")
print("Most common: ", threes.most_common(3))
print("Least common:", threes.most_common()[-3:])

# CG observed against expected: the frequency of C times that of G, times the number of 2-mers.
bases = Counter(genome)
pairs = count_kmers(genome, 2)
expected = bases["C"] / len(genome) * bases["G"] / len(genome) * (len(genome) - 1)
print(f"CG: {pairs['CG']} observed, {expected:.0f} expected, ratio {pairs['CG'] / expected:.2f}")

Algorithms 2: finding genes as open reading frames

An open reading frame (ORF) is a stretch of DNA that starts with a start codon, ATG, and runs in steps of three to the next stop codon (TAA, TAG or TGA). Each strand can be read in three frames, starting at its first, second or third base, so a DNA sequence has six frames in all. Protein-coding genes are long ORFs: random sequence hits one of the three stop codons about every 21 codons, so an ORF hundreds of codons long is unlikely to happen by chance.

Finding ORFs is the simplest form of gene prediction, and it works well for compact genomes such as those of viruses and bacteria. It has limits that are worth seeing for yourself: the first ATG of an ORF is not always the real start codon, short genes fall under any sensible length cut-off, and some genes are read by ribosomes that shift frame part-way through, as happens in SARS-CoV-2.

Interactive

Six-frame translation

Positions 21,501 to 21,640 of the SARS-CoV-2 genome, where ORF1ab ends (its stop codon is at 21,553–21,555) and the spike gene begins (its ATG is at 21,563). Each row is one reading frame; the bottom three read the other strand, from right to left.

Exercise

Find the genes of SARS-CoV-2

Complete find_orfs: in each frame, remember where the first ATG is, and at the next stop codon record the ORF if it is at least 300 bases long. Then compare what you find with the annotated coding sequences.

Data: NC_045512.2.fasta NC_045512.2.gff3

def read_fasta(path):
    """Return (header, sequence) for a FASTA file holding one record."""
    with open(path) as handle:
        header = handle.readline().strip()
        return header, "".join(line.strip() for line in handle)

STOPS = {"TAA", "TAG", "TGA"}

def find_orfs(sequence, minimum=300):
    """Open reading frames on this strand as (start, end, frame): 1-based, inclusive, from an ATG to
    the next in-frame stop codon (included), at least minimum bases long."""
    orfs = []
    for frame in range(3):
        start = None
        for i in range(frame, len(sequence) - 2, 3):
            codon = sequence[i:i + 3]
            # TODO: remember the first ATG; at the next stop codon, record (start + 1, i + 3, frame)
            # if it is at least minimum bases long, then forget the start and keep looking
    return sorted(orfs)

_, genome = read_fasta("NC_045512.2.fasta")
orfs = find_orfs(genome)

annotated = {}          # (start, end) -> gene, for every CDS in the annotation
with open("NC_045512.2.gff3") as gff:
    for line in gff:
        fields = line.rstrip("\n").split("\t")
        if len(fields) == 9 and fields[2] == "CDS":
            annotated[(int(fields[3]), int(fields[4]))] = fields[8].split("gene=")[1].split(";")[0]

for start, end, frame in orfs:
    print(f"{start:>6}-{end:<6} {end - start + 1:>6} bases  frame {frame + 1}  {annotated.get((start, end), '')}")
matches = [annotated[(start, end)] for start, end, _ in orfs if (start, end) in annotated]
print(len(orfs), "ORFs of 300 bases or more;", len(matches), "match an annotated CDS exactly:", ", ".join(matches))

Code lab: where does E. coli start copying its genome?

Bacterial chromosomes are circles, copied in both directions from a single origin of replication to a terminus on the opposite side. The two strands are copied differently, and over evolutionary time this leaves a mark in the sequence: the strand copied continuously (the leading strand) carries more G than C. So the GC skew, (G − C), changes sign at the origin and at the terminus, and if you add it up along the genome, the running total falls to its lowest point at the origin and climbs to its highest at the terminus.

This idea lets you find the origin of a newly sequenced genome with a few lines of code. The cell below computes the cumulative skew of the 4.6-million-base E. coli K-12 chromosome in windows of 10,000 bases, using str.count, which is fast because it runs in compiled code.

Example

The cumulative GC skew of E. coli K-12

Reading 4.6 million bases takes a few seconds in the browser.

Data: NC_000913.3.fasta.gz

import gzip
import matplotlib.pyplot as plt

with gzip.open("NC_000913.3.fasta.gz", "rt") as handle:
    handle.readline()                                # skip the header
    genome = "".join(line.strip() for line in handle)
print(f"E. coli K-12 genome: {len(genome):,} bases")

window = 10_000
positions, skew, total = [], [], 0
for start in range(0, len(genome), window):
    piece = genome[start:start + window]
    total += piece.count("G") - piece.count("C")     # the running total of G - C
    positions.append((start + len(piece)) / 1e6)     # in megabases
    skew.append(total)

lowest = positions[skew.index(min(skew))]
highest = positions[skew.index(max(skew))]
print(f"Lowest point:  {lowest:.2f} Mb (the annotated origin, oriC, is at 3.926 Mb)")
print(f"Highest point: {highest:.2f} Mb, about halfway round the circle: the terminus region")

plt.figure(figsize=(8, 3.2))
plt.plot(positions, skew, color="#0fa391")
plt.axvline(3.925744, color="#c26a00", linestyle="--", label="oriC (annotated)")
plt.xlabel("Position on the chromosome (Mb)")
plt.ylabel("Cumulative G − C")
plt.legend()
plt.tight_layout()
plt.show()
What you should see

The running total bottoms out in the window ending at 3.93 Mb, the window that contains oriC (positions 3,925,744–3,925,975); counted base by base, the lowest point is at 3,925,597, under 150 bases away. The highest point, near 1.55 Mb, lies roughly opposite, in the region where replication ends.

Check your understanding

Ten questions. Score 70% or more to complete this part of the topic. You can retake it as often as you like.

1A gene is annotated at positions 101 to 160 (1-based, inclusive). Which Python slice holds it?
2What does "GATTACA"[1:4] give?
3Which structure is best for looking up the amino acid of each codon?
4What is the reverse complement of ATGC?
5How many k-mers of length 5 does a sequence of 100 bases contain, counting overlapping windows?
6Why should you loop over a file handle instead of reading the whole file with read()?
7In FASTQ quality strings, a character's Phred score is its character code minus 33. What does a score of 30 mean?
8Why is a 900-base open reading frame good evidence for a gene?
9The ORF finder put the start of the spike ORF 27 bases before the annotated start. Why?
10Where does the cumulative GC skew of a bacterial chromosome reach its minimum?

Mini project: check a gene finder against GenBank

Put the pieces together: find the open reading frames of the SARS-CoV-2 genome, translate them, and compare each protein with the proteins in the GenBank record, which lists the translation of every annotated coding sequence. The parser for the GenBank file, the translator and the ORF finder are given; you write classify.

classify(protein, known) takes a protein sequence and a list of (gene, protein) pairs. It returns ("exact", gene) if the protein equals one of the known proteins, otherwise ("ends like", gene) if one of the two sequences ends with the other (a different start, the same protein), and otherwise ("none", None). Check for exact matches against every known protein first.

Exercise

ORFs against the GenBank proteins

Data: NC_045512.2.fasta NC_045512.2.gb

import re
def read_fasta(path):
    """Return (header, sequence) for a FASTA file holding one record."""
    with open(path) as handle:
        header = handle.readline().strip()
        return header, "".join(line.strip() for line in handle)

BASES = "TCAG"
AMINO_ACIDS = "FFLLSSSSYY**CC*WLLLLPPPPHHQQRRRRIIIMTTTTNNKKSSRRVVVVAAAADDEEGGGG"
CODON_TABLE = {a + b + c: AMINO_ACIDS[16 * i + 4 * j + k]          # the standard genetic code
               for i, a in enumerate(BASES) for j, b in enumerate(BASES) for k, c in enumerate(BASES)}

def translate(dna):
    return "".join(CODON_TABLE[dna[i:i + 3]] for i in range(0, len(dna) - 2, 3))

STOPS = {"TAA", "TAG", "TGA"}

def find_orfs(sequence, minimum=300):
    """Open reading frames on this strand as (start, end, frame): 1-based, inclusive, from an ATG to
    the next in-frame stop codon (included), at least minimum bases long."""
    orfs = []
    for frame in range(3):
        start = None
        for i in range(frame, len(sequence) - 2, 3):
            codon = sequence[i:i + 3]
            if start is None and codon == "ATG":
                start = i
            elif start is not None and codon in STOPS:
                if i + 3 - start >= minimum:
                    orfs.append((start + 1, i + 3, frame))
                start = None
    return sorted(orfs)

def genbank_proteins(path):
    """(gene, protein) for every CDS in a GenBank file, from its /translation qualifiers."""
    features = open(path).read().split("ORIGIN")[0]
    proteins = []
    for feature in re.split(r"\n {5}(?=\S)", features):
        if feature.startswith("CDS"):
            gene = re.search(r'/gene="([^"]+)"', feature).group(1)
            protein = re.sub(r"\s+", "", re.search(r'/translation="([^"]+)"', feature).group(1))
            proteins.append((gene, protein))
    return proteins

def classify(protein, known):
    """('exact', gene), ('ends like', gene) or ('none', None)."""
    return ("none", None)     # TODO

_, genome = read_fasta("NC_045512.2.fasta")
known = genbank_proteins("NC_045512.2.gb")
print(len(known), "proteins in the GenBank record\n")
results = []
for start, end, frame in find_orfs(genome):
    protein = translate(genome[start - 1:end]).rstrip("*")
    kind, gene = classify(protein, known)
    results.append((start, end, kind, gene))
    print(f"{start:>6}-{end:<6} {len(protein):>5} aa  {kind:<10} {gene or ''}")

Go further

  • Run find_orfs on the reverse complement of the genome. How many long ORFs are there on the minus strand, and do any match a protein? (SARS-CoV-2 is a positive-strand RNA virus.)
  • Lower the minimum to 75 bases. Which annotated genes now appear, and how many ORFs match nothing?
  • Translate the spike ORF from the annotated start, 21,563, and confirm that it gives the 1,273-residue spike protein.

Summary and further reading

Key takeaways

  • Sequences are strings. Python counts from 0 and slices exclude their end, so a 1-based, inclusive range start..end is s[start - 1:end].
  • Lists keep order, dictionaries look things up by key, sets test membership; loops, conditions, comprehensions and Counter do most of the counting.
  • Write small functions with a docstring, and test them with assert against known answers, such as a UniProt protein or an annotated exon position.
  • Stream files line by line with with open(...); gzip.open(path, "rt") reads compressed files directly, and a generator makes a memory-friendly parser.
  • k-mer counts underlie assembly, read classification and alignment-free comparison, and reveal biology such as CpG depletion.
  • Open reading frames find many genes in compact genomes, but miss short genes, can choose the wrong start codon and cannot follow frameshifts.

Key terms

Data used on this page

References and further reading

  1. Ekmekci B, McAnany CE, Mura C. An introduction to programming for bioscientists: a Python-based primer. PLOS Computational Biology 12, e1004867 (2016). doi:10.1371/journal.pcbi.1004867
  2. Bassi S. A primer on Python for life science researchers. PLoS Computational Biology 3, e199 (2007). doi:10.1371/journal.pcbi.0030199
  3. Cock PJA, et al. Biopython: freely available Python tools for computational molecular biology and bioinformatics. Bioinformatics 25, 1422–1423 (2009). doi:10.1093/bioinformatics/btp163
  4. Rule A, et al. Ten simple rules for writing and sharing computational analyses in Jupyter Notebooks. PLOS Computational Biology 15, e1007007 (2019). doi:10.1371/journal.pcbi.1007007
  5. Cock PJA, Fields CJ, Goto N, Heuer ML, Rice PM. The Sanger FASTQ file format for sequences with quality scores, and the Solexa/Illumina FASTQ variants. Nucleic Acids Research 38, 1767–1771 (2010). doi:10.1093/nar/gkp1137
  6. Marçais G, Kingsford C. A fast, lock-free approach for efficient parallel counting of occurrences of k-mers. Bioinformatics 27, 764–770 (2011). doi:10.1093/bioinformatics/btr011
  7. Xia X. Extreme genomic CpG deficiency in SARS-CoV-2 and evasion of host antiviral defense. Molecular Biology and Evolution 37, 2699–2705 (2020). doi:10.1093/molbev/msaa094
  8. Wu F, et al. A new coronavirus associated with human respiratory disease in China. Nature 579, 265–269 (2020). doi:10.1038/s41586-020-2008-3
  9. Kelly JA, et al. Structural and functional conservation of the programmed −1 ribosomal frameshift signal of SARS coronavirus 2 (SARS-CoV-2). Journal of Biological Chemistry 295, 10741–10748 (2020). doi:10.1074/jbc.AC120.013449
  10. Lobry JR. Asymmetric substitution patterns in the two DNA strands of bacteria. Molecular Biology and Evolution 13, 660–665 (1996). doi:10.1093/oxfordjournals.molbev.a025626
  11. Grigoriev A. Analyzing genomes with cumulative skew diagrams. Nucleic Acids Research 26, 2286–2290 (1998). doi:10.1093/nar/26.10.2286
  12. Blattner FR, et al. The complete genome sequence of Escherichia coli K-12. Science 277, 1453–1462 (1997). doi:10.1126/science.277.5331.1453
  13. The Python Tutorial, from the official Python documentation. docs.python.org
  14. Pyodide: Python in the browser, which runs the code cells on this page. pyodide.org

Finished the topic?

Pass the check and the exercises, or mark the topic complete yourself. Progress is saved in this browser.