The Biopython Project is an international association of developers of freely available Python (http://www.python.org) tools for computational molecular biology. Python is an object oriented, interpreted, flexible language that is becoming increasingly popular for scientific computing. Python is easy to learn, has a very clear syntax and can easily be extended with modules written in C, C++ or FORTRAN.

The Biopython web site (http://www.biopython.org) provides
an online resource for modules, scripts, and web links for developers
of Python-based software for bioinformatics use and research. Basically,
the goal of Biopython is to make it as easy as possible to use Python
for bioinformatics by creating high-quality, reusable modules and
classes. Biopython features include parsers for various Bioinformatics
file formats (BLAST, Clustalw, FASTA, Genbank,...), access to online
services (NCBI, Expasy,...), interfaces to common and not-so-common
programs (Clustalw, DSSP, MSMS...), a standard sequence class, various
clustering modules, a KD tree data structure etc. and even documentation.

Basically, we just like to program in Python and want to make it as easy as possible to use Python for bioinformatics by creating high-quality, reusable modules and scripts.

All of the installation information for Biopython was separated from
this document to make it easier to keep updated.

The short version is go to our downloads page (http://biopython.org/wiki/Download),
download and install the listed dependencies, then download and install Biopython.
Biopython runs on many platforms (Windows, Mac, and on the various flavors of Linux and Unix).
For Windows we provide pre-compiled click-and-run installers, while for Unix and other
operating systems you must install from source as described in the included README file.
This is usually as simple as the standard commands:

How do I cite Biopython in a scientific publication?
Please cite our application note [1, Cock et al., 2009]
as the main Biopython reference.
In addition, please cite any publications from the following list if appropriate, in particular as a reference for specific modules within Biopython (more information can be found on our website):

How should I capitalize “Biopython”? Is “BioPython” OK?
The correct capitalization is “Biopython”, not “BioPython” (even though
that would have matched BioPerl, BioJava and BioRuby).

What is going wrong with my print commands?
This tutorial now uses the Python 3 style print function.
As of Biopython 1.62, we support both Python 2 and Python 3.
The most obvious language difference is the print statement
in Python 2 became a print function in Python 3.

For example, this will only work under Python 2:

>>> print "Hello World!"
Hello World!

If you try that on Python 3 you’ll get a SyntaxError.
Under Python 3 you must write:

>>> print("Hello World!")
Hello World!

Surprisingly that will also work on Python 2 – but only for simple
examples printing one thing. In general you need to add this magic
line to the start of your Python scripts to use the print function
under Python 2.6 and 2.7:

from __future__ import print_function

If you forget to add this magic import, under Python 2 you’ll see
extra brackets produced by trying to use the print function when
Python 2 is interpreting it as a print statement and a tuple.

How do I find out what version of Biopython I have installed?
Use this:

>>> import Bio
>>> print(Bio.__version__)
...

If the “import Bio” line fails, Biopython is not installed.
Note that those are double underscores before and after version.
If the second line fails, your version is very out of date.
If the version string ends with a plus, you don’t have an official
release, but a snapshot of the in development code.

Where is the latest version of this document?
If you download a Biopython source code archive, it will include the
relevant version in both HTML and PDF formats. The latest published
version of this document (updated at each release) is online:

What is wrong with my sequence comparisons?
There was a major change in Biopython 1.65 making the Seq and
MutableSeq classes (and subclasses) use simple string-based
comparison (ignoring the alphabet other than if giving a warning),
which you can do explicitly with str(seq1) == str(seq2).

Older versions of Biopython would use instance-based comparison
for Seq objects which you can do explicitly with
id(seq1) == id(seq2).

If you still need to support old versions of Biopython, use these
explicit forms to avoid problems. See Section 3.11.

Why is theSeqobject missing the upper & lower methods described in this Tutorial?
You need Biopython 1.53 or later. Alternatively, use str(my_seq).upper() to get an upper case string.
If you need a Seq object, try Seq(str(my_seq).upper()) but be careful about blindly re-using the same alphabet.

Why doesn’t theSeqobject translation method support thecdsoption described in this Tutorial?
You need Biopython 1.51 or later.

Why won’t the Bio.SeqIOandBio.AlignIOfunctionsparse,readandwritetake filenames? They insist on handles!
You need Biopython 1.54 or later, or just use handles explicitly (see Section 22.1).
It is especially important to remember to close output handles explicitly after writing your data.

Why won’t the Bio.SeqIO.write()andBio.AlignIO.write()functions accept a single record or alignment? They insist on a list or iterator!
You need Biopython 1.54 or later, or just wrap the item with [...] to create a list of one element.

Why doesn’tstr(...)give me the full sequence of aSeqobject?
You need Biopython 1.45 or later.

Why doesn’tBio.Blastwork with the latest plain text NCBI blast output?
The NCBI keep tweaking the plain text output from the BLAST tools, and keeping our parser up to date is/was an ongoing struggle.
If you aren’t using the latest version of Biopython, you could try upgrading.
However, we (and the NCBI) recommend you use the XML output instead, which is designed to be read by a computer program.

Why doesn’tBio.Entrez.parse()work? The module imports fine but there is no parse function!
You need Biopython 1.52 or later.

Why has my script usingBio.Entrez.efetch()stopped working?
This could be due to NCBI changes in February 2012 introducing EFetch 2.0.
First, they changed the default return modes - you probably want to add retmode="text" to
your call.
Second, they are now stricter about how to provide a list of IDs – Biopython 1.59 onwards
turns a list into a comma separated string automatically.

Why doesn’tBio.Blast.NCBIWWW.qblast()give the same results as the NCBI BLAST website?
You need to specify the same options – the NCBI often adjust the default settings on the website,
and they do not match the QBLAST defaults anymore. Check things like the gap penalties and expectation threshold.

Why doesn’tBio.Blast.NCBIXML.read()work? The module imports but there is no read function!
You need Biopython 1.50 or later. Or, use next(Bio.Blast.NCBIXML.parse(...)) instead.

Why doesn’t mySeqRecordobject have aletter_annotationsattribute?
Per-letter-annotation support was added in Biopython 1.50.

Why can’t I slice mySeqRecordto get a sub-record?
You need Biopython 1.50 or later.

Why doesn’tBio.SeqIO.convert()orBio.AlignIO.convert()work? The modules import fine but there is no convert function!
You need Biopython 1.52 or later. Alternatively, combine the parse and write
functions as described in this tutorial (see Sections 5.5.2 and 6.2.1).

Why doesn’tBio.SeqIO.index()work? The module imports fine but there is no index function!
You need Biopython 1.52 or later.

Why doesn’tBio.SeqIO.index_db()work? The module imports fine but there is no index_db function!
You need Biopython 1.57 or later (and a Python with SQLite3 support).

Where is theMultipleSeqAlignmentobject? TheBio.Alignmodule imports fine but this class isn’t there!
You need Biopython 1.54 or later. Alternatively, the older Bio.Align.Generic.Alignment class supports some of its functionality, but using this is now discouraged.

Why can’t I run command line tools directly from the application wrappers?
You need Biopython 1.55 or later. Alternatively, use the Python subprocess module directly.

I looked in a directory for code, but I couldn’t find the code that does something. Where’s it hidden?
One thing to know is that we put code in __init__.py files. If you are not used to looking for code in this file this can be confusing. The reason we do this is to make the imports easier for users. For instance, instead of having to do a “repetitive” import like from Bio.GenBank import GenBank, you can just use from Bio import GenBank.

Why does the code from CVS seem out of date?
In late September 2009, just after the release of Biopython 1.52, we switched from using CVS to git, a distributed version control system. The old CVS server will remain available as a static and read only backup, but if you want to grab the latest code, you’ll need to use git instead. See our website for more details.

Why doesn’tBio.Fastawork?
We deprecated the Bio.Fasta module in Biopython 1.51 (August 2009) and removed it in Biopython 1.55 (August 2010). There is a brief example showing how to convert old code to use Bio.SeqIO instead in the DEPRECATED file.

This section is designed to get you started quickly with Biopython, and to give a general overview of what is available and how to use it. All of the examples in this section assume that you have some general working knowledge of Python, and that you have successfully installed Biopython on your system. If you think you need to brush up on your Python, the main Python web site provides quite a bit of free documentation to get started with (http://www.python.org/doc/).

Since much biological work on the computer involves connecting with databases on the internet, some of the examples will also require a working internet connection in order to run.

Now that that is all out of the way, let’s get into what we can do with Biopython.

As mentioned in the introduction, Biopython is a set of libraries to provide the ability to deal with “things” of interest to biologists working on the computer. In general this means that you will need to have at least some programming experience (in Python, of course!) or at least an interest in learning to program. Biopython’s job is to make your job easier as a programmer by supplying reusable libraries so that you can focus on answering your specific question of interest, instead of focusing on the internals of parsing a particular file format (of course, if you want to help by writing a parser that doesn’t exist and contributing it to Biopython, please go ahead!). So Biopython’s job is to make you happy!

One thing to note about Biopython is that it often provides multiple ways of “doing the same thing.” Things have improved in recent releases, but this can still be frustrating as in Python there should ideally be one right way to do something. However, this can also be a real benefit because it gives you lots of flexibility and control over the libraries. The tutorial helps to show you the common or easy ways to do things so that you can just make things work. To learn more about the alternative possibilities, look in the Cookbook (Chapter 18, this has some cools tricks and tips), the Advanced section (Chapter 20), the built in “docstrings” (via the Python help command, or the API documentation) or ultimately the code itself.

Disputably (of course!), the central object in bioinformatics is the sequence. Thus, we’ll start with a quick introduction to the Biopython mechanisms for dealing with sequences, the Seq object, which we’ll discuss in more detail in Chapter 3.

Most of the time when we think about sequences we have in my mind a string of letters like ‘AGTACACTGGT’. You can create such Seq object with this sequence as follows - the “>>>” represents the Python prompt followed by what you would type in:

What we have here is a sequence object with a generic alphabet - reflecting the fact we have not specified if this is a DNA or protein sequence (okay, a protein with a lot of Alanines, Glycines, Cysteines and Threonines!). We’ll talk more about alphabets in Chapter 3.

In addition to having an alphabet, the Seq object differs from the Python string in the methods it supports. You can’t do this with a plain string:

The next most important class is the SeqRecord or Sequence Record. This holds a sequence (as a Seq object) with additional annotation including an identifier, name and description. The Bio.SeqIO module for reading and writing sequence file formats works with SeqRecord objects, which will be introduced below and covered in more detail by Chapter 5.

This covers the basic features and uses of the Biopython sequence class.
Now that you’ve got some idea of what it is like to interact with the Biopython libraries, it’s time to delve into the fun, fun world of dealing with biological file formats!

Before we jump right into parsers and everything else to do with Biopython, let’s set up an example to motivate everything we do and make life more interesting. After all, if there wasn’t any biology in this tutorial, why would you want you read it?

Since I love plants, I think we’re just going to have to have a plant based example (sorry to all the fans of other organisms out there!). Having just completed a recent trip to our local greenhouse, we’ve suddenly developed an incredible obsession with Lady Slipper Orchids (if you wonder why, have a look at some Lady Slipper Orchids photos on Flickr, or try a Google Image Search).

Of course, orchids are not only beautiful to look at, they are also extremely interesting for people studying evolution and systematics. So let’s suppose we’re thinking about writing a funding proposal to do a molecular study of Lady Slipper evolution, and would like to see what kind of research has already been done and how we can add to that.

After a little bit of reading up we discover that the Lady Slipper Orchids are in the Orchidaceae family and the Cypripedioideae sub-family and are made up of 5 genera: Cypripedium, Paphiopedilum, Phragmipedium, Selenipedium and Mexipedium.

That gives us enough to get started delving for more information. So, let’s look at how the Biopython tools can help us. We’ll start with sequence parsing in Section 2.4, but the orchids will be back later on as well - for example we’ll search PubMed for papers about orchids and extract sequence data from GenBank in Chapter 9, extract data from Swiss-Prot from certain orchid proteins in Chapter 10, and work with ClustalW multiple sequence alignments of orchid proteins in Section 6.4.1.

A large part of much bioinformatics work involves dealing with the many types of file formats designed to hold biological data. These files are loaded with interesting biological data, and a special challenge is parsing these files into a format so that you can manipulate them with some kind of programming language. However the task of parsing these files can be frustrated by the fact that the formats can change quite regularly, and that formats may contain small subtleties which can break even the most well designed parsers.

We are now going to briefly introduce the Bio.SeqIO module – you can find out more in Chapter 5. We’ll start with an online search for our friends, the lady slipper orchids. To keep this introduction simple, we’re just using the NCBI website by hand. Let’s just take a look through the nucleotide databases at NCBI, using an Entrez online search (http://www.ncbi.nlm.nih.gov:80/entrez/query.fcgi?db=Nucleotide) for everything mentioning the text Cypripedioideae (this is the subfamily of lady slipper orchids).

When this tutorial was originally written, this search gave us only 94 hits, which we saved as a FASTA formatted text file and as a GenBank formatted text file (files ls_orchid.fasta and ls_orchid.gbk, also included with the Biopython source code under docs/tutorial/examples/).

If you run the search today, you’ll get hundreds of results! When following the tutorial, if you want to see the same list of genes, just download the two files above or copy them from docs/examples/ in the Biopython source code. In Section 2.5 we will look at how to do a search like this from within Python.

Now let’s load the GenBank file ls_orchid.gbk instead - notice that the code to do this is almost identical to the snippet used above for the FASTA file - the only difference is we change the filename and the format string:

Biopython has a lot of parsers, and each has its own little special niches based on the sequence format it is parsing and all of that. Chapter 5 covers Bio.SeqIO in more detail, while Chapter 6 introduces Bio.AlignIO for sequence alignments.

While the most popular file formats have parsers integrated into Bio.SeqIO and/or Bio.AlignIO, for some of the rarer and unloved file formats there is either no parser at all, or an old parser which has not been linked in yet.
Please also check the wiki pages http://biopython.org/wiki/SeqIO and http://biopython.org/wiki/AlignIO for the latest information, or ask on the mailing list. The wiki pages should include an up to date list of supported file types, and some additional examples.

The next place to look for information about specific parsers and how to do cool things with them is in the Cookbook (Chapter 18 of this Tutorial). If you don’t find the information you are looking for, please consider helping out your poor overworked documentors and submitting a cookbook entry about it! (once you figure out how to do it, that is!)

One of the very common things that you need to do in bioinformatics is extract information from biological databases. It can be quite tedious to access these databases manually, especially if you have a lot of repetitive work to do. Biopython attempts to save you time and energy by making some on-line databases available from Python scripts. Currently, Biopython has code to extract information from the following databases:

The code in these modules basically makes it easy to write Python code that interact with the CGI scripts on these pages, so that you can get results in an easy to deal with format. In some cases, the results can be tightly integrated with the Biopython parsers to make it even easier to extract information.

Now that you’ve made it this far, you hopefully have a good understanding of the basics of Biopython and are ready to start using it for doing useful work. The best thing to do now is finish reading this tutorial, and then if you want start snooping around in the source code, and looking at the automatically generated documentation.

Once you get a picture of what you want to do, and what libraries in Biopython will do it, you should take a peak at the Cookbook (Chapter 18), which may have example code to do something similar to what you want to do.

If you know what you want to do, but can’t figure out how to do it, please feel free to post questions to the main Biopython list (see http://biopython.org/wiki/Mailing_lists). This will not only help us answer your question, it will also allow us to improve the documentation so it can help the next person do what you want to do.

Biological sequences are arguably the central object in Bioinformatics, and in this chapter we’ll introduce the Biopython mechanism for dealing with sequences, the Seq object.
Chapter 4 will introduce the related SeqRecord object, which combines the sequence information with any annotation, used again in Chapter 5 for Sequence Input/Output.

Sequences are essentially strings of letters like AGTACACTGGT, which seems very natural since this is the most common way that sequences are seen in biological file formats.

There are two important differences between Seq objects and standard Python strings.
First of all, they have different methods. Although the Seq object supports many of the same methods as a plain string, its translate() method differs by doing biological translation, and there are also additional biologically relevant methods like reverse_complement().
Secondly, the Seq object has an important attribute, alphabet, which is an object describing what the individual characters making up the sequence string “mean”, and how they should be interpreted. For example, is AGTACACTGGT a DNA sequence, or just a protein sequence that happens to be rich in Alanines, Glycines, Cysteines
and Threonines?

The alphabet object is perhaps the important thing that makes the Seq object more than just a string. The currently available alphabets for Biopython are defined in the Bio.Alphabet module. We’ll use the IUPAC alphabets (http://www.chem.qmw.ac.uk/iupac/) here to deal with some of our favorite objects: DNA, RNA and Proteins.

Bio.Alphabet.IUPAC provides basic definitions for proteins, DNA and RNA, but additionally provides the ability to extend and customize the basic definitions. For instance, for proteins, there is a basic IUPACProtein class, but there is an additional ExtendedIUPACProtein class providing for the additional elements “U” (or “Sec” for selenocysteine) and “O” (or “Pyl” for pyrrolysine), plus the ambiguous symbols “B” (or “Asx” for asparagine or aspartic acid), “Z” (or “Glx” for glutamine or glutamic acid), “J” (or “Xle” for leucine isoleucine) and “X” (or “Xxx” for an unknown amino acid). For DNA you’ve got choices of IUPACUnambiguousDNA, which provides for just the basic letters, IUPACAmbiguousDNA (which provides for ambiguity letters for every possible situation) and ExtendedIUPACDNA, which allows letters for modified bases. Similarly, RNA can be represented by IUPACAmbiguousRNA or IUPACUnambiguousRNA.

The advantages of having an alphabet class are two fold. First, this gives an idea of the type of information the Seq object contains. Secondly, this provides a means of constraining the information, as a means of type checking.

Now that we know what we are dealing with, let’s look at how to utilize this class to do interesting work.
You can create an ambiguous sequence with the default generic alphabet like this:

Note that using the Bio.SeqUtils.GC() function should automatically cope with mixed case sequences and the ambiguous nucleotide S which means G or C.

Also note that just like a normal Python string, the Seq object is in some ways “read-only”. If you need to edit your sequence, for example simulating a point mutation, look at the Section 3.12 below which talks about the MutableSeq object.

Two things are interesting to note. First, this follows the normal conventions for Python strings. So the first element of the sequence is 0 (which is normal for computer science, but not so normal for biology). When you do a slice the first item is included (i.e. 4 in this case) and the last is excluded (12 in this case), which is the way things work in Python, but of course not necessarily the way everyone in the world would expect. The main goal is to stay consistent with what Python does.

The second thing to notice is that the slice is performed on the sequence data string, but the new object produced is another Seq object which retains the alphabet information from the original Seq object.

Also like a Python string, you can do slices with a start, stop and stride (the step size, which defaults to one). For example, we can get the first, second and third codon positions of this DNA sequence:

If you really do just need a plain string, for example to write to a file, or insert into a database, then this is very easy to get:

>>> str(my_seq)
'GATCGATGGGCCTATATAGGATCGAAAATCGC'

Since calling str() on a Seq object returns the full sequence as a string,
you often don’t actually have to do this conversion explicitly.
Python does this automatically in the print function
(and the print statement under Python 2):

>>> print(my_seq)
GATCGATGGGCCTATATAGGATCGAAAATCGC

You can also use the Seq object directly with a %s placeholder when using the Python string formatting or interpolation operator (%):

This line of code constructs a simple FASTA format record (without worrying about line wrapping).
Section 4.5 describes a neat way to get a FASTA formatted
string from a SeqRecord object, while the more general topic of reading and
writing FASTA format sequence files is covered in Chapter 5.

Naturally, you can in principle add any two Seq objects together - just like you can with Python strings to concatenate them. However, you can’t add sequences with incompatible alphabets, such as a protein sequence and a DNA sequence:

In all of these operations, the alphabet property is maintained. This is very
useful in case you accidentally end up trying to do something weird like take
the (reverse)complement of a protein sequence:

Before talking about transcription, I want to try to clarify the strand issue.
Consider the following (made up) stretch of double stranded DNA which
encodes a short peptide:

DNA coding strand (aka Crick strand, strand +1)

5’

ATGGCCATTGTAATGGGCCGCTGAAAGGGTGCCCGATAG

3’

|||||||||||||||||||||||||||||||||||||||

3’

TACCGGTAACATTACCCGGCGACTTTCCCACGGGCTATC

5’

DNA template strand (aka Watson strand, strand −1)

|

Transcription

↓

5’

AUGGCCAUUGUAAUGGGCCGCUGAAAGGGUGCCCGAUAG

3’

Single stranded messenger RNA

The actual biological transcription process works from the template strand, doing a reverse complement (TCAG → CUGA) to give the mRNA. However, in Biopython and bioinformatics in general, we typically work directly with the coding strand because this means we can get the mRNA sequence just by switching T → U.

Now let’s actually get down to doing a transcription in Biopython. First, let’s create Seq objects for the coding and template DNA strands:

Sticking with the same example discussed in the transcription section above,
now let’s translate this mRNA into the corresponding protein sequence - again taking
advantage of one of the Seq object’s biological methods:

You should notice in the above protein sequences that in addition to the end stop character, there is an internal stop as well. This was a deliberate choice of example, as it gives an excuse to talk about some optional arguments, including different translation tables (Genetic Codes).

The translation tables available in Biopython are based on those from the NCBI (see the next section of this tutorial). By default, translation will use the standard genetic code (NCBI table id 1).
Suppose we are dealing with a mitochondrial sequence. We need to tell the translation function to use the relevant genetic code instead:

Now, suppose you have a complete coding sequence CDS, which is to say a
nucleotide sequence (e.g. mRNA – after any splicing) which is a whole number
of codons (i.e. the length is a multiple of three), commences with a start
codon, ends with a stop codon, and has no internal in-frame stop codons.
In general, given a complete CDS, the default translate method will do what
you want (perhaps with the to_stop option). However, what if your
sequence uses a non-standard start codon? This happens a lot in bacteria –
for example the gene yaaX in E. coli K12:

In the bacterial genetic code GTG is a valid start codon,
and while it does normally encode Valine, if used as a start codon it
should be translated as methionine. This happens if you tell Biopython your
sequence is a complete CDS:

Sequence comparison is actually a very complicated topic, and there is no easy
way to decide if two sequences are equal. The basic problem is the meaning of
the letters in a sequence are context dependent - the letter “A” could be part
of a DNA, RNA or protein sequence. Biopython uses alphabet objects as part of
each Seq object to try to capture this information - so comparing two
Seq objects could mean considering both the sequence strings and
the alphabets.

For example, you might argue that the two DNA Seq objects
Seq("ACGT", IUPAC.unambiguous_dna) and
Seq("ACGT", IUPAC.ambiguous_dna) should be equal, even though
they do have different alphabets. Depending on the context this could be
important.

This gets worse – suppose you think Seq("ACGT",
IUPAC.unambiguous_dna) and Seq("ACGT") (i.e. the default generic
alphabet) should be equal. Then, logically, Seq("ACGT", IUPAC.protein)
and Seq("ACGT") should also be equal. Now, in logic if A=B and
B=C, by transitivity we expect A=C. So for logical consistency we’d
require Seq("ACGT", IUPAC.unambiguous_dna) and Seq("ACGT",
IUPAC.protein) to be equal – which most people would agree is just not right.
This transitivity also has implications for using Seq objects as
Python dictionary keys.

Now, in everyday use, your sequences will probably all have the same
alphabet, or at least all be the same type of sequence (all DNA, all RNA, or
all protein). What you probably want is to just compare the sequences as
strings – which you can do explicitly:

So, what does Biopython do? Well, as of Biopython 1.65, sequence comparison
only looks at the sequence, essentially ignoring the alphabet:

>>> seq1 == seq2
True
>>> seq1 == "ACGT"
True

As an extension to this, using sequence objects as keys in a Python dictionary
is now equivalent to using the sequence as a plain string for the key.
See also Section 3.4.

Note if you compare sequences with incompatible alphabets (e.g. DNA vs RNA,
or nucleotide versus protein), then you will get a warning but for the
comparison itself only the string of letters in the sequence is used:

WARNING: Older versions of Biopython instead used to check if the
Seq objects were the same object in memory.
This is important if you need to support scripts on both old and new
versions of Biopython. Here make the comparison explicit by wrapping
your sequence objects with either str(...) for string based
comparison or id(...) for object instance based comparison.

Just like the normal Python string, the Seq object is “read only”, or in Python terminology, immutable. Apart from wanting the Seq object to act like a string, this is also a useful default since in many biological applications you want to ensure you are not changing your sequence data:

Do note that unlike the Seq object, the MutableSeq object’s methods like reverse_complement() and reverse() act in-situ!

An important technical difference between mutable and immutable objects in Python means that you can’t use a MutableSeq object as a dictionary key, but you can use a Python string or a Seq object in this way.

Once you have finished editing your a MutableSeq object, it’s easy to get back to a read-only Seq object should you need to:

The UnknownSeq object is a subclass of the basic Seq object
and its purpose is to represent a
sequence where we know the length, but not the actual letters making it up.
You could of course use a normal Seq object in this situation, but it wastes
rather a lot of memory to hold a string of a million “N” characters when you could
just store a single letter “N” and the desired length as an integer.

You may be able to find a use for the UnknownSeq object in your own
code, but it is more likely that you will first come across them in a
SeqRecord object created by Bio.SeqIO
(see Chapter 5).
Some sequence file formats don’t always include the actual sequence, for
example GenBank and EMBL files may include a list of features but for the
sequence just present the contig information. Alternatively, the QUAL files
used in sequencing work hold quality scores but they never contain a
sequence – instead there is a partner FASTA file which does have the
sequence.

To close this chapter, for those you who really don’t want to use the sequence
objects (or who prefer a functional programming style to an object orientated one),
there are module level functions in Bio.Seq will accept plain Python strings,
Seq objects (including UnknownSeq objects) or MutableSeq objects:

Chapter 3 introduced the sequence classes. Immediately “above” the Seq class is the Sequence Record or SeqRecord class, defined in the Bio.SeqRecord module. This class allows higher level features such as identifiers and features (as SeqFeature objects) to be associated with the sequence, and is used throughout the sequence input/output interface Bio.SeqIO described fully in Chapter 5.

If you are only going to be working with simple data like FASTA files, you can probably skip this chapter
for now. If on the other hand you are going to be using richly annotated sequence data, say from GenBank
or EMBL files, this information is quite important.

While this chapter should cover most things to do with the SeqRecord and SeqFeature objects in this chapter, you may also want to read the SeqRecord wiki page (http://biopython.org/wiki/SeqRecord), and the built in documentation (also online – SeqRecord and SeqFeature):

The SeqRecord (Sequence Record) class is defined in the Bio.SeqRecord module. This class allows higher level features such as identifiers and features to be associated with a sequence (see Chapter 3), and is the basic data type for the Bio.SeqIO sequence input/output interface (see Chapter 5).

The SeqRecord class itself is quite simple, and offers the following information as attributes:

.seq

– The sequence itself, typically a Seq object.

.id

– The primary ID used to identify the sequence – a string. In most cases this is something like an accession number.

.name

– A “common” name/id for the sequence – a string. In some cases this will be the same as the accession number, but it could also be a clone name. I think of this as being analogous to the LOCUS id in a GenBank record.

.description

– A human readable description or expressive name for the sequence – a string.

.letter_annotations

– Holds per-letter-annotations using a (restricted) dictionary of additional information about the letters in the sequence. The keys are the name of the information, and the information is contained in the value as a Python sequence (i.e. a list, tuple or string) with the same length as the sequence itself. This is often used for quality scores (e.g. Section 18.1.6) or secondary structure information (e.g. from Stockholm/PFAM alignment files).

.annotations

– A dictionary of additional information about the sequence. The keys are the name of the information, and the information is contained in the value. This allows the addition of more “unstructured” information to the sequence.

.features

– A list of SeqFeature objects with more structured information about the features on a sequence (e.g. position of genes on a genome, or domains on a protein sequence). The structure of sequence features is described below in Section 4.3.

Using a SeqRecord object is not very complicated, since all of the
information is presented as attributes of the class. Usually you won’t create
a SeqRecord “by hand”, but instead use Bio.SeqIO to read in a
sequence file for you (see Chapter 5 and the examples
below). However, creating SeqRecord can be quite simple.

As mentioned above, the SeqRecord has an dictionary attribute annotations. This is used
for any miscellaneous annotations that doesn’t fit under one of the other more specific attributes.
Adding annotations is easy, and just involves dealing directly with the annotation dictionary:

>>> simple_seq_r.annotations["evidence"] = "None. I just made it up."
>>> print(simple_seq_r.annotations)
{'evidence': 'None. I just made it up.'}
>>> print(simple_seq_r.annotations["evidence"])
None. I just made it up.

Working with per-letter-annotations is similar, letter_annotations is a
dictionary like attribute which will let you assign any Python sequence (i.e.
a string, list or tuple) which has the same length as the sequence:

This example uses a fairly large FASTA file containing the whole sequence for Yersinia pestis biovar Microtus str. 91001 plasmid pPCP1, originally downloaded from the NCBI. This file is included with the Biopython unit tests under the GenBank folder, or online NC_005816.fna from our website.

The file starts like this - and you can check there is only one record present (i.e. only one line starting with a greater than symbol):

Back in Chapter 2 you will have seen the function Bio.SeqIO.parse(...)
used to loop over all the records in a file as SeqRecord objects. The Bio.SeqIO module
has a sister function for use on files which contain just one record which we’ll use here (see Chapter 5 for details):

Here Bio.SeqIO has defaulted to a generic alphabet, rather
than guessing that this is DNA. If you know in advance what kind of sequence
your FASTA file contains, you can tell Bio.SeqIO which alphabet to use
(see Chapter 5).

As you can see above, the first word of the FASTA record’s title line (after
removing the greater than symbol) is used for both the id and
name attributes. The whole title line (after removing the greater than
symbol) is used for the record description. This is deliberate, partly for
backwards compatibility reasons, but it also makes sense if you have a FASTA
file like this:

In this case our example FASTA file was from the NCBI, and they have a fairly well defined set of conventions for formatting their FASTA lines. This means it would be possible to parse this information and extract the GI number and accession for example. However, FASTA files from other sources vary, so this isn’t possible in general.

As in the previous example, we’re going to look at the whole sequence for Yersinia pestis biovar Microtus str. 91001 plasmid pPCP1, originally downloaded from the NCBI, but this time as a GenBank file.
Again, this file is included with the Biopython unit tests under the GenBank folder, or online NC_005816.gb from our website.

This file contains a single record (i.e. only one LOCUS line) and starts:

You should be able to spot some differences already! But taking the attributes individually,
the sequence string is the same as before, but this time Bio.SeqIO has been able to automatically assign a more specific alphabet (see Chapter 5 for details):

Sequence features are an essential part of describing a sequence. Once you get beyond the sequence itself, you need some way to organize and easily get at the more “abstract” information that is known about the sequence. While it is probably impossible to develop a general sequence feature class that will cover everything, the Biopython SeqFeature class attempts to encapsulate as much of the information about the sequence as possible. The design is heavily based on the GenBank/EMBL feature tables, so if you understand how they look, you’ll probably have an easier time grasping the structure of the Biopython classes.

The key idea about each SeqFeature object is to describe a region on a parent sequence, typically a SeqRecord object. That region is described with a location object, typically a range between two positions (see Section 4.3.2 below).

The SeqFeature class has a number of attributes, so first we’ll list them and their general features, and then later in the chapter work through examples to show how this applies to a real life example. The attributes of a SeqFeature are:

.type

– This is a textual description of the type of feature (for instance, this will be something like ‘CDS’ or ‘gene’).

.location

– The location of the SeqFeature on the sequence
that you are dealing with, see Section 4.3.2 below. The
SeqFeature delegates much of its functionality to the location
object, and includes a number of shortcut attributes for properties
of the location:

.ref

– shorthand for .location.ref – any (different)
reference sequence the location is referring to. Usually just None.

.ref_db

– shorthand for .location.ref_db – specifies
the database any identifier in .ref refers to. Usually just None.

.strand

– shorthand for .location.strand – the strand on
the sequence that the feature is located on. For double stranded nucleotide
sequence this may either be 1 for the top strand, −1 for the bottom
strand, 0 if the strand is important but is unknown, or None
if it doesn’t matter. This is None for proteins, or single stranded sequences.

.qualifiers

– This is a Python dictionary of additional information about the feature. The key is some kind of terse one-word description of what the information contained in the value is about, and the value is the actual information. For example, a common key for a qualifier might be “evidence” and the value might be “computational (non-experimental).” This is just a way to let the person who is looking at the feature know that it has not be experimentally (i. e. in a wet lab) confirmed. Note that other the value will be a list of strings (even when there is only one string). This is a reflection of the feature tables in GenBank/EMBL files.

.sub_features

– This used to be used to represent features with complicated locations like ‘joins’ in GenBank/EMBL files. This has been deprecated with the introduction of the CompoundLocation object, and should now be ignored.

The key idea about each SeqFeature object is to describe a
region on a parent sequence, for which we use a location object,
typically describing a range between two positions. Two try to
clarify the terminology we’re using:

position

– This refers to a single position on a sequence,
which may be fuzzy or not. For instance, 5, 20, <100 and
>200 are all positions.

location

– A location is region of sequence bounded by
some positions. For instance 5..20 (i. e. 5 to 20) is a location.

I just mention this because sometimes I get confused between the two.

4.3.2.1 FeatureLocation object

Unless you work with eukaryotic genes, most SeqFeature locations are
extremely simple - you just need start and end coordinates and a strand.
That’s essentially all the basic FeatureLocation object does.

In practise of course, things can be more complicated. First of all
we have to handle compound locations made up of several regions.
Secondly, the positions themselves may be fuzzy (inexact).

4.3.2.2 CompoundLocation object

Biopython 1.62 introduced the CompoundLocation as part of
a restructuring of how complex locations made up of multiple regions
are represented.
The main usage is for handling ‘join’ locations in EMBL/GenBank files.

4.3.2.3 Fuzzy Positions

So far we’ve only used simple positions. One complication in dealing
with feature locations comes in the positions themselves.
In biology many times things aren’t entirely certain
(as much as us wet lab biologists try to make them certain!). For
instance, you might do a dinucleotide priming experiment and discover
that the start of mRNA transcript starts at one of two sites. This
is very useful information, but the complication comes in how to
represent this as a position. To help us deal with this, we have
the concept of fuzzy positions. Basically there are several types
of fuzzy positions, so we have five classes do deal with them:

ExactPosition

– As its name suggests, this class represents a position which is specified as exact along the sequence. This is represented as just a number, and you can get the position by looking at the position attribute of the object.

BeforePosition

– This class represents a fuzzy position
that occurs prior to some specified site. In GenBank/EMBL notation,
this is represented as something like `<13', signifying that
the real position is located somewhere less than 13. To get
the specified upper boundary, look at the position
attribute of the object.

AfterPosition

– Contrary to BeforePosition, this
class represents a position that occurs after some specified site.
This is represented in GenBank as `>13', and like
BeforePosition, you get the boundary number by looking
at the position attribute of the object.

WithinPosition

– Occasionally used for GenBank/EMBL locations,
this class models a position which occurs somewhere between two
specified nucleotides. In GenBank/EMBL notation, this would be
represented as ‘(1.5)’, to represent that the position is somewhere
within the range 1 to 5. To get the information in this class you
have to look at two attributes. The position attribute
specifies the lower boundary of the range we are looking at, so in
our example case this would be one. The extension attribute
specifies the range to the higher boundary, so in this case it
would be 4. So object.position is the lower boundary and
object.position + object.extension is the upper boundary.

OneOfPosition

– Occasionally used for GenBank/EMBL locations,
this class deals with a position where several possible values exist,
for instance you could use this if the start codon was unclear and
there where two candidates for the start of the gene. Alternatively,
that might be handled explicitly as two related gene features.

UnknownPosition

– This class deals with a position of unknown
location. This is not used in GenBank/EMBL, but corresponds to the ‘?’
feature coordinate used in UniProt.

Note that the details of some of the fuzzy-locations changed in Biopython 1.59,
in particular for BetweenPosition and WithinPosition you must now make it explicit
which integer position should be used for slicing etc. For a start position this
is generally the lower (left) value, while for an end position this would generally
be the higher (right) value.

If you print out a FeatureLocation object, you can get a nice representation of the information:

>>> print(my_location)
[>5:(8^9)]

We can access the fuzzy start and end positions using the start and end attributes of the location:

That is most of the nitty gritty about dealing with fuzzy positions in Biopython.
It has been designed so that dealing with fuzziness is not that much more
complicated than dealing with exact positions, and hopefully you find that true!

4.3.2.4 Location testing

You can use the Python keyword in with a SeqFeature or location
object to see if the base/residue for a parent coordinate is within the
feature/location or not.

For example, suppose you have a SNP of interest and you want to know which
features this SNP is within, and lets suppose this SNP is at index 4350
(Python counting!). Here is a simple brute force solution where we just
check all the features one by one in a loop:

A SeqFeature or location object doesn’t directly contain a sequence, instead the location (see Section 4.3.2) describes how to get this from the parent sequence. For example consider a (short) gene sequence with location 5:18 on the reverse strand, which in GenBank/EMBL notation using 1-based counting would be complement(6..18), like this:

You could take the parent sequence, slice it to extract 5:18, and then take the reverse complement.
If you are using Biopython 1.59 or later, the feature location’s start and end are integer like so this works:

This is a simple example so this isn’t too bad – however once you have to deal with compound features (joins) this is rather messy. Instead, the SeqFeature object has an extract method to take care of all this:

Another common annotation related to a sequence is a reference to a journal or other published work dealing with the sequence. We have a fairly simple way of representing a Reference in Biopython – we have a Bio.SeqFeature.Reference class that stores the relevant information about a reference as attributes of an object.

The attributes include things that you would expect to see in a reference like journal, title and authors. Additionally, it also can hold the medline_id and pubmed_id and a comment about the reference. These are all accessed simply as attributes of the object.

A reference also has a location object so that it can specify a particular location on the sequence that the reference refers to. For instance, you might have a journal that is dealing with a particular gene located on a BAC, and want to specify that it only refers to this position exactly. The location is a potentially fuzzy location, as described in section 4.3.2.

Any reference objects are stored as a list in the SeqRecord object’s annotations dictionary under the key “references”.
That’s all there is too it. References are meant to be easy to deal with, and hopefully general enough to cover lots of usage cases.

This format method takes a single mandatory argument, a lower case string which is
supported by Bio.SeqIO as an output format (see Chapter 5).
However, some of the file formats Bio.SeqIO can write to require more than
one record (typically the case for multiple sequence alignment formats), and thus won’t
work via this format() method. See also Section 5.5.4.

You can slice a SeqRecord, to give you a new SeqRecord covering just
part of the sequence. What is important
here is that any per-letter annotations are also sliced, and any features which fall
completely within the new sequence are preserved (with their locations adjusted).

For this example we’re going to focus in on the pim gene, YP_pPCP05.
If you have a look at the GenBank file directly you’ll find this gene/CDS has
location string 4343..4780, or in Python counting 4342:4780.
From looking at the file you can work out that these are the twelfth and
thirteenth entries in the file, so in Python zero-based counting they are
entries 11 and 12 in the features list:

Notice that their locations have been adjusted to reflect the new parent sequence!

While Biopython has done something sensible and hopefully intuitive with the features
(and any per-letter annotation), for the other annotation it is impossible to know if
this still applies to the sub-sequence or not. To avoid guessing, the annotations
and dbxrefs are omitted from the sub-record, and it is up to you to transfer
any relevant information as appropriate.

>>> sub_record.annotations
{}
>>> sub_record.dbxrefs
[]

The same point could be made about the record id, name
and description, but for practicality these are preserved:

This illustrates the problem nicely though, our new sub-record is
not the complete sequence of the plasmid, so the description is wrong!
Let’s fix this and then view the sub-record as a reduced GenBank file using
the format method described above in Section 4.5:

You can add SeqRecord objects together, giving a new SeqRecord.
What is important here is that any common
per-letter annotations are also added, all the features are preserved (with their
locations adjusted), and any other common annotation is also kept (like the id, name
and description).

For an example with per-letter annotation, we’ll use the first record in a
FASTQ file. Chapter 5 will explain the SeqIO functions:

Let’s suppose this was Roche 454 data, and that from other information
you think the TTT should be only TT. We can make a new edited
record by first slicing the SeqRecord before and after the “extra”
third T:

This is because the SeqRecord slicing step is cautious in what annotation
it preserves (erroneously propagating annotation can cause major problems). If
you want to keep the database cross references or the annotations dictionary,
this must be done explicitly:

One of the new features in Biopython 1.57 was the SeqRecord object’s
reverse_complement method. This tries to balance easy of use with worries
about what to do with the annotation in the reverse complemented record.

For the sequence, this uses the Seq object’s reverse complement method. Any
features are transferred with the location and strand recalculated. Likewise
any per-letter-annotation is also copied but reversed (which makes sense for
typical examples like quality scores). However, transfer of most annotation
is problematical.

For instance, if the record ID was an accession, that accession should not really
apply to the reverse complemented sequence, and transferring the identifier by
default could easily cause subtle data corruption in downstream analysis.
Therefore by default, the SeqRecord’s id, name, description, annotations
and database cross references are all not transferred by default.

The SeqRecord object’s reverse_complement method takes a number
of optional arguments corresponding to properties of the record. Setting these
arguments to True means copy the old values, while False means
drop the old values and use the default value. You can alternatively provide
the new desired value instead.

In this chapter we’ll discuss in more detail the Bio.SeqIO module, which was briefly introduced in Chapter 2 and also used in Chapter 4. This aims to provide a simple interface for working with assorted sequence file formats in a uniform way.
See also the Bio.SeqIO wiki page (http://biopython.org/wiki/SeqIO), and the built in documentation (also online):

>>> from Bio import SeqIO
>>> help(SeqIO)
...

The “catch” is that you have to work with SeqRecord objects (see Chapter 4), which contain a Seq object (see Chapter 3) plus annotation like an identifier and description.

The workhorse function Bio.SeqIO.parse() is used to read in sequence data as SeqRecord objects. This function expects two arguments:

The first argument is a handle to read the data from, or a filename. A handle is typically a file opened for reading, but could be the output from a command line program, or data downloaded from the internet (see Section 5.3). See Section 22.1 for more about handles.

The second argument is a lower case string specifying sequence format – we don’t try and guess the file format for you! See http://biopython.org/wiki/SeqIO for a full listing of supported formats.

There is an optional argument alphabet to specify the alphabet to be used. This is useful for file formats like FASTA where otherwise Bio.SeqIO will default to a generic alphabet.

The Bio.SeqIO.parse() function returns an iterator which gives SeqRecord objects. Iterators are typically used in a for loop as shown below.

Sometimes you’ll find yourself dealing with files which contain only a single record. For this situation use the function Bio.SeqIO.read() which takes the same arguments. Provided there is one and only one record in the file, this is returned as a SeqRecord object. Otherwise an exception is raised.

The above example is repeated from the introduction in Section 2.4, and will load the orchid DNA sequences in the FASTA format file ls_orchid.fasta. If instead you wanted to load a GenBank format file like ls_orchid.gbk then all you need to do is change the filename and the format string:

Similarly, if you wanted to read in a file in another file format, then assuming Bio.SeqIO.parse() supports it you would just need to change the format string as appropriate, for example “swiss” for SwissProt files or “embl” for EMBL text files. There is a full listing on the wiki page (http://biopython.org/wiki/SeqIO) and in the built in documentation (also online).

Another very common way to use a Python iterator is within a list comprehension (or
a generator expression). For example, if all you wanted to extract from the file was
a list of the record identifiers we can easily do this with the following list comprehension:

In the above examples, we have usually used a for loop to iterate over all the records one by one. You can use the for loop with all sorts of Python objects (including lists, tuples and strings) which support the iteration interface.

The object returned by Bio.SeqIO is actually an iterator which returns SeqRecord objects. You get to see each record in turn, but once and only once. The plus point is that an iterator can save you memory when dealing with large files.

Instead of using a for loop, can also use the next() function on an iterator to step through the entries, like this:

A word of warning here – using the next() function like this will silently ignore any additional records in the file.
If your files have one and only one record, like some of the online examples later in this chapter, or a GenBank file for a single chromosome, then use the new Bio.SeqIO.read() function instead.
This will check there are no extra unexpected records present.

In the previous section we talked about the fact that Bio.SeqIO.parse() gives you a SeqRecord iterator, and that you get the records one by one. Very often you need to be able to access the records in any order. The Python list data type is perfect for this, and we can turn the record iterator into a list of SeqRecord objects using the built-in Python function list() like so:

Found 94 records
The last record
Z78439.1
Seq('CATTGTTGAGATCACATAATAATTGATCGAGTTAATCTGGAGGATCTGTTTACT...GCC', IUPACAmbiguousDNA())
592
The first record
Z78533.1
Seq('CGTAACAAGGTTTCCGTAGGTGAACCTGCGGAAGGATCATTGATGAGACCGTGG...CGC', IUPACAmbiguousDNA())
740

You can of course still use a for loop with a list of SeqRecord objects. Using a list is much more flexible than an iterator (for example, you can determine the number of records from the length of the list), but does need more memory because it will hold all the records in memory at once.

The SeqRecord object and its annotation structures are described more fully in
Chapter 4. As an example of how annotations are stored, we’ll look at the output from parsing the first record in the GenBank file ls_orchid.gbk.

This gives a human readable summary of most of the annotation data for the SeqRecord.
For this example we’re going to use the .annotations attribute which is just a Python dictionary.
The contents of this annotations dictionary were shown when we printed the record above.
You can also print them out directly:

print(first_record.annotations)

Like any Python dictionary, you can easily get a list of the keys:

print(first_record.annotations.keys())

or values:

print(first_record.annotations.values())

In general, the annotation values are strings, or lists of strings. One special case is any references in the file get stored as reference objects.

Suppose you wanted to extract a list of the species from the ls_orchid.gbk GenBank file. The information we want, Cypripedium irapeanum, is held in the annotations dictionary under ‘source’ and ‘organism’, which we can access like this:

>>> print(first_record.annotations["source"])
Cypripedium irapeanum

or:

>>> print(first_record.annotations["organism"])
Cypripedium irapeanum

In general, ‘organism’ is used for the scientific name (in Latin, e.g. Arabidopsis thaliana),
while ‘source’ will often be the common name (e.g. thale cress). In this example, as is often the case,
the two fields are identical.

Now let’s go through all the records, building up a list of the species each orchid sequence is from:

Great. That was pretty easy because GenBank files are annotated in a standardised way.

Now, let’s suppose you wanted to extract a list of the species from a FASTA file, rather than the GenBank file. The bad news is you will have to write some code to extract the data you want from the record’s description line - if the information is in the file in the first place! Our example FASTA format file ls_orchid.fasta starts like this:

You can check by hand, but for every record the species name is in the description line as the second word. This means if we break up each record’s .description at the spaces, then the species is there as field number one (field zero is the record identifier). That means we can do this:

In general, extracting information from the FASTA description line is not very nice.
If you can get your sequences in a well annotated file format like GenBank or EMBL,
then this sort of annotation information is much easier to deal with.

In the previous section, we looked at parsing sequence data from a file.
Instead of using a filename, you can give Bio.SeqIO a handle
(see Section 22.1), and in this section
we’ll use handles to parse sequence from compressed files.

As you’ll have seen above, we can use Bio.SeqIO.read() or
Bio.SeqIO.parse() with a filename - for instance this quick
example calculates the total length of the sequences in a multiple
record GenBank file using a generator expression:

If you are using Python 2.7 or later, the with-version works for
gzip and bz2 as well. Unfortunately this is broken on older versions of
Python (Issue 3860) and you’d
get an AttributeError about __exit__ being missing.

There is a gzip (GNU Zip) variant called BGZF (Blocked GNU Zip Format),
which can be treated like an ordinary gzip file for reading, but has
advantages for random access later which we’ll talk about later in
Section 5.4.4.

In the previous sections, we looked at parsing sequence data from a file
(using a filename or handle), and from compressed files (using a handle).
Here we’ll use Bio.SeqIO with another type of handle, a network
connection, to download and parse sequences from the internet.

Note that just because you can download sequence data and parse it into
a SeqRecord object in one go doesn’t mean this is a good idea.
In general, you should probably download sequences once and save them to
a file for reuse.

Section 9.6 talks about the Entrez EFetch interface in more detail,
but for now let’s just connect to the NCBI and get a few Opuntia (prickly-pear)
sequences from GenBank using their GI numbers.

First of all, let’s fetch just one record. If you don’t care about the
annotations and features downloading a FASTA file is a good choice as these
are compact. Now remember, when you expect the handle to contain one and
only one record, use the Bio.SeqIO.read() function:

The NCBI will also let you ask for the file in other formats, in particular as
a GenBank file. Until Easter 2009, the Entrez EFetch API let you use “genbank”
as the return type, however the NCBI now insist on using the official
return types of “gb” (or “gp” for proteins) as described on
EFetch for Sequence and other Molecular Biology Databases.
As a result, in Biopython 1.50 onwards, we support “gb” as an
alias for “genbank” in Bio.SeqIO.

Now let’s use a handle to download a SwissProt file from ExPASy,
something covered in more depth in Chapter 10.
As mentioned above, when you expect the handle to contain one and only one record,
use the Bio.SeqIO.read() function:

We’re now going to introduce three related functions in the Bio.SeqIO
module which allow dictionary like random access to a multi-sequence file.
There is a trade off here between flexibility and memory usage. In summary:

Bio.SeqIO.to_dict() is the most flexible but also the most
memory demanding option (see Section 5.4.1). This is basically
a helper function to build a normal Python dictionary with each entry
held as a SeqRecord object in memory, allowing you to modify the
records.

Bio.SeqIO.index() is a useful middle ground, acting like a
read only dictionary and parsing sequences into SeqRecord objects
on demand (see Section 5.4.2).

Bio.SeqIO.index_db() also acts like a read only dictionary
but stores the identifiers and file offsets in a file on disk (as an
SQLite3 database), meaning it has very low memory requirements (see
Section 5.4.3), but will be a little bit slower.

The next thing that we’ll do with our ubiquitous orchid files is to show how
to index them and access them like a database using the Python dictionary
data type (like a hash in Perl). This is very useful for moderately large files
where you only need to access certain elements of the file, and makes for a nice
quick ’n dirty database. For dealing with larger files where memory becomes a
problem, see Section 5.4.2 below.

You can use the function Bio.SeqIO.to_dict() to make a SeqRecord dictionary
(in memory). By default this will use each record’s identifier (i.e. the .id
attribute) as the key. Let’s try this using our GenBank file:

There is just one required argument for Bio.SeqIO.to_dict(), a list or
generator giving SeqRecord objects. Here we have just used the output
from the SeqIO.parse function. As the name suggests, this returns a
Python dictionary.

Since this variable orchid_dict is an ordinary Python dictionary, we can look at all of the keys we have available:

So, it is very easy to create an in memory “database” of our GenBank records. Next we’ll try this for the FASTA file instead.

Note that those of you with prior Python experience should all be able to construct a dictionary like this “by hand”. However, typical dictionary construction methods will not deal with the case of repeated keys very nicely. Using the Bio.SeqIO.to_dict() will explicitly check for duplicate keys, and raise an exception if any are found.

You should recognise these strings from when we parsed the FASTA file earlier in Section 2.4.1. Suppose you would rather have something else as the keys - like the accession numbers. This brings us nicely to SeqIO.to_dict()’s optional argument key_function, which lets you define what to use as the dictionary key for your records.

First you must write your own function to return the key you want (as a string) when given a SeqRecord object. In general, the details of function will depend on the sort of input records you are dealing with. But for our orchids, we can just split up the record’s identifier using the “pipe” character (the vertical line) and return the fourth entry (field three):

5.4.1.2 Indexing a dictionary using the SEGUID checksum

To give another example of working with dictionaries of SeqRecord objects, we’ll use the SEGUID checksum function. This is a relatively recent checksum, and collisions should be very rare (i.e. two different sequences with the same checksum), an improvement on the CRC64 checksum.

Once again, working with the orchids GenBank file:

from Bio import SeqIO
from Bio.SeqUtils.CheckSum import seguid
for record in SeqIO.parse("ls_orchid.gbk", "genbank"):
print(record.id, seguid(record.seq))

Now, recall the Bio.SeqIO.to_dict() function’s key_function argument expects a function which turns a SeqRecord into a string. We can’t use the seguid() function directly because it expects to be given a Seq object (or a string). However, we can use Python’s lambda feature to create a “one off” function to give to Bio.SeqIO.to_dict() instead:

As the previous couple of examples tried to illustrate, using
Bio.SeqIO.to_dict() is very flexible. However, because it holds
everything in memory, the size of file you can work with is limited by your
computer’s RAM. In general, this will only work on small to medium files.

For larger files you should consider
Bio.SeqIO.index(), which works a little differently. Although
it still returns a dictionary like object, this does not keep
everything in memory. Instead, it just records where each record
is within the file – when you ask for a particular record, it then parses
it on demand.

Note that Bio.SeqIO.index() won’t take a handle,
but only a filename. There are good reasons for this, but it is a little
technical. The second argument is the file format (a lower case string as
used in the other Bio.SeqIO functions). You can use many other
simple file formats, including FASTA and FASTQ files (see the example in
Section 18.1.11). However, alignment
formats like PHYLIP or Clustal are not supported. Finally as an optional
argument you can supply an alphabet, or a key function.

Here is the same example using the FASTA file - all we change is the
filename and the format name:

5.4.2.1 Specifying the dictionary keys

Suppose you want to use the same keys as before? Much like with the
Bio.SeqIO.to_dict() example in Section 5.4.1.1,
you’ll need to write a tiny function to map from the FASTA identifier
(as a string) to the key you want:

5.4.2.2 Getting the raw data for a record

The dictionary-like object from Bio.SeqIO.index() gives you each
entry as a SeqRecord object. However, it is sometimes useful to
be able to get the original raw data straight from the file. For this
use the get_raw() method which takes a
single argument (the record identifier) and returns a string (extracted
from the file without modification).

A motivating example is extracting a subset of a records from a large
file where either Bio.SeqIO.write() does not (yet) support the
output file format (e.g. the plain text SwissProt file format) or
where you need to preserve the text exactly (e.g. GenBank or EMBL
output from Biopython does not yet preserve every last bit of
annotation).

Biopython 1.57 introduced an alternative, Bio.SeqIO.index_db(), which
can work on even extremely large files since it stores the record information
as a file on disk (using an SQLite3 database) rather than in memory. Also,
you can index multiple files together (providing all the record identifiers
are unique).

The Bio.SeqIO.index() function takes three required arguments:

Index filename, we suggest using something ending .idx.
This index file is actually an SQLite3 database.

List of sequence filenames to index (or a single filename)

File format (lower case string as used in the rest of the
SeqIO module).

As an example, consider the GenBank flat file releases from the NCBI FTP site,
ftp://ftp.ncbi.nih.gov/genbank/, which are gzip compressed GenBank files.
As of GenBank release 182, there are 16 files making up the viral sequences,
gbvrl1.seq, …, gbvrl16.seq, containing in total almost
one million records. You can index them like this:

That takes about two minutes to run on my machine. If you rerun it then the
index file (here gbvrl.idx) is reloaded in under a second. You can
use the index as a read only Python dictionary - without having to worry
about which file the sequence comes from, e.g.

Very often when you are indexing a sequence file it can be quite large – so
you may want to compress it on disk. Unfortunately efficient random access
is difficult with the more common file formats like gzip and bzip2. In this
setting, BGZF (Blocked GNU Zip Format) can be very helpful. This is a variant
of gzip (and can be decompressed using standard gzip tools) popularised by
the BAM file format, samtools, and
tabix.

To create a BGZF compressed file you can use the command line tool bgzip
which comes with samtools. In our examples we use a filename extension
*.bgz, so they can be distinguished from normal gzipped files (named
*.gz). You can also use the Bio.bgzf module to read and write
BGZF files from within Python.

The Bio.SeqIO.index() and Bio.SeqIO.index_db() can both be
used with BGZF compressed files. For example, if you started with an
uncompressed GenBank file:

So, which of these methods should you use and why? It depends on what you are
trying to do (and how much data you are dealing with). However, in general
picking Bio.SeqIO.index() is a good starting point. If you are dealing
with millions of records, multiple files, or repeated analyses, then look at
Bio.SeqIO.index_db().

Reasons to choose Bio.SeqIO.to_dict() over either
Bio.SeqIO.index() or Bio.SeqIO.index_db() boil down to a need
for flexibility despite its high memory needs. The advantage of storing the
SeqRecord objects in memory is they can be changed, added to, or
removed at will. In addition to the downside of high memory consumption,
indexing can also take longer because all the records must be fully parsed.

Both Bio.SeqIO.index() and Bio.SeqIO.index_db() only parse
records on demand. When indexing, they scan the file once looking for the
start of each record and do as little work as possible to extract the
identifier.

Not memory limited – this is already important with files from second
generation sequencing where 10s of millions of sequences are common, and
using Bio.SeqIO.index() can require more than 4GB of RAM and therefore
a 64bit version of Python.

Because the index is kept on disk, it can be reused. Although building
the index database file takes longer, if you have a script which will be
rerun on the same datafiles in future, this could save time in the long run.

Indexing multiple files together

The get_raw() method can be much faster, since for most file
formats the length of each record is stored as well as its offset.

We’ve talked about using Bio.SeqIO.parse() for sequence input (reading files), and now we’ll look at Bio.SeqIO.write() which is for sequence output (writing files). This is a function taking three arguments: some SeqRecord objects, a handle or filename to write to, and a sequence format.

Here is an example, where we start by creating a few SeqRecord objects the hard way (by hand, rather than by loading them from a file):

Suppose you wanted to know how many records the Bio.SeqIO.write() function wrote to the handle?
If your records were in a list you could just use len(my_records), however you can’t do that when your records come from a generator/iterator. The Bio.SeqIO.write() function returns the number of SeqRecord objects written to the file.

Note - If you tell the Bio.SeqIO.write() function to write to a file that already exists, the old file will be overwritten without any warning.

Some people like their parsers to be “round-tripable”, meaning if you read in
a file and write it back out again it is unchanged. This requires that the parser
must extract enough information to reproduce the original file exactly.
Bio.SeqIO does not aim to do this.

As a trivial example, any line wrapping of the sequence data in FASTA files is
allowed. An identical SeqRecord would be given from parsing the following
two examples which differ only in their line breaks:

To make a round-tripable FASTA parser you would need to keep track of where the
sequence line breaks occurred, and this extra information is usually pointless.
Instead Biopython uses a default line wrapping of 60 characters on output.
The same problem with white space applies in many other file formats too.
Another issue in some cases is that Biopython does not (yet) preserve every
last bit of annotation (e.g. GenBank and EMBL).

Occasionally preserving the original layout (with any quirks it may have) is
important. See Section 5.4.2.2 about the get_raw()
method of the Bio.SeqIO.index() dictionary-like object for one potential
solution.

In previous example we used a list of SeqRecord objects as input to the Bio.SeqIO.write() function, but it will also accept a SeqRecord iterator like we get from Bio.SeqIO.parse() – this lets us do file conversion by combining these two functions.

For this example we’ll read in the GenBank format file ls_orchid.gbk and write it out in FASTA format:

The Bio.SeqIO.convert() function will take handles or filenames.
Watch out though – if the output file already exists, it will overwrite it!
To find out more, see the built in help:

>>> from Bio import SeqIO
>>> help(SeqIO.convert)
...

In principle, just by changing the filenames and the format names, this code
could be used to convert between any file formats available in Biopython.
However, writing some formats requires information (e.g. quality scores) which
other files formats don’t contain. For example, while you can turn a FASTQ
file into a FASTA file, you can’t do the reverse. See also
Sections 18.1.9 and 18.1.10
in the cookbook chapter which looks at inter-converting between different FASTQ formats.

Finally, as an added incentive for using the Bio.SeqIO.convert() function
(on top of the fact your code will be shorter), doing it this way may also be
faster! The reason for this is the convert function can take advantage of
several file format specific optimisations and tricks.

Suppose you had a file of nucleotide sequences, and you wanted to turn it into a file containing their reverse complement sequences. This time a little bit of work is required to transform the SeqRecord objects we get from our input file into something suitable for saving to our output file.

To start with, we’ll use Bio.SeqIO.parse() to load some nucleotide
sequences from a file, then print out their reverse complements using
the Seq object’s built in .reverse_complement() method (see Section 3.7):

Now, if we want to save these reverse complements to a file, we’ll need to make SeqRecord objects.
We can use the SeqRecord object’s built in .reverse_complement() method (see Section 4.8) but we must decide how to name our new records.

This is an excellent place to demonstrate the power of list comprehensions which make a list in memory:

That would create an in memory list of reverse complement records where the sequence length was under 700 base pairs. However, we can do exactly the same with a generator expression - but with the advantage that this does not create a list of all the records in memory at once:

Suppose that you don’t really want to write your records to a file or handle – instead you want a string containing the records in a particular file format. The Bio.SeqIO interface is based on handles, but Python has a useful built in module which provides a string based handle.

For an example of how you might use this, let’s load in a bunch of SeqRecord objects from our orchids GenBank file, and create a string containing the records in FASTA format:

This isn’t entirely straightforward the first time you see it! On the bright side, for the special case where you would like a string containing a single record in a particular file format, use the the SeqRecord class’ format() method (see Section 4.5).

Note that although we don’t encourage it, you can use the format() method to write to a file, for example something like this:

While this style of code will work for a simple sequential file format like FASTA or the simple tab separated format used here, it will not work for more complex or interlaced file formats. This is why we still recommend using Bio.SeqIO.write(), as in the following example:

This chapter is about Multiple Sequence Alignments, by which we mean a collection of
multiple sequences which have been aligned together – usually with the insertion of gap
characters, and addition of leading or trailing gaps – such that all the sequence
strings are the same length. Such an alignment can be regarded as a matrix of letters,
where each row is held as a SeqRecord object internally.

We will introduce the MultipleSeqAlignment object which holds this kind of data,
and the Bio.AlignIO module for reading and writing them as various file formats
(following the design of the Bio.SeqIO module from the previous chapter).
Note that both Bio.SeqIO and Bio.AlignIO can read and write sequence
alignment files. The appropriate choice will depend largely on what you want to do
with the data.

The final part of this chapter is about our command line wrappers for common multiple
sequence alignment tools like ClustalW and MUSCLE.

We have two functions for reading in sequence alignments, Bio.AlignIO.read() and Bio.AlignIO.parse() which following the convention introduced in Bio.SeqIO are for files containing one or multiple alignments respectively.

Using Bio.AlignIO.parse() will return an iterator which gives MultipleSeqAlignment objects. Iterators are typically used in a for loop. Examples of situations where you will have multiple different alignments include resampled alignments from the PHYLIP tool seqboot, or multiple pairwise alignments from the EMBOSS tools water or needle, or Bill Pearson’s FASTA tools.

However, in many situations you will be dealing with files which contain only a single alignment. In this case, you should use the Bio.AlignIO.read() function which returns a single MultipleSeqAlignment object.

Both functions expect two mandatory arguments:

The first argument is a handle to read the data from, typically an open file (see Section 22.1), or a filename.

The second argument is a lower case string specifying the alignment format. As in Bio.SeqIO we don’t try and guess the file format for you! See http://biopython.org/wiki/AlignIO for a full listing of supported formats.

There is also an optional seq_count argument which is discussed in Section 6.1.3 below for dealing with ambiguous file formats which may contain more than one alignment.

A further optional alphabet argument allowing you to specify the expected alphabet. This can be useful as many alignment file formats do not explicitly label the sequences as RNA, DNA or protein – which means Bio.AlignIO will default to using a generic alphabet.

This is the seed alignment for the Phage_Coat_Gp8 (PF05371) PFAM entry, downloaded from a now out of date release of PFAM from http://pfam.sanger.ac.uk/. We can load this file as follows (assuming it has been saved to disk as “PF05371_seed.sth” in the current working directory):

Sanger provide a nice web interface at http://pfam.sanger.ac.uk/family?acc=PF05371 which will actually let you download this alignment in several other formats. This is what the file looks like in the FASTA file format:

Note the website should have an option about showing gaps as periods (dots) or dashes, we’ve shown dashes above. Assuming you download and save this as file “PF05371_seed.faa” then you can load it with almost exactly the same code:

All that has changed in this code is the filename and the format string. You’ll get the same output as before, the sequences and record identifiers are the same.
However, as you should expect, if you check each SeqRecord there is no annotation nor database cross-references because these are not included in the FASTA file format.

Note that rather than using the Sanger website, you could have used Bio.AlignIO to convert the original Stockholm format file into a FASTA file yourself (see below).

With any supported file format, you can load an alignment in exactly the same way just by changing the format string. For example, use “phylip” for PHYLIP files, “nexus” for NEXUS files or “emboss” for the alignments output by the EMBOSS tools. There is a full listing on the wiki page (http://biopython.org/wiki/AlignIO) and in the built in documentation (also online):

The previous section focused on reading files containing a single alignment. In general however, files can contain more than one alignment, and to read these files we must use the Bio.AlignIO.parse() function.

Suppose you have a small alignment in PHYLIP format:

5 6
Alpha AACAAC
Beta AACCCC
Gamma ACCAAC
Delta CCACCA
Epsilon CCAAAC

If you wanted to bootstrap a phylogenetic tree using the PHYLIP tools, one of the steps would be to create a set of many resampled alignments using the tool bootseq. This would give output something like this, which has been abbreviated for conciseness:

As with the function Bio.SeqIO.parse(), using Bio.AlignIO.parse() returns an iterator.
If you want to keep all the alignments in memory at once, which will allow you to access them in any order, then turn the iterator into a list:

Many alignment file formats can explicitly store more than one alignment, and the division between each alignment is clear. However, when a general sequence file format has been used there is no such block structure. The most common such situation is when alignments have been saved in the FASTA file format. For example consider the following:

This could be a single alignment containing six sequences (with repeated identifiers). Or, judging from the identifiers, this is probably two different alignments each with three sequences, which happen to all have the same length.

In this third example, because of the differing lengths, this cannot be treated as a single alignment containing all six records. However, it could be three pairwise alignments.

Clearly trying to store more than one alignment in a FASTA file is not ideal. However, if you are forced to deal with these as input files Bio.AlignIO can cope with the most common situation where all the alignments have the same number of records.
One example of this is a collection of pairwise alignments, which can be produced by the EMBOSS tools needle and water – although in this situation, Bio.AlignIO should be able to understand their native output using “emboss” as the format string.

To interpret these FASTA examples as several separate alignments, we can use Bio.AlignIO.parse() with the optional seq_count argument which specifies how many sequences are expected in each alignment (in these examples, 3, 2 and 2 respectively).
For example, using the third example as the input data:

Using Bio.AlignIO.read() or Bio.AlignIO.parse() without the seq_count argument would give a single alignment containing all six records for the first two examples. For the third example, an exception would be raised because the lengths differ preventing them being turned into a single alignment.

If the file format itself has a block structure allowing Bio.AlignIO to determine the number of sequences in each alignment directly, then the seq_count argument is not needed. If it is supplied, and doesn’t agree with the file contents, an error is raised.

Note that this optional seq_count argument assumes each alignment in the file has the same number of sequences. Hypothetically you may come across stranger situations, for example a FASTA file containing several alignments each with a different number of sequences – although I would love to hear of a real world example of this. Assuming you cannot get the data in a nicer file format, there is no straight forward way to deal with this using Bio.AlignIO. In this case, you could consider reading in the sequences themselves using Bio.SeqIO and batching them together to create the alignments as appropriate.

We’ve talked about using Bio.AlignIO.read() and Bio.AlignIO.parse() for alignment input (reading files), and now we’ll look at Bio.AlignIO.write() which is for alignment output (writing files). This is a function taking three arguments: some MultipleSeqAlignment objects (or for backwards compatibility the obsolete Alignment objects), a handle or filename to write to, and a sequence format.

Here is an example, where we start by creating a few MultipleSeqAlignment objects the hard way (by hand, rather than by loading them from a file).
Note we create some SeqRecord objects to construct the alignment from.

Its more common to want to load an existing alignment, and save that, perhaps after some simple manipulation like removing certain rows or columns.

Suppose you wanted to know how many alignments the Bio.AlignIO.write() function wrote to the handle? If your alignments were in a list like the example above, you could just use len(my_alignments), however you can’t do that when your records come from a generator/iterator. Therefore the Bio.AlignIO.write() function returns the number of alignments written to the file.

Note - If you tell the Bio.AlignIO.write() function to write to a file that already exists, the old file will be overwritten without any warning.

Converting between sequence alignment file formats with Bio.AlignIO works
in the same way as converting between sequence file formats with Bio.SeqIO
(Section 5.5.2). We load generally the alignment(s) using
Bio.AlignIO.parse() and then save them using the Bio.AlignIO.write()
– or just use the Bio.AlignIO.convert() helper function.

For this example, we’ll load the PFAM/Stockholm format file used earlier and save it as a Clustal W format file:

The Bio.AlignIO.write() function expects to be given multiple alignment objects. In the example above we gave it the alignment iterator returned by Bio.AlignIO.parse().

In this case, we know there is only one alignment in the file so we could have used Bio.AlignIO.read() instead, but notice we have to pass this alignment to Bio.AlignIO.write() as a single element list:

One of the big handicaps of the original PHYLIP alignment file format is
that the sequence identifiers are strictly truncated at ten characters.
In this example, as you can see the resulting names are still unique -
but they are not very readable. As a result, a more relaxed variant of
the original PHYLIP format is now quite widely used:

If you have to work with the original strict PHYLIP format, then you may need to
compress the identifers somehow – or assign your own names or numbering system.
This following bit of code manipulates the record identifiers before saving the output:

In general, because of the identifier limitation, working with
strict PHYLIP file formats shouldn’t be your first choice.
Using the PFAM/Stockholm format on the other hand allows you to record a lot of additional annotation too.

The Bio.AlignIO interface is based on handles, which means if you want to get your alignment(s) into a string in a particular file format you need to do a little bit more work (see below).
However, you will probably prefer to take advantage of the alignment object’s format() method.
This takes a single mandatory argument, a lower case string which is supported by Bio.AlignIO as an output format. For example:

First of all, in some senses the alignment objects act like a Python list of
SeqRecord objects (the rows). With this model in mind hopefully the actions
of len() (the number of rows) and iteration (each row as a SeqRecord)
make sense:

You can also use the list-like append and extend methods to add
more rows to the alignment (as SeqRecord objects). Keeping the list
metaphor in mind, simple slicing of the alignment should also make sense -
it selects some of the rows giving back another alignment object:

Another common use of alignment addition would be to combine alignments for
several different genes into a meta-alignment. Watch out though - the identifiers
need to match up (see Section 4.7 for how adding
SeqRecord objects works). You may find it helpful to first sort the
alignment rows alphabetically by id:

There are lots of algorithms out there for aligning sequences, both pairwise alignments
and multiple sequence alignments. These calculations are relatively slow, and you generally
wouldn’t want to write such an algorithm in Python. Instead, you can use Biopython to invoke
a command line tool on your behalf. Normally you would:

Prepare an input file of your unaligned sequences, typically this will be a FASTA file
which you might create using Bio.SeqIO (see Chapter 5).

Call the command line tool to process this input file, typically via one of Biopython’s
command line wrappers (which we’ll discuss here).

Read the output from the tool, i.e. your aligned sequences, typically using
Bio.AlignIO (see earlier in this chapter).

All the command line wrappers we’re going to talk about in this chapter follow the same style.
You create a command line object specifying the options (e.g. the input filename and the
output filename), then invoke this command line via a Python operating system call (e.g.
using the subprocess module).

Most of these wrappers are defined in the Bio.Align.Applications module:

(Ignore the entries starting with an underscore – these have
special meaning in Python.)
The module Bio.Emboss.Applications has wrappers for some of the
EMBOSS suite, including
needle and water, which are described below in
Section 6.4.5, and wrappers for the EMBOSS
packaged versions of the PHYLIP tools (which EMBOSS refer to as one
of their EMBASSY packages - third party tools with an EMBOSS style
interface).
We won’t explore all these alignment tools here in the section, just a
sample, but the same principles apply.

ClustalW is a popular command line tool for multiple sequence alignment
(there is also a graphical interface called ClustalX). Biopython’s
Bio.Align.Applications module has a wrapper for this alignment tool
(and several others).

Before trying to use ClustalW from within Python, you should first try running
the ClustalW tool yourself by hand at the command line, to familiarise
yourself the other options. You’ll find the Biopython wrapper is very
faithful to the actual command line API:

For the most basic usage, all you need is to have a FASTA input file, such as
opuntia.fasta
(available online or in the Doc/examples subdirectory of the Biopython source
code). This is a small FASTA file containing seven prickly-pear DNA sequences
(from the cactus family Opuntia).

By default ClustalW will generate an alignment and guide tree file with names
based on the input FASTA file, in this case opuntia.aln and
opuntia.dnd, but you can override this or make it explicit:

Notice here we have given the executable name as clustalw2,
indicating we have version two installed, which has a different filename to
version one (clustalw, the default). Fortunately both versions
support the same set of arguments at the command line (and indeed, should be
functionally identical).

You may find that even though you have ClustalW installed, the above command
doesn’t work – you may get a message about “command not found” (especially
on Windows). This indicated that the ClustalW executable is not on your PATH
(an environment variable, a list of directories to be searched). You can
either update your PATH setting to include the location of your copy of
ClustalW tools (how you do this will depend on your OS), or simply type in
the full path of the tool. For example:

Remember, in Python strings \n and \t are by default
interpreted as a new line and a tab – which is why we’re put a letter
“r” at the start for a raw string that isn’t translated in this way.
This is generally good practice when specifying a Windows style file name.

Internally this uses the
subprocess module which is now the recommended way to run another
program in Python. This replaces older options like the os.system()
and the os.popen* functions.

Now, at this point it helps to know about how command line tools “work”.
When you run a tool at the command line, it will often print text output
directly to screen. This text can be captured or redirected, via
two “pipes”, called standard output (the normal results) and standard
error (for error messages and debug messages). There is also standard
input, which is any text fed into the tool. These names get shortened
to stdin, stdout and stderr. When the tool finishes, it has a return
code (an integer), which by convention is zero for success.

When you run the command line tool like this via the Biopython wrapper,
it will wait for it to finish, and check the return code. If this is
non zero (indicating an error), an exception is raised. The wrapper
then returns two strings, stdout and stderr.

In the case of ClustalW, when run at the command line all the important
output is written directly to the output files. Everything normally printed to
screen while you wait (via stdout or stderr) is boring and can be
ignored (assuming it worked).

What we care about are the two output files, the alignment and the guide
tree. We didn’t tell ClustalW what filenames to use, but it defaults to
picking names based on the input file. In this case the output should be
in the file opuntia.aln.
You should be able to work out how to read in the alignment using
Bio.AlignIO by now:

MUSCLE is a more recent multiple sequence alignment tool than ClustalW, and
Biopython also has a wrapper for it under the Bio.Align.Applications
module. As before, we recommend you try using MUSCLE from the command line before
trying it from within Python, as the Biopython wrapper is very faithful to the
actual command line API:

For the most basic usage, all you need is to have a FASTA input file, such as
opuntia.fasta
(available online or in the Doc/examples subdirectory of the Biopython source
code). You can then tell MUSCLE to read in this FASTA file, and write the
alignment to an output file:

Note that MUSCLE uses “-in” and “-out” but in Biopython we have to use
“input” and “out” as the keyword arguments or property names. This is
because “in” is a reserved word in Python.

By default MUSCLE will output the alignment as a FASTA file (using gapped
sequences). The Bio.AlignIO module should be able to read this
alignment using format="fasta".
You can also ask for ClustalW-like output:

Using a MUSCLE command line as in the examples above will write the alignment
to a file. This means there will be no important information written to the
standard out (stdout) or standard error (stderr) handles. However, by default
MUSCLE will write the alignment to standard output (stdout). We can take
advantage of this to avoid having a temporary output file! For example:

If we run this via the wrapper, we get back the output as a string. In order
to parse this we can use StringIO to turn it into a handle.
Remember that MUSCLE defaults to using FASTA as the output format:

The above approach is fairly simple, but if you are dealing with very large output
text the fact that all of stdout and stderr is loaded into memory as a string can
be a potential drawback. Using the subprocess module we can work directly
with handles instead:

We don’t actually need to have our FASTA input sequences prepared in a file,
because by default MUSCLE will read in the input sequence from standard input!
Note this is a bit more advanced and fiddly, so don’t bother with this technique
unless you need to.

First, we’ll need some unaligned sequences in memory as SeqRecord objects.
For this demonstration I’m going to use a filtered version of the original FASTA
file (using a generator expression), taking just six of the seven sequences:

After writing the six sequences to the handle, MUSCLE will still be waiting
to see if that is all the FASTA sequences or not – so we must signal that
this is all the input data by closing the handle. At that point MUSCLE should
start to run, and we can ask for the output:

Wow! There we are with a new alignment of just the six records, without having created
a temporary FASTA input file, or a temporary alignment output file. However, a word of
caution: Dealing with errors with this style of calling external programs is much more
complicated.
It also becomes far harder to diagnose problems, because you can’t try running MUSCLE
manually outside of Biopython (because you don’t have the input file to supply).
There can also be subtle cross platform issues (e.g. Windows versus Linux,
Python 2 versus Python 3), and how
you run your script can have an impact (e.g. at the command line, from IDLE or an
IDE, or as a GUI script). These are all generic Python issues though, and not
specific to Biopython.

If you find working directly with subprocess like this scary, there is an
alternative. If you execute the tool with muscle_cline() you can supply
any standard input as a big string, muscle_cline(stdin=...). So,
provided your data isn’t very big, you can prepare the FASTA input in memory as
a string using StringIO (see Section 22.1):

The EMBOSS suite includes the water and
needle tools for Smith-Waterman algorithm local alignment, and Needleman-Wunsch
global alignment. The tools share the same style interface, so switching between the two
is trivial – we’ll just use needle here.

Suppose you want to do a global pairwise alignment between two sequences, prepared in
FASTA format as follows:

Why not try running this by hand at the command prompt? You should see it does a
pairwise comparison and records the output in the file needle.txt (in the
default EMBOSS alignment file format).

Even if you have EMBOSS installed, running this command may not work – you
might get a message about “command not found” (especially on Windows). This
probably means that the EMBOSS tools are not on your PATH environment
variable. You can either update your PATH setting, or simply tell Biopython
the full path to the tool, for example:

Next we want to use Python to run this command for us. As explained above,
for full control, we recommend you use the built in Python subprocess
module, but for simple usage the wrapper object usually suffices:

In this example, we told EMBOSS to write the output to a file, but you
can tell it to write the output to stdout instead (useful if you
don’t want a temporary output file to get rid of – use
stdout=True rather than the outfile argument), and
also to read one of the one of the inputs from stdin (e.g.
asequence="stdin", much like in the MUSCLE example in the
section above).

This has only scratched the surface of what you can do with needle
and water. One useful trick is that the second file can contain
multiple sequences (say five), and then EMBOSS will do five pairwise
alignments.

Note - Biopython includes its own pairwise alignment code in the Bio.pairwise2
module (written in C for speed, but with a pure Python fallback available too). This
doesn’t work with alignment objects, so we have not covered it within this chapter.
See the module’s docstring (built in help) for details.

Hey, everybody loves BLAST right? I mean, geez, how can get it get any easier to do comparisons between one of your sequences and every other sequence in the known world? But, of course, this section isn’t about how cool BLAST is, since we already know that. It is about the problem with BLAST – it can be really difficult to deal with the volume of data generated by large runs, and to automate BLAST runs in general.

Fortunately, the Biopython folks know this only too well, so they’ve developed lots of tools for dealing with BLAST and making things much easier. This section details how to use these tools and do useful things with them.

Dealing with BLAST can be split up into two steps, both of which can be done from within Biopython.
Firstly, running BLAST for your query sequence(s), and getting some output.
Secondly, parsing the BLAST output in Python for further analysis.

Your first introduction to running BLAST was probably via the NCBI web-service.
In fact, there are lots of ways you can run BLAST, which can be categorised several ways.
The most important distinction is running BLAST locally (on your own machine),
and running BLAST remotely (on another machine, typically the NCBI servers).
We’re going to start this chapter by invoking the NCBI online BLAST service
from within a Python script.

NOTE: The following Chapter 8 describes
Bio.SearchIO, an experimental module in Biopython. We
intend this to ultimately replace the older Bio.Blast module, as it
provides a more general framework handling other related sequence
searching tools as well. However, until that is declared stable, for
production code please continue to use the Bio.Blast module
for dealing with NCBI BLAST.

We use the function qblast() in the Bio.Blast.NCBIWWW module
call the online version of BLAST. This has three non-optional arguments:

The first argument is the blast program to use for the search, as a
lower case string. The options and descriptions of the programs are
available at http://www.ncbi.nlm.nih.gov/BLAST/blast_program.shtml.
Currently qblast only works with blastn, blastp, blastx, tblast
and tblastx.

The third argument is a string containing your query sequence. This
can either be the sequence itself, the sequence in fasta format,
or an identifier like a GI number.

The qblast function also take a number of other option arguments
which are basically analogous to the different parameters you can set
on the BLAST web page. We’ll just highlight a few of them here:

The qblast function can return the BLAST results in various
formats, which you can choose with the optional format_type keyword:
"HTML", "Text", "ASN.1", or "XML".
The default is "XML", as that is the format expected by the parser,
described in section 7.3 below.

The argument expect sets the expectation or e-value threshold.

For more about the optional BLAST arguments, we refer you to the NCBI’s own
documentation, or that built into Biopython:

>>> from Bio.Blast import NCBIWWW
>>> help(NCBIWWW.qblast)
...

Note that the default settings on the NCBI BLAST website are not quite
the same as the defaults on QBLAST. If you get different results, you’ll
need to check the parameters (e.g. the expectation value threshold and
the gap values).

For example, if you have a nucleotide sequence you want to search against
the nucleotide database (nt) using BLASTN, and you know the GI number of your
query sequence, you can use:

Supplying just the sequence means that BLAST will assign an identifier
for your sequence automatically. You might prefer to use the
SeqRecord object’s format method to make a fasta string
(which will include the existing identifier):

This approach makes more sense if you have your sequence(s) in a
non-FASTA file format which you can extract using Bio.SeqIO
(see Chapter 5).

Whatever arguments you give the qblast() function, you should
get back your results in a handle object (by default in XML format).
The next step would be to parse the XML output into Python objects
representing the search results (Section 7.3),
but you might want to save a local copy of the output file first.
I find this especially useful when debugging my code that extracts
info from the BLAST results (because re-running the online search
is slow and wastes the NCBI computer time).

We need to be a bit careful since we can use result_handle.read() to
read the BLAST output only once – calling result_handle.read() again
returns an empty string.

After doing this, the results are in the file my_blast.xml and the
original handle has had all its data extracted (so we closed it). However,
the parse function of the BLAST parser (described
in 7.3) takes a file-handle-like object, so
we can just open the saved file for input:

>>> result_handle = open("my_blast.xml")

Now that we’ve got the BLAST results back into a handle again, we are ready
to do something with them, so this leads us right into the parsing section
(see Section 7.3 below). You may want to jump ahead to
that now ….

Running BLAST locally (as opposed to over the internet, see
Section 7.1) has at least major two advantages:

Local BLAST may be faster than BLAST over the internet;

Local BLAST allows you to make your own database to search for sequences against.

Dealing with proprietary or unpublished sequence data can be another reason to run BLAST
locally. You may not be allowed to redistribute the sequences, so submitting them to the
NCBI as a BLAST query would not be an option.

Unfortunately, there are some major drawbacks too – installing all the bits and getting
it setup right takes some effort:

Local BLAST requires command line tools to be installed.

Local BLAST requires (large) BLAST databases to be setup (and potentially kept up to date).

To further confuse matters there are several different BLAST packages available,
and there are also other tools which can produce imitation BLAST output files, such as BLAT.

The “new”
NCBI BLAST+ suite was released in 2009. This replaces the old NCBI “legacy” BLAST
package (see below).

This section will show briefly how to use these tools from within Python. If you have
already read or tried the alignment tool examples in Section 6.4
this should all seem quite straightforward. First, we construct a command line string
(as you would type in at the command line prompt if running standalone BLAST by hand).
Then we can execute this command from within Python.

For example, taking a FASTA file of gene nucleotide sequences, you might want to
run a BLASTX (translation) search against the non-redundant (NR) protein database.
Assuming you (or your systems administrator) has downloaded and installed the NR
database, you might run:

This should run BLASTX against the NR database, using an expectation cut-off value
of 0.001 and produce XML output to the specified file (which we can then parse).
On my computer this takes about six minutes - a good reason to save the output
to a file so you and repeat any analysis as needed.

From within Biopython we can use the NCBI BLASTX wrapper from the
Bio.Blast.Applications module to build the command line string,
and run it:

In this example there shouldn’t be any output from BLASTX to the terminal,
so stdout and stderr should be empty. You may want to check the output file
opuntia.xml has been created.

As you may recall from earlier examples in the tutorial, the opuntia.fasta
contains seven sequences, so the BLAST XML output should contain multiple results.
Therefore use Bio.Blast.NCBIXML.parse() to parse it as described below in
Section 7.3.

NCBI BLAST+ (written in C++) was first released in 2009 as a replacement for
the original NCBI “legacy” BLAST (written in C) which is no longer being updated.
There were a lot of changes – the old version had a single core command line
tool blastall which covered multiple different BLAST search types (which
are now separate commands in BLAST+), and all the command line options
were renamed.
Biopython’s wrappers for the NCBI “legacy” BLAST tools have been deprecated
and will be removed in a future release.
To try to avoid confusion, we do not cover calling these old tools from Biopython
in this tutorial.

You may also come across Washington University BLAST
(WU-BLAST), and its successor, Advanced Biocomputing
BLAST (AB-BLAST, released in 2009, not free/open source). These packages include
the command line tools wu-blastall and ab-blastall, which mimicked
blastall from the NCBI “legacy” BLAST stuie.
Biopython does not currently provide wrappers for calling these tools, but should be able
to parse any NCBI compatible output from them.

As mentioned above, BLAST can generate output in various formats, such as
XML, HTML, and plain text. Originally, Biopython had parsers for BLAST
plain text and HTML output, as these were the only output formats offered
at the time. Unfortunately, the BLAST output in these formats kept changing,
each time breaking the Biopython parsers. Our HTML BLAST parser has been
removed, but the plain text BLAST parser is still available (see
Section 7.5). Use it at your own risk,
it may or may not work, depending on which BLAST version you’re using.

As keeping up with changes in BLAST
became a hopeless endeavor, especially with users running different BLAST
versions, we now recommend to parse the output in XML format, which can be
generated by recent versions of BLAST. Not only is the XML output more stable
than the plain text and HTML output, it is also much easier to parse
automatically, making Biopython a whole lot more stable.

You can get BLAST output in XML format in various ways. For the parser, it
doesn’t matter how the output was generated, as long as it is in the XML format.

You can use Biopython to run BLAST over the internet, as described in
section 7.1.

You can use Biopython to run BLAST locally, as described in
section 7.2.

You can do the BLAST search yourself on the NCBI site through your
web browser, and then save the results. You need to choose XML as the format
in which to receive the results, and save the final BLAST page you get
(you know, the one with all of the interesting results!) to a file.

You can also run BLAST locally without using Biopython, and save
the output in a file. Again, you need to choose XML as the format in which
to receive the results.

The important point is that you do not have to use Biopython
scripts to fetch the data in order to be able to parse it.
Doing things in one of these ways, you then need to get a handle
to the results. In Python, a handle is just a nice general way of
describing input to any info source so that the info can be retrieved
using read() and readline() functions
(see Section sec:appendix-handles).

If you followed the code above for interacting with BLAST through a
script, then you already have result_handle, the handle to the
BLAST results. For example, using a GI number to do an online search:

Just like Bio.SeqIO and Bio.AlignIO
(see Chapters 5 and 6),
we have a pair of input functions, read and parse, where
read is for when you have exactly one object, and parse
is an iterator for when you can have lots of objects – but instead of
getting SeqRecord or MultipleSeqAlignment objects, we
get BLAST record objects.

To be able to handle the situation where the BLAST file may be huge,
containing thousands of results, NCBIXML.parse() returns an
iterator. In plain English, an iterator allows you to step through
the BLAST output, retrieving BLAST records one by one for each BLAST
search result:

>>> for blast_record in blast_records:
... # Do something with blast_record

Note though that you can step through the BLAST records only once.
Usually, from each BLAST record you would save the information that
you are interested in. If you want to save all returned BLAST records,
you can convert the iterator into a list:

>>> blast_records = list(blast_records)

Now you can access each BLAST record in the list with an index as usual.
If your BLAST file is huge though, you may run into memory problems trying to
save them all in a list.

Usually, you’ll be running one BLAST search at a time. Then, all you need
to do is to pick up the first (and only) BLAST record in blast_records:

A BLAST Record contains everything you might ever want to extract from the
BLAST output. Right now we’ll just show
an example of how to get some info out of the BLAST report, but if you
want something in particular that is not described here, look at the
info on the record class in detail, and take a gander into the code or
automatically generated documentation – the docstrings have lots of
good info about what is stored in each piece of information.

To continue with our example, let’s just print out some summary info
about all hits in our blast report greater than a particular
threshold. The following code does this:

Basically, you can do anything you want to with the info in the BLAST
report once you have parsed it. This will, of course, depend on what
you want to use it for, but hopefully this helps you get started on
doing what you need to do!

An important consideration for extracting information from a BLAST report is the type of objects that the information is stored in. In Biopython, the parsers return Record objects, either Blast or PSIBlast depending on what you are parsing. These objects are defined in Bio.Blast.Record and are quite complete.

Here are my attempts at UML class diagrams for the Blast and PSIBlast record classes. If you are good at UML and see mistakes/improvements that can be made, please let me know. The Blast class diagram is shown in Figure 7.4.

The PSIBlast record object is similar, but has support for the rounds that are used in the iteration steps of PSIBlast. The class diagram for PSIBlast is shown in Figure 7.4.

Older versions of Biopython had parsers for BLAST output in plain text or HTML
format. Over the years, we discovered that it is very hard to maintain these
parsers in working order. Basically, any small change to the BLAST output in
newly released BLAST versions tends to cause the plain text and HTML parsers
to break. We therefore recommend parsing BLAST output in XML format, as
described in section 7.3.

Depending on which BLAST versions or programs you’re using, our plain text BLAST parser may or may not work. Use it at your own risk!

As with the XML parser, we need to have a handle object that we can pass to the parser. The handle must implement the readline() method and do this properly. The common ways to get such a handle are to either use the provided blastall or blastpgp functions to run the local blast, or to run a local blast via the command line, and then do something like the following:

>>> result_handle = open("my_file_of_blast_output.txt")

Well, now that we’ve got a handle (which we’ll call result_handle),
we are ready to parse it. This can be done with the following code:

This will parse the BLAST report into a Blast Record class (either a Blast or a PSIBlast record, depending on what you are parsing) so that you can extract the information from it. In our case, let’s just use print out a quick summary of all of the alignments greater than some threshold value.

If you also read the section 7.3 on parsing BLAST XML output, you’ll notice that the above code is identical to what is found in that section. Once you parse something into a record class you can deal with it independent of the format of the original BLAST info you were parsing. Pretty snazzy!

Sure, parsing one record is great, but I’ve got a BLAST file with tons of records – how can I parse them all? Well, fear not, the answer lies in the very next section.

One really ugly problem that happens to me is that I’ll be parsing a huge blast file for a while, and the parser will bomb out with a ValueError. This is a serious problem, since you can’t tell if the ValueError is due to a parser problem, or a problem with the BLAST. To make it even worse, you have no idea where the parse failed, so you can’t just ignore the error, since this could be ignoring an important data point.

We used to have to make a little script to get around this problem, but the Bio.Blast module now includes a BlastErrorParser which really helps make this easier. The BlastErrorParser works very similar to the regular BlastParser, but it adds an extra layer of work by catching ValueErrors that are generated by the parser, and attempting to diagnose the errors.

Let’s take a look at using this parser – first we define the file we are going to parse and the file to write the problem reports to:

Notice that the parser take an optional argument of a handle. If a handle is passed, then the parser will write any blast records which generate a ValueError to this handle. Otherwise, these records will not be recorded.

Now we can use the BlastErrorParser just like a regular blast parser. Specifically, we might want to make an iterator that goes through our blast records one at a time and parses them with the error parser:

The next() functionality is normally called indirectly via a for-loop.
Right now the BlastErrorParser can generate the following errors:

ValueError – This is the same error generated by the regular BlastParser, and is due to the parser not being able to parse a specific file. This is normally either due to a bug in the parser, or some kind of discrepancy between the version of BLAST you are using and the versions the parser is able to handle.

LowQualityBlastError – When BLASTing a sequence that is of really bad quality (for example, a short sequence that is basically a stretch of one nucleotide), it seems that Blast ends up masking out the entire sequence and ending up with nothing to parse. In this case it will produce a truncated report that causes the parser to generate a ValueError. LowQualityBlastError is reported in these cases. This error returns an info item with the following information:

item[0] – The error message

item[1] – The id of the input record that caused the error. This is really useful if you want to record all of the records that are causing problems.

As mentioned, with each error generated, the BlastErrorParser will write the offending record to the specified error_handle. You can then go ahead and look and these and deal with them as you see fit. Either you will be able to debug the parser with a single blast report, or will find out problems in your blast runs. Either way, it will definitely be a useful experience!

Hopefully the BlastErrorParser will make it much easier to debug and deal with large Blast files.

You can run the standalone version of PSI-BLAST (the legacy NCBI command line
tool blastpgp, or its replacement psiblast) using the wrappers
in Bio.Blast.Applications module.

At the time of writing, the NCBI do not appear to support tools running a
PSI-BLAST search via the internet.

Note that the Bio.Blast.NCBIXML parser can read the XML output from
current versions of PSI-BLAST, but information like which sequences in each
iteration is new or reused isn’t present in the XML file.
If you care about this information you may have more joy with the plain text
output and the PSIBlastParser in Bio.Blast.NCBIStandalone.

WARNING: This chapter of the Tutorial describes an experimental
module in Biopython. It is being included in Biopython and documented
here in the tutorial in a pre-final state to allow a period of feedback
and refinement before we declare it stable. Until then the details will
probably change, and any scripts using the current Bio.SearchIO
would need to be updated. Please keep this in mind! For stable code
working with NCBI BLAST, please continue to use Bio.Blast described
in the preceding Chapter 7.

Biological sequence identification is an integral part of bioinformatics.
Several tools are available for this, each with their own algorithms and
approaches, such as BLAST (arguably the most popular), FASTA, HMMER, and many
more. In general, these tools usually use your sequence to search a database of
potential matches. With the growing number of known sequences (hence the
growing number of potential matches), interpreting the results becomes
increasingly hard as there could be hundreds or even thousands of potential
matches. Naturally, manual interpretation of these searches’ results is out of
the question. Moreover, you often need to work with several sequence search
tools, each with its own statistics, conventions, and output format. Imagine how
daunting it would be when you need to work with multiple sequences using
multiple search tools.

We know this too well ourselves, which is why we created the Bio.SearchIO
submodule in Biopython. Bio.SearchIO allows you to extract information
from your search results in a convenient way, while also dealing with the
different standards and conventions used by different search tools.
The name SearchIO is a homage to BioPerl’s module of the same name.

In this chapter, we’ll go through the main features of Bio.SearchIO to
show what it can do for you. We’ll use two popular search tools along the way:
BLAST and BLAT. They are used merely for illustrative purposes, and you should
be able to adapt the workflow to any other search tools supported by
Bio.SearchIO in a breeze. You’re very welcome to follow along with the
search output files we’ll be using. The BLAST output file can be downloaded
here,
and the BLAT output file
here.
Both output files were generated using this sequence:

The BLAST result is an XML file generated using blastn against the NCBI
refseq_rna database. For BLAT, the sequence database was the February 2009
hg19 human genome draft and the output format is PSL.

We’ll start from an introduction to the Bio.SearchIO object model. The
model is the representation of your search results, thus it is core to
Bio.SearchIO itself. After that, we’ll check out the main functions in
Bio.SearchIO that you may often use.

Now that we’re all set, let’s go to the first step: introducing the core
object model.

Despite the wildly differing output styles among many sequence search tools,
it turns out that their underlying concept is similar:

The output file may contain results from one or more search queries.

In each search query, you will see one or more hits from the given
search database.

In each database hit, you will see one or more regions containing the
actual sequence alignment between your query sequence and the database
sequence.

Some programs like BLAT or Exonerate may further split these regions into
several alignment fragments (or blocks in BLAT and possibly exons in
exonerate). This is not something you always see, as programs like BLAST and
HMMER do not do this.

Realizing this generality, we decided use it as base for creating the
Bio.SearchIO object model. The object model consists of a nested
hierarchy of Python objects, each one representing one concept outlined above.
These objects are:

QueryResult, to represent a single search query.

Hit, to represent a single database hit. Hit objects are
contained within QueryResult and in each QueryResult there is
zero or more Hit objects.

HSP (short for high-scoring pair), to represent region(s) of
significant alignments between query and hit sequences. HSP objects
are contained within Hit objects and each Hit has one or more
HSP objects.

HSPFragment, to represent a single contiguous alignment between
query and hit sequences. HSPFragment objects are contained within
HSP objects. Most sequence search tools like BLAST and HMMER unify
HSP and HSPFragment objects as each HSP will only have
a single HSPFragment. However there are tools like BLAT and Exonerate
that produce HSP containing multiple HSPFragment. Don’t worry
if this seems a tad confusing now, we’ll elaborate more on these two objects
later on.

These four objects are the ones you will interact with when you use
Bio.SearchIO. They are created using one of the main Bio.SearchIO
methods: read, parse, index, or index_db. The
details of these methods are provided in later sections. For this section, we’ll
only be using read and parse. These functions behave similarly to their
Bio.SeqIO and Bio.AlignIO counterparts:

read is used for search output files with a single query and
returns a QueryResult object

parse is used for search output files with multiple queries and
returns a generator that yields QueryResult objects

With that settled, let’s start probing each Bio.SearchIO object,
beginning with QueryResult.

We’ve just begun to scratch the surface of the object model, but you can see that
there’s already some useful information. By invoking print on the
QueryResult object, you can see:

The program name and version (blastn version 2.2.27+)

The query ID, description, and its sequence length (ID is 42291,
description is ‘mystery_seq’, and it is 61 nucleotides long)

The target database to search against (refseq_rna)

A quick overview of the resulting hits. For our query sequence, there are
100 potential hits (numbered 0–99 in the table). For each hit, we can also see
how many HSPs it contains, its ID, and a snippet of its description. Notice
here that Bio.SearchIO truncates the hit table overview, by showing
only hits numbered 0–29, and then 97–99.

You’ll immediately notice that there are some differences. Some of these are
caused by the way PSL format stores its details, as you’ll see. The rest are
caused by the genuine program and target database differences between our BLAST
and BLAT searches:

The program name and version. Bio.SearchIO knows that the program
is BLAT, but in the output file there is no information regarding the
program version so it defaults to ‘<unknown version>’.

The query ID, description, and its sequence length. Notice here that these
details are slightly different from the ones we saw in BLAST. The ID is
‘mystery_seq’ instead of 42991, there is no known description, but the query
length is still 61. This is actually a difference introduced by the file
formats themselves. BLAST sometimes creates its own query IDs and uses your
original ID as the sequence description.

The target database is not known, as it is not stated in the BLAT output
file.

And finally, the list of hits we have is completely different. Here, we
see that our query sequence only hits the ‘chr19’ database entry, but in it
we see 17 HSP regions. This should not be surprising however, given that we
are using a different program, each with its own target database.

All the details you saw when invoking the print method can be accessed
individually using Python’s object attribute access notation (a.k.a. the dot
notation). There are also other format-specific attributes that you can access
using the same method.

For a complete list of accessible attributes, you can check each format-specific
documentation. Here are the ones
for BLAST
and for
BLAT.

Having looked at using print on QueryResult objects, let’s drill
down deeper. What exactly is a QueryResult? In terms of Python objects,
QueryResult is a hybrid between a list and a dictionary. In other words,
it is a container object with all the convenient features of lists and
dictionaries.

Like Python lists and dictionaries, QueryResult objects are iterable.
Each iteration returns a Hit object:

Sometimes, knowing whether a hit is present is not enough; you also want to know
the rank of the hit. Here, the index method comes to the rescue:

>>> blast_qresult.index('gi|301171437|ref|NR_035870.1|')
22

Remember that we’re using Python’s indexing style here, which is zero-based.
This means our hit above is ranked at no. 23, not 22.

Also, note that the hit rank you see here is based on the native hit ordering
present in the original search output file. Different search tools may order
these hits based on different criteria.

If the native hit ordering doesn’t suit your taste, you can use the sort
method of the QueryResult object. It is very similar to Python’s
list.sort method, with the addition of an option to create a new sorted
QueryResult object or not.

Here is an example of using QueryResult.sort to sort the hits based on
each hit’s full sequence length. For this particular sort, we’ll set the
in_place flag to False so that sorting will return a new
QueryResult object and leave our initial object unsorted. We’ll also set
the reverse flag to True so that we sort in descending order.

The advantage of having the in_place flag here is that we’re preserving
the native ordering, so we may use it again later. You should note that this is
not the default behavior of QueryResult.sort, however, which is why we
needed to set the in_place flag to True explicitly.

At this point, you’ve known enough about QueryResult objects to make it
work for you. But before we go on to the next object in the Bio.SearchIO
model, let’s take a look at two more sets of methods that could make it even
easier to work with QueryResult objects: the filter and map
methods.

If you’re familiar with Python’s list comprehensions, generator expressions
or the built in filter and map functions,
you’ll know how useful they are for working with list-like objects (if you’re
not, check them out!). You can use these built in methods to manipulate
QueryResult objects, but you’ll end up with regular Python lists and lose
the ability to do more interesting manipulations.

That’s why, QueryResult objects provide its own flavor of
filter and map methods. Analogous to filter, there are
hit_filter and hsp_filter methods. As their name implies, these
methods filter its QueryResult object either on its Hit objects
or HSP objects. Similarly, analogous to map, QueryResult
objects also provide the hit_map and hsp_map methods. These
methods apply a given function to all hits or HSPs in a QueryResult
object, respectively.

Let’s see these methods in action, beginning with hit_filter. This method
accepts a callback function that checks whether a given Hit object passes
the condition you set or not. In other words, the function must accept as its
argument a single Hit object and returns True or False.

Here is an example of using hit_filter to filter out Hit objects
that only have one HSP:

hsp_filter works the same as hit_filter, only instead of looking
at the Hit objects, it performs filtering on the HSP objects in
each hits.

As for the map methods, they too accept a callback function as their
arguments. However, instead of returning True or False, the
callback function must return the modified Hit or HSP object
(depending on whether you’re using hit_map or hsp_map).

Hit objects represent all query results from a single database entry.
They are the second-level container in the Bio.SearchIO object hierarchy.
You’ve seen that they are contained by QueryResult objects, but they
themselves contain HSP objects.

The query ID and description is present. A hit is always tied to a query,
so we want to keep track of the originating query as well. These values can
be accessed from a hit using the query_id and
query_description attributes.

We also have the unique hit ID, description, and full sequence lengths.
They can be accessed using id, description, and
seq_len, respectively.

Finally, there’s a table containing quick information about the HSPs this
hit contains. In each row, we’ve got the important HSP details listed: the
HSP index, its e-value, its bit score, its span (the alignment length
including gaps), its query coordinates, and its hit coordinates.

Now let’s contrast this with the BLAT search. Remember that in the BLAT search we
had one hit with 17 HSPs.

Here, we’ve got a similar level of detail as with the BLAST hit we saw earlier.
There are some differences worth explaining, though:

The e-value and bit score column values. As BLAT HSPs do not have e-values
and bit scores, the display defaults to ‘?’.

What about the span column? The span values is meant to display the
complete alignment length, which consists of all residues and any gaps that
may be present. The PSL format do not have this information readily available
and Bio.SearchIO does not attempt to try guess what it is, so we get a
‘?’ similar to the e-value and bit score columns.

In terms of Python objects, Hit behaves almost the same as Python lists,
but contain HSP objects exclusively. If you’re familiar with lists, you
should encounter no difficulties working with the Hit object.

Just like Python lists, Hit objects are iterable, and each iteration
returns one HSP object it contains:

You can use the slice notation on Hit objects, whether to retrieve single
HSP or multiple HSP objects. Like QueryResult, if you slice
for multiple HSP, a new Hit object will be returned containing
only the sliced HSP objects:

You can also sort the HSP inside a Hit, using the exact same
arguments like the sort method you saw in the QueryResult object.

Finally, there are also the filter and map methods you can use
on Hit objects. Unlike in the QueryResult object, Hit
objects only have one variant of filter (Hit.filter) and one
variant of map (Hit.map). Both of Hit.filter and
Hit.map work on the HSP objects a Hit has.

HSP (high-scoring pair) represents region(s) in the hit sequence that
contains significant alignment(s) to the query sequence. It contains the actual
match between your query sequence and a database entry. As this match is
determined by the sequence search tool’s algorithms, the HSP object
contains the bulk of the statistics computed by the search tool. This also makes
the distinction between HSP objects from different search tools more
apparent compared to the differences you’ve seen in QueryResult or
Hit objects.

Let’s see some examples from our BLAST and BLAT searches. We’ll look at the
BLAST HSP first:

Just like QueryResult and Hit, invoking print on an
HSP shows its general details:

There are the query and hit IDs and descriptions. We need these to
identify our HSP.

We’ve also got the matching range of the query and hit sequences. The
slice notation we’re using here is an indication that the range is displayed
using Python’s indexing style (zero-based, half open). The number inside the
parenthesis denotes the strand. In this case, both sequences have the plus
strand.

Some quick statistics are available: the e-value and bitscore.

There is information about the HSP fragments. Ignore this for now; it will
be explained later on.

And finally, we have the query and hit sequence alignment itself.

These details can be accessed on their own using the dot notation, just like in
QueryResult and Hit:

>>> blast_hsp.query_range
(0, 61)

>>> blast_hsp.evalue
4.91307e-23

They’re not the only attributes available, though. HSP objects come with
a default set of properties that makes it easy to probe their various
details. Here are some examples:

>>> blast_hsp.hit_start # start coordinate of the hit sequence
0
>>> blast_hsp.query_span # how many residues in the query sequence
61
>>> blast_hsp.aln_span # how long the alignment is
61

Check out the HSPdocumentation
for a full list of these predefined properties.

Furthermore, each sequence search tool usually computes its own statistics /
details for its HSP objects. For example, an XML BLAST search also
outputs the number of gaps and identical residues. These attributes can be
accessed like so:

These details are format-specific; they may not be present in other formats.
To see which details are available for a given sequence search tool, you
should check the format’s documentation in Bio.SearchIO. Alternatively,
you may also use .__dict__.keys() for a quick list of what’s available:

Some of the outputs you may have already guessed. We have the query and hit IDs
and descriptions and the sequence coordinates. Values for evalue and bitscore is
‘?’ as BLAT HSPs do not have these attributes. But The biggest difference here
is that you don’t see any sequence alignments displayed. If you look closer, PSL
formats themselves do not have any hit or query sequences, so
Bio.SearchIO won’t create any sequence or alignment objects. What happens
if you try to access HSP.query, HSP.hit, or HSP.aln?
You’ll get the default values for these attributes, which is None:

This does not affect other attributes, though. For example, you can still
access the length of the query or hit alignment. Despite not displaying any
attributes, the PSL format still have this information so Bio.SearchIO
can extract them:

So far so good? Things get more interesting when you look at another ‘variant’
of HSP present in our BLAT results. You might recall that in BLAT searches,
sometimes we get our results separated into ‘blocks’. These blocks are
essentially alignment fragments that may have some intervening sequence between
them.

Let’s take a look at a BLAT HSP that contains multiple blocks to see how
Bio.SearchIO deals with this:

What’s happening here? We still some essential details covered: the IDs and
descriptions, the coordinates, and the quick statistics are similar to what
you’ve seen before. But the fragments detail is all different. Instead of
showing ‘Fragments: 1’, we now have a table with two data rows.

This is how Bio.SearchIO deals with HSPs having multiple fragments. As
mentioned before, an HSP alignment may be separated by intervening sequences
into fragments. The intervening sequences are not part of the query-hit match,
so they should not be considered part of query nor hit sequence. However, they
do affect how we deal with sequence coordinates, so we can’t ignore them.

Take a look at the hit coordinate of the HSP above. In the Hit range: field,
we see that the coordinate is [54233104:54264463]. But looking at the
table rows, we see that not the entire region spanned by this coordinate matches
our query. Specifically, the intervening region spans from 54233122 to
54264420.

Why then, is the query coordinates seem to be contiguous, you ask? This is
perfectly fine. In this case it means that the query match is contiguous (no
intervening regions), while the hit match is not.

All these attributes are accessible from the HSP directly, by the way:

Most of these attributes are not readily available from the PSL file we have,
but Bio.SearchIO calculates them for you on the fly when you parse the
PSL file. All it needs are the start and end coordinates of each fragment.

What about the query, hit, and aln attributes? If the
HSP has multiple fragments, you won’t be able to use these attributes as they
only fetch single SeqRecord or MultipleSeqAlignment objects.
However, you can use their *_all counterparts: query_all,
hit_all, and aln_all. These properties will return a list containing
SeqRecord or MultipleSeqAlignment objects from each of the HSP
fragment. There are other attributes that behave similarly, i.e. they only work
for HSPs with one fragment. Check out the HSPdocumentation
for a full list.

Finally, to check whether you have multiple fragments or not, you can use the
is_fragmented property like so:

Before we move on, you should also know that we can use the slice notation on
HSP objects, just like QueryResult or Hit objects. When
you use this notation, you’ll get an HSPFragment object in return, the
last component of the object model.

HSPFragment represents a single, contiguous match between the query and
hit sequences. You could consider it the core of the object model and search
result, since it is the presence of these fragments that determine whether your
search have results or not.

In most cases, you don’t have to deal with HSPFragment objects directly
since not that many sequence search tools fragment their HSPs. When you do have
to deal with them, what you should remember is that HSPFragment objects
were written with to be as compact as possible. In most cases, they only contain
attributes directly related to sequences: strands, reading frames, alphabets,
coordinates, the sequences themselves, and their IDs and descriptions.

These attributes are readily shown when you invoke print on an
HSPFragment. Here’s an example, taken from our BLAST search:

Before we move on to the main functions, there is something you ought to know
about the standards Bio.SearchIO uses. If you’ve worked with multiple
sequence search tools, you might have had to deal with the many different ways
each program deals with things like sequence coordinates. It might not have been
a pleasant experience as these search tools usually have their own standards.
For example, one tools might use one-based coordinates, while the other uses
zero-based coordinates. Or, one program might reverse the start and end
coordinates if the strand is minus, while others don’t. In short, these often
creates unnecessary mess must be dealt with.

We realize this problem ourselves and we intend to address it in
Bio.SearchIO. After all, one of the goals of Bio.SearchIO is to
create a common, easy to use interface to deal with various search output files.
This means creating standards that extend beyond the object model you just saw.

Now, you might complain, "Not another standard!". Well, eventually we have to
choose one convention or the other, so this is necessary. Plus, we’re not
creating something entirely new here; just adopting a standard we think is best
for a Python programmer (it is Biopython, after all).

There are three implicit standards that you can expect when working with
Bio.SearchIO:

The first one pertains to sequence coordinates. In Bio.SearchIO,
all sequence coordinates follows Python’s coordinate style: zero-based and
half open. For example, if in a BLAST XML output file the start and end
coordinates of an HSP are 10 and 28, they would become 9 and 28 in
Bio.SearchIO. The start coordinate becomes 9 because Python indices
start from zero, while the end coordinate remains 28 as Python slices omit
the last item in an interval.

The second is on sequence coordinate orders. In Bio.SearchIO, start
coordinates are always less than or equal to end coordinates. This isn’t
always the case with all sequence search tools, as some of them have larger
start coordinates when the sequence strand is minus.

The last one is on strand and reading frame values. For strands, there are
only four valid choices: 1 (plus strand), -1 (minus strand),
0 (protein sequences), and None (no strand). For reading
frames, the valid choices are integers from -3 to 3 and
None.

Note that these standards only exist in Bio.SearchIO objects. If you
write Bio.SearchIO objects into an output format, Bio.SearchIO
will use the format’s standard for the output. It does not force its standard
over to your output file.

There are two functions you can use for reading search output files into
Bio.SearchIO objects: read and parse. They’re essentially
similar to read and parse functions in other submodules like
Bio.SeqIO or Bio.AlignIO. In both cases, you need to supply the
search output file name and the file format name, both as Python strings. You
can check the documentation for a list of format names Bio.SearchIO
recognizes.

Bio.SearchIO.read is used for reading search output files with only one
query and returns a QueryResult object. You’ve seen read used in
our previous examples. What you haven’t seen is that read may also accept
additional keyword arguments, depending on the file format.

Here are some examples. In the first one, we use read just like
previously to read a BLAST tabular output file. In the second one, we use a
keyword argument to modify so it parses the BLAST tabular variant with comments
in it:

These keyword arguments differs among file formats. Check the format
documentation to see if it has keyword arguments that modifies its parser’s
behavior.

As for the Bio.SearchIO.parse, it is used for reading search output
files with any number of queries. The function returns a generator object that
yields a QueryResult object in each iteration. Like
Bio.SearchIO.read, it also accepts format-specific keyword arguments:

Sometimes, you’re handed a search output file containing hundreds or thousands
of queries that you need to parse. You can of course use
Bio.SearchIO.parse for this file, but that would be grossly inefficient
if you need to access only a few of the queries. This is because parse
will parse all queries it sees before it fetches your query of interest.

In this case, the ideal choice would be to index the file using
Bio.SearchIO.index or Bio.SearchIO.index_db. If the names sound
familiar, it’s because you’ve seen them before in Section 5.4.2.
These functions also behave similarly to their Bio.SeqIO counterparts,
with the addition of format-specific keyword arguments.

Here are some examples. You can use index with just the filename and
format name:

It is occasionally useful to be able to manipulate search results from an output
file and write it again to a new file. Bio.SearchIO provides a
write function that lets you do exactly this. It takes as its arguments
an iterable returning QueryResult objects, the output filename to write
to, the format name to write to, and optionally some format-specific keyword
arguments. It returns a four-item tuple, which denotes the number or
QueryResult, Hit, HSP, and HSPFragment objects that
were written.

You should note different file formats require different attributes of the
QueryResult, Hit, HSP and HSPFragment objects. If
these attributes are not present, writing won’t work. In other words, you can’t
always write to the output format that you want. For example, if you read a
BLAST XML file, you wouldn’t be able to write the results to a PSL file as PSL
files require attributes not calculated by BLAST (e.g. the number of repeat
matches). You can always set these attributes manually, if you really want to
write to PSL, though.

Like read, parse, index, and index_db, write
also accepts format-specific keyword arguments. Check out the documentation for
a complete list of formats Bio.SearchIO can write to and their arguments.

Finally, Bio.SearchIO also provides a convert function, which is
simply a shortcut for Bio.SearchIO.parse and Bio.SearchIO.write.
Using the convert function, our example above would be:

As convert uses write, it is only limited to format conversions
that have all the required attributes. Here, the BLAST XML file provides all the
default values a BLAST tabular file requires, so it works just fine. However,
other format conversions are less likely to work since you need to manually
assign the required attributes first.

Entrez (http://www.ncbi.nlm.nih.gov/Entrez) is a data retrieval system that provides users access to NCBI’s databases such as PubMed, GenBank, GEO, and many others. You can access Entrez from a web browser to manually enter queries, or you can use Biopython’s Bio.Entrez module for programmatic access to Entrez. The latter allows you for example to search PubMed or download GenBank records from within a Python script.

The Bio.Entrez module makes use of the Entrez Programming Utilities (also known as EUtils), consisting of eight tools that are described in detail on NCBI’s page at http://www.ncbi.nlm.nih.gov/entrez/utils/.
Each of these tools corresponds to one Python function in the Bio.Entrez module, as described in the sections below. This module makes sure that the correct URL is used for the queries, and that not more than one request is made every three seconds, as required by NCBI.

The output returned by the Entrez Programming Utilities is typically in XML format. To parse such output, you have several options:

Read the XML output as raw text, and parse it by string searching and manipulation.

For the DOM and SAX parsers, see the Python documentation. The parser in Bio.Entrez is discussed below.

NCBI uses DTD (Document Type Definition) files to describe the structure of the information contained in XML files. Most of the DTD files used by NCBI are included in the Biopython distribution. The Bio.Entrez parser makes use of the DTD files when parsing an XML file returned by NCBI Entrez.

Occasionally, you may find that the DTD file associated with a specific XML file is missing in the Biopython distribution. In particular, this may happen when NCBI updates its DTD files. If this happens, Entrez.read will show a warning message with the name and URL of the missing DTD file. The parser will proceed to access the missing DTD file through the internet, allowing the parsing of the XML file to continue. However, the parser is much faster if the DTD file is available locally. For this purpose, please download the DTD file from the URL in the warning message and place it in the directory ...site-packages/Bio/Entrez/DTDs, containing the other DTD files. If you don’t have write access to this directory, you can also place the DTD file in ~/.biopython/Bio/Entrez/DTDs, where ~ represents your home directory. Since this directory is read before the directory ...site-packages/Bio/Entrez/DTDs, you can also put newer versions of DTD files there if the ones in ...site-packages/Bio/Entrez/DTDs become outdated. Alternatively, if you installed Biopython from source, you can add the DTD file to the source code’s Bio/Entrez/DTDs directory, and reinstall Biopython. This will install the new DTD file in the correct location together with the other DTD files.

The Entrez Programming Utilities can also generate output in other formats, such as the Fasta or GenBank file formats for sequence databases, or the MedLine format for the literature database, discussed in Section 9.12.

Before using Biopython to access the NCBI’s online resources (via Bio.Entrez or some of the other modules), please read the
NCBI’s Entrez User Requirements.
If the NCBI finds you are abusing their systems, they can and will ban your access!

To paraphrase:

For any series of more than 100 requests, do this at weekends or outside USA peak times. This is up to you to obey.

Make no more than three requests every seconds (relaxed from at most one request every three seconds in early 2009). This is automatically enforced by Biopython.

Use the optional email parameter so the NCBI can contact you if there is a problem. You can either explicitly set this as a parameter with each call to Entrez (e.g. include email="A.N.Other@example.com" in the argument list), or you can set a global email address:

>>> from Bio import Entrez
>>> Entrez.email = "A.N.Other@example.com"

Bio.Entrez will then use this email address with each call to Entrez. The example.com address is a reserved domain name specifically for documentation (RFC 2606). Please DO NOT use a random email – it’s better not to give an email at all. The email parameter will be mandatory from June 1, 2010. In case of excessive usage, NCBI will attempt to contact a user at the e-mail address provided prior to blocking access to the E-utilities.

If you are using Biopython within some larger software suite, use the tool parameter to specify this. You can either explicitly set the tool name as a parameter with each call to Entrez (e.g. include tool="MyLocalScript" in the argument list), or you can set a global tool name:

>>> from Bio import Entrez
>>> Entrez.tool = "MyLocalScript"

The tool parameter will default to Biopython.

For large queries, the NCBI also recommend using their session history feature (the WebEnv session cookie string, see Section 9.15). This is only slightly more complicated.

In conclusion, be sensible with your usage levels. If you plan to download lots of data, consider other options. For example, if you want easy access to all the human genes, consider fetching each chromosome by FTP as a GenBank file, and importing these into your own BioSQL database (see Section 18.5).

EInfo provides field index term counts, last update, and available links for each of NCBI’s databases. In addition, you can use EInfo to obtain a list of all database names accessible through the Entrez utilities:

Since this is a fairly simple XML file, we could extract the information it contains simply by string searching. Using Bio.Entrez’s parser instead, we can directly parse this XML file into a Python object:

That’s a long list, but indirectly this tells you that for the PubMed
database, you can do things like Jones[AUTH] to search the
author field, or Sanger[AFFL] to restrict to authors at the
Sanger Centre. This can be very handy - especially if you are not so
familiar with a particular database.

In this output, you see seven PubMed IDs (including 19304878 which is the PMID for the Biopython application note), which can be retrieved by EFetch (see section 9.6).

You can also use ESearch to search GenBank. Here we’ll do a quick
search for the matK gene in Cypripedioideae orchids
(see Section 9.2 about EInfo for one way to
find out which fields you can search in each Entrez database):

Each of the IDs (126789333, 37222967, 37222966, …) is a GenBank identifier.
See section 9.6 for information on how to actually download these GenBank records.

Note that instead of a species name like Cypripedioideae[Orgn], you can restrict the search using an NCBI taxon identifier, here this would be txid158330[Orgn]. This isn’t currently documented on the ESearch help page - the NCBI explained this in reply to an email query. You can often deduce the search term formatting by playing with the Entrez web interface. For example, including complete[prop] in a genome search restricts to just completed genomes.

EPost uploads a list of UIs for use in subsequent search strategies; see the
EPost help page for more information. It is available from Biopython through
the Bio.Entrez.epost() function.

To give an example of when this is useful, suppose you have a long list of IDs
you want to download using EFetch (maybe sequences, maybe citations –
anything). When you make a request with EFetch your list of IDs, the database
etc, are all turned into a long URL sent to the server. If your list of IDs is
long, this URL gets long, and long URLs can break (e.g. some proxies don’t
cope well).

Instead, you can break this up into two steps, first uploading the list of IDs
using EPost (this uses an “HTML post” internally, rather than an “HTML get”,
getting round the long URL problem). With the history support, you can then
refer to this long list of IDs, and download the associated data with EFetch.

Let’s look at a simple example to see how EPost works – uploading some PubMed identifiers:

ESummary retrieves document summaries from a list of primary IDs (see the ESummary help page for more information). In Biopython, ESummary is available as Bio.Entrez.esummary(). Using the search result above, we can for example find out more about the journal with ID 30367:

EFetch is what you use when you want to retrieve a full record from Entrez.
This covers several possible databases, as described on the main EFetch Help page.

For most of their databases, the NCBI support several different file formats. Requesting a specific file format from Entrez using Bio.Entrez.efetch() requires specifying the rettype and/or retmode optional arguments. The different combinations are described for each database type on the pages linked to on NCBI efetch webpage (e.g. literature, sequences and taxonomy).

One common usage is downloading sequences in the FASTA or GenBank/GenPept plain text formats (which can then be parsed with Bio.SeqIO, see Sections 5.3.1 and 9.6). From the Cypripedioideae example above, we can download GenBank record 186972394 using Bio.Entrez.efetch:

The arguments rettype="gb" and retmode="text" let us download this record in the GenBank format.

Note that until Easter 2009, the Entrez EFetch API let you use “genbank” as the
return type, however the NCBI now insist on using the official return types of
“gb” or “gbwithparts” (or “gp” for proteins) as described on online.
Also not that until Feb 2012, the Entrez EFetch API would default to returning
plain text files, but now defaults to XML.

Alternatively, you could for example use rettype="fasta" to get the Fasta-format; see the EFetch Sequences Help page for other options. Remember – the available formats depend on which database you are downloading from - see the main EFetch Help page.

If you fetch the record in one of the formats accepted by Bio.SeqIO (see Chapter 5), you could directly parse it into a SeqRecord:

Note that a more typical use would be to save the sequence data to a local file, and then parse it with Bio.SeqIO. This can save you having to re-download the same file repeatedly while working on your script, and places less load on the NCBI’s servers. For example:

ELink, available from Biopython as Bio.Entrez.elink(), can be used to find related items in the NCBI Entrez databases. For example, you can us this to find nucleotide entries for an entry in the gene database,
and other cool stuff.

Let’s use ELink to find articles related to the Biopython application note published in Bioinformatics in 2009. The PubMed ID of this article is 19304878:

The record variable consists of a Python list, one for each database in which we searched. Since we specified only one PubMed ID to search for, record contains only one item. This item is a dictionary containing information about our search term, as well as all the related items that were found:

>>> record[0]["DbFrom"]
'pubmed'
>>> record[0]["IdList"]
['19304878']

The "LinkSetDb" key contains the search results, stored as a list consisting of one item for each target database. In our search results, we only find hits in the PubMed database (although sub-divided into categories):

EGQuery provides counts for a search term in each of the Entrez databases (i.e. a global query). This is particularly useful to find out how many items your search terms would find in each database without actually performing lots of separate searches with ESearch (see the example in 9.14.2 below).

In this example, we use Bio.Entrez.egquery() to obtain the counts for “Biopython”:

The Entrez.read function reads the entire XML file returned by Entrez into a single Python object, which is kept in memory. To parse Entrez XML files too large to fit in memory, you can use the function Entrez.parse. This is a generator function that reads records in the XML file one by one. This function is only useful if the XML file reflects a Python list object (in other words, if Entrez.read on a computer with infinite memory resources would return a Python list).

For example, you can download the entire Entrez Gene database for a given organism as a file from NCBI’s ftp site. These files can be very large. As an example, on September 4, 2009, the file Homo_sapiens.ags.gz, containing the Entrez Gene database for human, had a size of 116576 kB. This file, which is in the ASN format, can be converted into an XML file using NCBI’s gene2xml program (see NCBI’s ftp site for more information):

gene2xml -b T -i Homo_sapiens.ags -o Homo_sapiens.xml

The resulting XML file has a size of 6.1 GB. Attempting Entrez.read on this file will result in a MemoryError on many computers.

The XML file Homo_sapiens.xml consists of a list of Entrez gene records, each corresponding to one Entrez gene in human. Entrez.parse retrieves these gene records one by one. You can then print out or store the relevant information in each record by iterating over the records. For example, this script iterates over the Entrez gene records and prints out the gene numbers and names for all current genes:

In this file, for some reason the tag <DocsumList> (and several others) are not listed in the DTD file eInfo_020511.dtd, which is specified on the second line as the DTD for this XML file. By default, the parser will stop and raise a ValidationError if it cannot find some tag in the DTD:

>>> from Bio import Entrez
>>> handle = open("einfo3.xml")
>>> record = Entrez.read(handle)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/usr/local/lib/python2.7/site-packages/Bio/Entrez/__init__.py", line 257, in read
record = handler.read(handle)
File "/usr/local/lib/python2.7/site-packages/Bio/Entrez/Parser.py", line 154, in read
self.parser.ParseFile(handle)
File "/usr/local/lib/python2.7/site-packages/Bio/Entrez/Parser.py", line 246, in startElementHandler
raise ValidationError(name)
Bio.Entrez.Parser.ValidationError: Failed to find tag 'DocsumList' in the DTD. To skip all tags that are not represented in the DTD, please call Bio.Entrez.read or Bio.Entrez.parse with validate=False.

Optionally, you can instruct the parser to skip such tags instead of raising a ValidationError. This is done by calling Entrez.read or Entrez.parse with the argument validate equal to False:

The Bio.Entrez.read() function can parse most (if not all) XML output returned by Entrez. Entrez typically allows you to retrieve records in other formats, which may have some advantages compared to the XML format in terms of readability (or download size).

To request a specific file format from Entrez using Bio.Entrez.efetch() requires specifying the rettype and/or retmode optional arguments. The different combinations are described for each database type on the NCBI efetch webpage.

One obvious case is you may prefer to download sequences in the FASTA or GenBank/GenPept plain text formats (which can then be parsed with Bio.SeqIO, see Sections 5.3.1 and 9.6). For the literature databases, Biopython contains a parser for the MEDLINE format used in PubMed.

You can find the Medline parser in Bio.Medline. Suppose we want to parse the file pubmed_result1.txt, containing one Medline record. You can find this file in Biopython’s Tests\Medline directory. The file looks like this:

>>> record["AB"]
'Bioinformatics research is often difficult to do with commercial software.
The Open Source BioPerl, BioPython and Biojava projects provide toolkits with
multiple functionality that make it easier to create customised pipelines or
analysis. This review briefly compares the quirks of the underlying languages
and the functionality, documentation, utility and relative advantages of the
Bio counterparts, particularly from the point of view of the beginning
biologist programmer.'

The key names used in a Medline record can be rather obscure; use

>>> help(record)

for a brief summary.

To parse a file containing multiple Medline records, you can use the parse function instead:

>>> from Bio import Medline
>>> with open("pubmed_result2.txt") as handle:
... for record in Medline.parse(handle):
... print(record["TI"])
...
A high level interface to SCOP and ASTRAL implemented in python.
GenomeDiagram: a python package for the visualization of large-scale genomic data.
Open source clustering software.
PDB file parser and structure class implemented in Python.

Instead of parsing Medline records stored in files, you can also parse Medline records downloaded by Bio.Entrez.efetch. For example, let’s look at all Medline records in PubMed related to Biopython:

Note that in both of these examples, for simplicity we have naively combined ESearch and EFetch.
In this situation, the NCBI would expect you to use their history feature,
as illustrated in Section 9.15.

From the Entrez website, UID “200000016” is GDS16 while the other hit
“100000028” is for the associated platform, GPL28. Unfortunately, at the
time of writing the NCBI don’t seem to support downloading GEO files using
Entrez (not as XML, nor in the Simple Omnibus Format in Text (SOFT)
format).

UniGene is an NCBI database of the transcriptome, with each UniGene record showing the set of transcripts that are associated with a particular gene in a specific organism. A typical UniGene record looks like this:

This particular record shows the set of transcripts (shown in the SEQUENCE lines) that originate from the human gene NAT2, encoding en N-acetyltransferase. The PROTSIM lines show proteins with significant similarity to NAT2, whereas the STS lines show the corresponding sequence-tagged sites in the genome.

Normally you won’t have to worry about using a proxy, but if this is an issue
on your network here is how to deal with it. Internally, Bio.Entrez
uses the standard Python library urllib for accessing the NCBI servers.
This will check an environment variable called http_proxy to configure
any simple proxy automatically. Unfortunately this module does not support
the use of proxies which require authentication.

You may choose to set the http_proxy environment variable once (how you
do this will depend on your operating system). Alternatively you can set this
within Python at the start of your script, for example:

If you are in the medical field or interested in human issues (and many times even if you are not!), PubMed (http://www.ncbi.nlm.nih.gov/PubMed/) is an excellent source of all kinds of goodies. So like other things, we’d like to be able to grab information from it and use it in Python scripts.

In this example, we will query PubMed for all articles having to do with orchids (see section 2.3 for our motivation). We first check how many of such articles there are:

Now that we’ve got them, we obviously want to get the corresponding Medline records and extract the information from them. Here, we’ll download the Medline records in the Medline flat-file format, and use the Bio.Medline module to parse them:

Especially interesting to note is the list of authors, which is returned as a standard Python list. This makes it easy to manipulate and search using standard Python tools. For instance, we could loop through a whole bunch of entries searching for a particular author with code like the following:

Here we’ll show a simple example of performing a remote Entrez query. In section 2.3 of the parsing examples, we talked about using NCBI’s Entrez website to search the NCBI nucleotide databases for info on Cypripedioideae, our friends the lady slipper orchids. Now, we’ll look at how to automate that process using a Python script. In this example, we’ll just show how to connect, get the results, and parse them, with the Entrez module doing all of the work.

First, we use EGQuery to find out the number of results we will get before actually downloading them. EGQuery will tell us how many search results were found in each of the databases, but for this example we are only interested in nucleotides:

So, we expect to find 814 Entrez Nucleotide records (this is the number I obtained in 2008; it is likely to increase in the future). If you find some ridiculously high number of hits, you may want to reconsider if you really want to download all of them, which is our next step:

We can download these records using efetch.
While you could download these records one by one, to reduce the load on NCBI’s servers, it is better to fetch a bunch of records at the same time, shown below.
However, in this situation you should ideally be using the history feature described later in Section 9.15.

The GenBank record format is a very popular method of holding information about sequences, sequence features, and other associated sequence information. The format is a good way to get information from the NCBI databases at http://www.ncbi.nlm.nih.gov/.

In this example we’ll show how to query the NCBI databases,to retrieve the records from the query, and then parse them using Bio.SeqIO - something touched on in Section 5.3.1.
For simplicity, this example does not take advantage of the WebEnv history feature – see Section 9.15 for this.

First, we want to make a query and find out the ids of the records to retrieve. Here we’ll do a quick search for one of our favorite organisms, Opuntia (prickly-pear cacti). We can do quick search and get back the GIs (GenBank identifiers) for all of the corresponding records. First we check how many records there are:

Now we use these GIs to download the GenBank records - note that with older versions of Biopython you had to supply a comma separated list of GI numbers to Entrez, as of Biopython 1.59 you can pass a list and this is converted for you:

In this case, we are just getting the raw records. To get the records in a more Python-friendly form, we can use Bio.SeqIO to parse the GenBank data into SeqRecord objects, including SeqFeature objects (see Chapter 5):

Using these automated query retrieval functionality is a big plus over doing things by hand. Although the module should obey the NCBI’s max three queries per second rule, the NCBI have other recommendations like avoiding peak hours. See Section 9.1.
In particular, please note that for simplicity, this example does not use the WebEnv history feature. You should use this for any non-trivial search and download work, see Section 9.15.

Finally, if plan to repeat your analysis, rather than downloading the files from the NCBI and parsing them immediately (as shown in this example), you should just download the records once and save them to your hard disk, and then parse the local file.

Staying with a plant example, let’s now find the lineage of the Cypripedioideae orchid family. First, we search the Taxonomy database for Cypripedioideae, which yields exactly one NCBI taxonomy identifier:

Often you will want to make a series of linked queries. Most typically,
running a search, perhaps refining the search, and then retrieving detailed
search results. You can do this by making a series of separate calls
to Entrez. However, the NCBI prefer you to take advantage of their history
support - for example combining ESearch and EFetch.

Another typical use of the history support would be to combine EPost and
EFetch. You use EPost to upload a list of identifiers, which starts a new
history session. You then download the records with EFetch by referring
to the session (instead of the identifiers).

Suppose we want to search and download all the Opuntia rpl16
nucleotide sequences, and store them in a FASTA file. As shown in
Section 9.14.3, we can naively combine
Bio.Entrez.esearch() to get a list of GI numbers, and then call
Bio.Entrez.efetch() to download them all.

However, the approved approach is to run the search with the history
feature. Then, we can fetch the results by reference to the search
results - which the NCBI can anticipate and cache.

To do this, call Bio.Entrez.esearch() as normal, but with the
additional argument of usehistory="y",

Having stored these values in variables session_cookie and query_key we can use them as parameters to Bio.Entrez.efetch() instead of giving the GI numbers as identifiers.

While for small searches you might be OK downloading everything at once, it is better to download in batches. You use the retstart and retmax parameters to specify which range of search results you want returned (starting entry using zero-based counting, and maximum number of results to return). For example,

At the time of writing, this gave 28 matches - but because this is a date dependent search, this will of course vary. As described in Section 9.12.1 above, you can then use Bio.Medline to parse the saved records.

Back in Section 9.7 we mentioned ELink can be used to search for citations of a given paper.
Unfortunately this only covers journals indexed for PubMed Central
(doing it for all the journals in PubMed would mean a lot more work for the NIH).
Let’s try this for the Biopython PDB parser paper, PubMed ID 14630660:

Great - eleven articles. But why hasn’t the Biopython application note been
found (PubMed ID 19304878)? Well, as you might have guessed from the variable
names, there are not actually PubMed IDs, but PubMed Central IDs. Our
application note is the third citing paper in that list, PMCID 2682512.

So, what if (like me) you’d rather get back a list of PubMed IDs? Well we
can call ELink again to translate them. This becomes a two step process,
so by now you should expect to use the history feature to accomplish it
(Section 9.15).

But first, taking the more straightforward approach of making a second
(separate) call to ELink:

Swiss-Prot (http://www.expasy.org/sprot) is a hand-curated database of protein sequences. Biopython can parse the “plain text” Swiss-Prot file format, which is still used for the UniProt Knowledgebase which combined Swiss-Prot, TrEMBL and PIR-PSD. We do not (yet) support the UniProtKB XML file format.

In Section 5.3.2, we described how to extract the sequence of a Swiss-Prot record as a SeqRecord object. Alternatively, you can store the Swiss-Prot record in a Bio.SwissProt.Record object, which in fact stores the complete information contained in the Swiss-Prot record. In this Section, we describe how to extract Bio.SwissProt.Record objects from a Swiss-Prot file.

To parse a Swiss-Prot record, we first get a handle to a Swiss-Prot record. There are several ways to do so, depending on where and how the Swiss-Prot record is stored:

The key point is that for the parser, it doesn’t matter how the handle was created, as long as it points to data in the Swiss-Prot format.

We can use Bio.SeqIO as described in Section 5.3.2 to get file format agnostic SeqRecord objects. Alternatively, we can use Bio.SwissProt get Bio.SwissProt.Record objects, which are a much closer match to the underlying file format.

To read one Swiss-Prot record from the handle, we use the function read():

>>> from Bio import SwissProt
>>> record = SwissProt.read(handle)

This function should be used if the handle points to exactly one Swiss-Prot record. It raises a ValueError if no Swiss-Prot record was found, and also if more than one record was found.

To parse a file that contains more than one Swiss-Prot record, we use the parse function instead. This function allows us to iterate over the records in the file.

For example, let’s parse the full Swiss-Prot database and collect all the descriptions.
You can download this from the ExPAYs FTP site as a single gzipped-file uniprot_sprot.dat.gz (about 300MB). This is a compressed file containing a single file, uniprot_sprot.dat (over 1.5GB).

As described at the start of this section, you can use the Python library gzip to open and uncompress a .gz file, like this:

>>> import gzip
>>> handle = gzip.open("uniprot_sprot.dat.gz")

However, uncompressing a large file takes time, and each time you open the file for reading in this way, it has to be decompressed on the fly. So, if you can spare the disk space you’ll save time in the long run if you first decompress the file to disk, to get the uniprot_sprot.dat file inside. Then you can open the file for reading as usual:

>>> handle = open("uniprot_sprot.dat")

As of June 2009, the full Swiss-Prot database downloaded from ExPASy contained 468851 Swiss-Prot records. One concise way to build up a list of the record descriptions is with a list comprehension:

Prosite is a database containing protein domains, protein families, functional sites, as well as the patterns and profiles to recognize them. Prosite was developed in parallel with Swiss-Prot. In Biopython, a Prosite record is represented by the Bio.ExPASy.Prosite.Record class, whose members correspond to the different fields in a Prosite record.

In general, a Prosite file can contain more than one Prosite records. For example, the full set of Prosite records, which can be downloaded as a single file (prosite.dat) from the ExPASy FTP site, contains 2073 records (version 20.24 released on 4 December 2007). To parse such a file, we again make use of an iterator:

In the Prosite example above, the record.pdoc accession numbers 'PDOC00001', 'PDOC00004', 'PDOC00005' and so on refer to Prosite documentation. The Prosite documentation records are available from ExPASy as individual files, and as one file (prosite.doc) containing all Prosite documentation records.

We use the parser in Bio.ExPASy.Prodoc to parse Prosite documentation records. For example, to create a list of all accession numbers of Prosite documentation record, you can use

In this example, the first line shows the EC (Enzyme Commission) number of lipoprotein lipase (second line). Alternative names of lipoprotein lipase are "clearing factor lipase", "diacylglycerol lipase", and "diglyceride lipase" (lines 3 through 5). The line starting with "CA" shows the catalytic activity of this enzyme. Comment lines start with "CC". The "PR" line shows references to the Prosite Documentation records, and the "DR" lines show references to Swiss-Prot records. Not of these entries are necessarily present in an Enzyme record.

In Biopython, an Enzyme record is represented by the Bio.ExPASy.Enzyme.Record class. This record derives from a Python dictionary and has keys corresponding to the two-letter codes used in Enzyme files. To read an Enzyme file containing one Enzyme record, use the read function in Bio.ExPASy.Enzyme:

The read function raises a ValueError if no Enzyme record is found, and also if more than one Enzyme record is found.

The full set of Enzyme records can be downloaded as a single file (enzyme.dat) from the ExPASy FTP site, containing 4877 records (release of 3 March 2009). To parse such a file containing multiple Enzyme records, use the parse function in Bio.ExPASy.Enzyme to obtain an iterator:

Let’s say we are looking at chalcone synthases for Orchids (see section 2.3 for some justification for looking for interesting things about orchids). Chalcone synthase is involved in flavanoid biosynthesis in plants, and flavanoids make lots of cool things like pigment colors and UV protectants.

If you do a search on Swiss-Prot, you can find three orchid proteins for Chalcone Synthase, id numbers O23729, O23730, O23731. Now, let’s write a script which grabs these, and parses out some interesting information.

First, we grab the records, using the get_sprot_raw() function of Bio.ExPASy. This function is very nice since you can feed it an id and get back a handle to a raw text record (no html to mess with!). We can the use Bio.SwissProt.read to pull out the Swiss-Prot record, or Bio.SeqIO.read to get a SeqRecord. The following code accomplishes what I just wrote:

If the accession number you provided to ExPASy.get_sprot_raw does not exist, then SwissProt.read(handle) will raise a ValueError. You can catch ValueException exceptions to detect invalid accession numbers:

Now, you may remark that I knew the records’ accession numbers
beforehand. Indeed, get_sprot_raw() needs either the entry name
or an accession number. When you don’t have them handy, you can use
one of the sprot_search_de() or sprot_search_ful()
functions.

Prosite and Prosite documentation records can be retrieved either in HTML format, or in raw format. To parse Prosite and Prosite documentation records with Biopython, you should retrieve the records in raw format. For other purposes, however, you may be interested in these records in HTML format.

To retrieve a Prosite or Prosite documentation record in raw format, use get_prosite_raw(). For example, to download a Prosite record and print it out in raw text format, use

For non-existing accession numbers, ExPASy.get_prosite_raw returns a handle to an emptry string. When faced with an empty string, Prosite.read and Prodoc.read will raise a ValueError. You can catch these exceptions to detect invalid accession numbers.

The functions get_prosite_entry() and get_prodoc_entry() are used to download Prosite and Prosite documentation records in HTML format. To create a web page showing one Prosite record, you can use

You can use Biopython’s Bio.ExPASy.ScanProsite module to scan the Prosite database from Python. This module both helps you to access ScanProsite programmatically, and to parse the results returned by ScanProsite. To scan for Prosite patterns in the following protein sequence:

A Bio.ExPASy.ScanProsite.Record object is derived from a list, with each element in the list storing one ScanProsite hit. This object also stores the number of hits, as well as the number of search sequences, as returned by ScanProsite. This ScanProsite search resulted in six hits:

Bio.PopGen is a Biopython module supporting population genetics,
available in Biopython 1.44 onwards.

The medium term objective for the module is to support widely used data
formats, applications and databases. This module is currently under intense
development and support for new features should appear at a rather fast pace.
Unfortunately this might also entail some instability on the API, especially
if you are using a development version. APIs that are made available on
our official public releases should be much more stable.

GenePop (http://genepop.curtin.edu.au/) is a popular population
genetics software package supporting Hardy-Weinberg tests, linkage
desiquilibrium, population diferentiation, basic statistics, Fst and
migration estimates, among others. GenePop does not supply sequence
based statistics as it doesn’t handle sequence data.
The GenePop file format is supported by a wide range of other population
genetic software applications, thus making it a relevant format in the
population genetics field.

Bio.PopGen provides a parser and generator of GenePop file format.
Utilities to manipulate the content of a record are also provided.
Here is an example on how to read a GenePop file (you can find
example GenePop data files in the Test/PopGen directory of Biopython):

This will read a file called example.gen and parse it. If you
do print rec, the record will be output again, in GenePop format.

The most important information in rec will be the loci names and
population information (but there is more – use help(GenePop.Record)
to check the API documentation). Loci names can be found on rec.loci_list.
Population information can be found on rec.populations.
Populations is a list with one element per population. Each element is itself
a list of individuals, each individual is a pair composed by individual
name and a list of alleles (2 per marker), here is an example for
rec.populations:

So we have two populations, the first with two individuals, the
second with only one. The first individual of the first
population is called Ind1, allelic information for each of
the 3 loci follows. Please note that for any locus, information
might be missing (see as an example, Ind2 above).

A few utility functions to manipulate GenePop records are made
available, here is an example:

from Bio.PopGen import GenePop
#Imagine that you have loaded rec, as per the code snippet above...
rec.remove_population(pos)
#Removes a population from a record, pos is the population position in
# rec.populations, remember that it starts on position 0.
# rec is altered.
rec.remove_locus_by_position(pos)
#Removes a locus by its position, pos is the locus position in
# rec.loci_list, remember that it starts on position 0.
# rec is altered.
rec.remove_locus_by_name(name)
#Removes a locus by its name, name is the locus name as in
# rec.loci_list. If the name doesn't exist the function fails
# silently.
# rec is altered.
rec_loci = rec.split_in_loci()
#Splits a record in loci, that is, for each loci, it creates a new
# record, with a single loci and all populations.
# The result is returned in a dictionary, being each key the locus name.
# The value is the GenePop record.
# rec is not altered.
rec_pops = rec.split_in_pops(pop_names)
#Splits a record in populations, that is, for each population, it creates
# a new record, with a single population and all loci.
# The result is returned in a dictionary, being each key
# the population name. As population names are not available in GenePop,
# they are passed in array (pop_names).
# The value of each dictionary entry is the GenePop record.
# rec is not altered.

GenePop does not support population names, a limitation which can be
cumbersome at times. Functionality to enable population names is currently
being planned for Biopython. These extensions won’t break compatibility in
any way with the standard format. In the medium term, we would also like to
support the GenePop web service.

A coalescent simulation is a backward model of population genetics with relation to
time. A simulation of ancestry is done until the Most Recent Common Ancestor (MRCA) is found.
This ancestry relationship starting on the MRCA and ending on the current generation
sample is sometimes called a genealogy. Simple cases assume a population of constant
size in time, haploidy, no population structure, and simulate the alleles of a single
locus under no selection pressure.

Coalescent theory is used in many fields like selection detection, estimation of
demographic parameters of real populations or disease gene mapping.

The strategy followed in the Biopython implementation of the coalescent was not
to create a new, built-in, simulator from scratch but to use an existing one,
Fastsimcoal2 (http://cmpg.unibe.ch/software/fastsimcoal2/). Fastsimcoal2 allows for,
among others, population structure, multiple demographic events, simulation
of multiple types of loci (SNPs, sequences, STRs/microsatellites and RFLPs)
with recombination, diploidy multiple chromosomes or ascertainment bias. Notably
Fastsimcoal2 doesn’t support any selection model. We recommend reading
Fastsimcoal2’s
documentation, available in the link above.

The input for Fastsimcoal2 is a file specifying the desired demography and genome,
the output is a set of files (typically around 1000) with the simulated genomes
of a sample of individuals per subpopulation. This set of files can be used
in many ways, like to compute confidence intervals where which certain
statistics (e.g., Fst or Tajima D) are expected to lie. Real population
genetics datasets statistics can then be compared to those confidence intervals.

Biopython coalescent code allows to create demographic scenarios and genomes and
to run Fastsimcoal2.

Creating a scenario involves both creating a demography and a chromosome structure.
In many cases (e.g. when doing Approximate Bayesian Computations – ABC) it is
important to test many parameter variations (e.g. vary the effective population size,
Ne, between 10, 50, 500 and 1000 individuals). The code provided allows for
the simulation of scenarios with different demographic parameters very easily.

Below we see how we can create scenarios and then how simulate them.

11.2.1.1 Demography

A few predefined demographies are built-in, all have two shared parameters: sample size
(called sample_size on the template, see below for its use) per deme and deme size, i.e.
subpopulation size (pop_size). All demographies are available as templates where all
parameters can be varied, each template has a system name. The prefedined
demographies/templates are:

As seen on figure 11.2.1.1. The parameters
are current population size (pop_size on template ne3 on figure), time of expansion,
given as the generation in the past when it occurred (expand_gen),
effective population size during bottleneck (ne2), time of contraction
(contract_gen) and original size in the remote past (ne3). Template name: bottle.

Island model

The typical island model. The total number of demes is specified
by total_demes and the migration rate by mig. Template name island.

Stepping stone model - 1 dimension

The stepping stone model in 1 dimension,
extremes disconnected. The total number of demes is total_demes, migration rate
is mig. Template name is ssm_1d.

Stepping stone model - 2 dimensions

The stepping stone model in 2 dimensions,
extremes disconnected. The parameters are x for the horizontal dimension and y
for the vertical (being the total number of demes x times y), migration rate is mig.
Template name is ssm_2d.

In our first example, we will generate a template for a single population, constant size
model with a sample size of 30 and a deme size of 500. The code for this is:

Executing this code snippet will generate a file on the current directory called
simple_100_300.par this file can be given as input to Fastsimcoal2 to simulate the
demography (below we will see how Biopython can take care of calling
Fastsimcoal2).

This code consists of a single function call, let’s discuss it parameter by parameter.

The first parameter is the template id (from the list above). We are using the id
’simple’ which is the template for a single population of constant size along time.

The second parameter is the chromosome structure. Please ignore it for now, it will be
explained in the next section.

The third parameter is a list of all required parameters (recall that the simple model
only needs sample_size and pop_size) and possible values (in this case each
parameter only has a possible value).

Now, let’s consider an example where we want to generate several island models, and we
are interested in varying the number of demes: 10, 50 and 100 with a migration
rate of 1%. Sample size and deme
size will be the same as before. Here is the code:

In this case, 3 files will be generated: island_100_0.01_100_30.par,
island_10_0.01_100_30.par and island_50_0.01_100_30.par. Notice the
rule to make file names: template name, followed by parameter values in
reverse order.

A few, arguably more esoteric template demographies exist (please check the
Bio/PopGen/SimCoal/data directory on Biopython source tree). Furthermore it is possible
for the user to create new templates. That functionality will be discussed in a future
version of this document.

11.2.1.2 Chromosome structure

We strongly recommend reading Fastsimcoal2 documentation to understand the full potential
available in modeling chromosome structures. In this subsection we only discuss how
to implement chromosome structures using the Biopython interface, not the underlying
Fastsimcoal2 capabilities.

We will start by implementing a single chromosome, with 24 SNPs with
a recombination rate immediately on the right of each locus of 0.0005 and a
minimum frequency of the minor allele of 0. This will be specified by the
following list (to be passed as second parameter to the function
generate_simcoal_from_template):

[(1, [('SNP', [24, 0.0005, 0.0])])]

This is actually the chromosome structure used in the above examples.

The chromosome structure is represented by a list of chromosomes,
each chromosome (i.e., each element in the list)
is composed by a tuple (a pair): the first element
is the number of times the chromosome is to be repeated (as there
might be interest in repeating the same chromosome many times).
The second element is a list of the actual components of the chromosome.
Each element is again a pair, the first member is the locus type and
the second element the parameters for that locus type. Confused?
Before showing more examples let’s review the example above: We have
a list with one element (thus one chromosome), the chromosome is
a single instance (therefore not to be repeated), it is composed
of 24 SNPs, with a recombination rate of 0.0005 between each
consecutive SNP, the minimum frequency of the minor allele is
0.0 (i.e, it can be absent from a certain population).

We start by having 5 chromosomes with the same structure as
above (i.e., 24 SNPs). We then have 2 chromosomes which
have a DNA sequence with 10 nucleotides, 0.0 recombination rate,
0.0005 mutation rate, and a transition rate of 0.33. Then we
have an RFLP with 0.0 recombination rate to the next locus and
a 0.0001 mutation rate. Finally we have a microsatellite (or STR),
with 0.0 recombination rate to the next locus (note, that as this
is a single microsatellite which has no loci following, this
recombination rate here is irrelevant), with a mutation rate
of 0.001, geometric parameter of 0.0 and a range constraint
of 0.0 (for information about this parameters please consult
the Fastsimcoal2 documentation, you can use them to simulate
various mutation models, including the typical – for microsatellites –
stepwise mutation model among others).

We now discuss how to run Fastsimcoal2 from inside Biopython. It is required
that the binary for Fastsimcoal2 is called fastsimcoal21 (or fastsimcoal21.exe on Windows
based platforms), please note that the typical name when downloading the
program is in the format fastsimcoal2_x_y. As such, when installing
Fastsimcoal2
you will need to rename of the downloaded executable so that Biopython can
find it.

It is possible to run Fastsimcoal2 on files that were not generated using the method
above (e.g., writing a parameter file by hand), but we will show an
example by creating a model using the framework presented above.

The lines of interest are the last two (plus the new import).
Firstly a controller for the
application is created. The directory where the binary is located has
to be specified.

The simulator is then run on the last line: we know, from the rules explained
above, that the input file name is simple_100_30.par for the
simulation parameter file created. We then specify
that we want to run 50 independent simulations, by default Biopython
requests a simulation of diploid data, but a third parameter can
be added to simulate haploid data (adding as a parameter the
string ’0’). Fastsimcoal2 will now run (please
note that this can take quite a lot of time) and will create a directory
with the simulation results. The results can now be analysed (typically
studying the data with Arlequin3). In the future Biopython might support
reading the Arlequin3 format and thus allowing for the analysis of
Fastsimcoal2
data inside Biopython.

FDist is a selection detection application suite based on computing
(i.e. simulating) a “neutral” confidence interval based on Fst and
heterozygosity. Markers (which can be SNPs, microsatellites, AFLPs
among others) which lie outside the “neutral” interval are to be
considered as possible candidates for being under selection.

FDist is mainly used when the number of markers is considered enough
to estimate an average Fst, but not enough to either have outliers
calculated from the dataset directly or, with even more markers for
which the relative positions in the genome are known, to use
approaches based on, e.g., Extended Haplotype Heterozygosity (EHH).

The typical usage pattern for FDist is as follows:

Import a dataset from an external format into FDist format.

Compute average Fst. This is done by datacal inside FDist.

Simulate “neutral” markers based on the
average Fst and expected number of total populations.
This is the core operation, done by fdist inside FDist.

Calculate the confidence interval, based on the desired
confidence boundaries (typically 95% or 99%). This is done by
cplot and is mainly used to plot the interval.

Assess each marker status against the simulation “neutral”
confidence interval. Done
by pv. This is used to detect the outlier status of each marker
against the simulation.

We will now discuss each step with illustrating example code
(for this example to work FDist binaries have to be on the
executable PATH).

The FDist data format is application specific and is not used at
all by other applications, as such you will probably have to convert
your data for use with FDist. Biopython can help you do this.
Here is an example converting from GenePop format to FDist format
(along with imports that will be needed on examples further below):

In this code we simply parse a GenePop file and convert it to a FDist
record.

Printing an FDist record will generate
a string that can be directly saved to a file and supplied to FDist. FDist
requires the input file to be called infile, therefore we save the record on
a file with that name.

The most important fields on a FDist record are: num_pops, the number of
populations; num_loci, the number of loci and loci_data with the marker
data itself. Most probably the details of the record are of no interest
to the user, as the record only purpose is to be passed to FDist.

The next step is to calculate the average Fst of the dataset (along
with the sample size):

Number of populations existing in nature. This is really a
“guestimate”. Has to be lower than 100.

nsamples

Number of populations sampled, has to be lower than npops.

fst

Average Fst.

sample_size

Average number of individuals sampled on each population.

mut

Mutation model: 0 - Infinite alleles; 1 - Stepwise mutations

num_sims

Number of simulations to perform. Typically a number around
40000 will be OK, but if you get a confidence interval that looks sharp
(this can be detected when plotting the confidence interval computed
below) the value can be increased (a suggestion would be steps of 10000
simulations).

The confusion in wording between number of samples and sample size
stems from the original application.

A file named out.dat will be created with the simulated heterozygosities
and Fsts, it will have as many lines as the number of simulations
requested.

Note that fdist returns the average Fst that it was capable of
simulating, for more details about this issue please read below the paragraph
on approximating the desired average Fst.

The next (optional) step is to calculate the confidence interval:

cpl_interval = ctrl.run_cplot(ci=0.99)

You can only call cplot after having run fdist.

This will calculate the confidence intervals (99% in this case)
for a previous fdist run. A list of quadruples is returned. The
first element represents the heterozygosity, the second the lower
bound of Fst confidence interval for that heterozygosity,
the third the average and the fourth the upper bound. This can
be used to trace the confidence interval contour. This list
is also written to a file, out.cpl.

The main purpose of this step is return a set of points which can
be easily used to plot a confidence interval. It can be skipped
if the objective is only to assess the status of each marker against
the simulation, which is the next step...

pv_data = ctrl.run_pv()

You can only call cplot after having run datacal and fdist.

This will use the simulated markers to assess the status of each
individual real marker. A list, in the same order than the loci_list
that is on the FDist record (which is in the same order that the GenePop
record) is returned. Each element in the list is a quadruple, the
fundamental member of each quadruple is the last element (regarding the
other elements, please refer to the pv documentation – for the
sake of simplicity we will not discuss them here) which returns the
probability of the simulated Fst being lower than the marker Fst.
Higher values would indicate a stronger candidate for positive selection,
lower values a candidate for balancing selection, and intermediate values
a possible neutral marker. What is “higher”, “lower” or “intermediate”
is really a subjective issue, but taking a “confidence interval” approach
and considering a 95% confidence interval, “higher” would be between 0.95
and 1.0, “lower” between 0.0 and 0.05 and “intermediate” between 0.05 and
0.95.

11.3.1.1 Approximating the desired average Fst

Fdist tries to approximate the desired average Fst by doing a
coalescent simulation using migration rates based on the formula

Nm =

1 − Fst

4Fst

This formula assumes a few premises like an infinite number of populations.

In practice, when the number of populations is low, the mutation model
is stepwise and the sample size increases, fdist will not be able to
simulate an acceptable approximate average Fst.

To address that, a function is provided to iteratively approach the desired
value by running several fdists in sequence. This approach is computationally
more intensive than running a single fdist run, but yields good results.
The following code runs fdist approximating the desired Fst:

The only new optional parameter, when comparing with run_fdist, is limit
which is the desired maximum error. run_fdist can (and probably should)
be safely replaced with run_fdist_force_fst.

11.3.1.2 Final notes

The process to determine the average Fst can be more sophisticated than
the one presented here. For more information we refer you to the FDist
README file. Biopython’s code can be used to implement more sophisticated
approaches.

The most desired future developments would be the ones you add yourself ;) .

That being said, already existing fully functional code is currently being
incorporated in Bio.PopGen, that code covers the applications FDist and
SimCoal2, the HapMap and UCSC Table Browser databases and some simple statistics
like Fst, or allele counts.

The Bio.Phylo module was introduced in Biopython 1.54. Following the lead of SeqIO and AlignIO,
it aims to provide a common way to work with phylogenetic trees independently of the source data
format, as well as a consistent API for I/O operations.

Bio.Phylo is described in an open-access journal article [9, Talevich
et al., 2012], which you might also find helpful.

To get acquainted with the module, let’s start with a tree that we’ve already constructed, and
inspect it a few different ways. Then we’ll colorize the branches, to use a special phyloXML
feature, and finally save it.

Create a simple Newick file named simple.dnd using your favorite text editor,
or use simple.dnd
provided with the Biopython source code:

(((A,B),(C,D)),(E,F,G));

This tree has no branch lengths, only a topology and labelled terminals. (If you have a real
tree file available, you can follow this demo using that instead.)

Launch the Python interpreter of your choice:

% ipython -pylab

For interactive work, launching the IPython interpreter with the -pylab flag enables
matplotlib integration, so graphics will pop up automatically. We’ll use that during
this demo.

Now, within Python, read the tree file, giving the file name and the name of the format.

The functions draw and draw_graphviz support the display of different
colors and branch widths in a tree.
As of Biopython 1.59, the color and width attributes are available on the
basic Clade object and there’s nothing extra required to use them.
Both attributes refer to the branch leading the given clade, and apply recursively, so
all descendent branches will also inherit the assigned width and color values during
display.

In earlier versions of Biopython, these were special features of PhyloXML trees, and
using the attributes required first converting the tree to a subclass of the basic tree
object called Phylogeny, from the Bio.Phylo.PhyloXML module.

In Biopython 1.55 and later, this is a convenient tree method:

>>> tree = tree.as_phyloxml()

In Biopython 1.54, you can accomplish the same thing with one extra import:

Note that the file formats Newick and Nexus don’t support branch colors or widths, so
if you use these attributes in Bio.Phylo, you will only be able to save the values in
PhyloXML format. (You can still save a tree as Newick or Nexus, but the color and width
values will be skipped in the output file.)

Now we can begin assigning colors.
First, we’ll color the root clade gray. We can do that by assigning the 24-bit color
value as an RGB triple, an HTML-style hex string, or the name of one of the predefined
colors.

>>> tree.root.color = (128, 128, 128)

Or:

>>> tree.root.color = "#808080"

Or:

>>> tree.root.color = "gray"

Colors for a clade are treated as cascading down through the entire clade, so when we colorize
the root here, it turns the whole tree gray. We can override that by assigning a different
color lower down on the tree.

Let’s target the most recent common ancestor (MRCA) of the nodes named “E” and “F”. The
common_ancestor method returns a reference to that clade in the original tree, so when
we color that clade “salmon”, the color will show up in the original tree.

If we happened to know exactly where a certain clade is in the tree, in terms of nested list
entries, we can jump directly to that position in the tree by indexing it. Here, the index
[0,1] refers to the second child of the first child of the root.

Note that a clade’s color includes the branch leading to that clade, as well as its
descendents. The common ancestor of E and F turns out to be just under the root, and with this
coloring we can see exactly where the root of the tree is.

My, we’ve accomplished a lot! Let’s take a break here and save our work. Call the
write function with a file name or handle — here we use standard output, to see what
would be written — and the format phyloxml. PhyloXML saves the colors we assigned,
so you can open this phyloXML file in another tree viewer like Archaeopteryx, and the colors
will show up there, too.

Like SeqIO and AlignIO, Phylo handles file input and output through four functions:
parse, read, write and convert,
all of which support the tree file formats Newick, NEXUS, phyloXML and NeXML, as
well as the Comparative Data Analysis Ontology (CDAO).

The read function parses a single tree in the given file and returns it. Careful; it
will raise an error if the file contains more than one tree, or no trees.

This is essentially an outline of the object hierarchy Biopython uses to represent a tree. But
more likely, you’d want to see a drawing of the tree. There are three functions to do this.

As we saw in the demo, draw_ascii prints an ascii-art drawing of the tree (a
rooted phylogram) to standard output, or an open file handle if given. Not all of the
available information about the tree is shown, but it provides a way to quickly view the
tree without relying on any external dependencies.

draw_graphviz draws an unrooted cladogram, but requires that you have Graphviz,
PyDot or PyGraphviz, NetworkX, and matplotlib (or pylab) installed. Using the same example as
above, and the dot program included with Graphviz, let’s draw a rooted tree (see
Fig. 12.3):

(Tip: If you execute IPython with the -pylab option, calling draw_graphviz causes
the matplotlib viewer to launch automatically without manually calling show().)

This exports the tree object to a NetworkX graph, uses Graphviz to lay out the nodes, and
displays it using matplotlib.
There are a number of keyword arguments that can modify the resulting diagram, including
most of those accepted by the NetworkX functions networkx.draw and
networkx.draw_graphviz.

The display is also affected by the rooted attribute of the given tree object.
Rooted trees are shown with a “head” on each branch indicating direction (see
Fig. 12.3):

The “prog” argument specifies the Graphviz engine used for layout. The default,
twopi, behaves well for any size tree, reliably avoiding crossed branches. The
neato program may draw more attractive moderately-sized trees, but sometimes will
cross branches (see Fig. 12.3). The dot program may be useful
with small trees, but tends to do surprising things with the layout of larger trees.

>>> Phylo.draw_graphviz(tree, prog="neato")

This viewing mode is particularly handy for exploring larger trees, because the matplotlib
viewer can zoom in on a selected region, thinning out a cluttered graphic.

Note that branch lengths are not displayed accurately, because Graphviz ignores them when
creating the node layouts. The branch lengths are retained when exporting a tree as a NetworkX
graph object (to_networkx), however.

See the Phylo page on the Biopython wiki (http://biopython.org/wiki/Phylo) for
descriptions and examples of the more advanced functionality in draw_ascii,
draw_graphviz and to_networkx.

The Tree objects produced by parse and read are containers for recursive
sub-trees, attached to the Tree object at the root attribute (whether or not the
phylogenic tree is actually considered rooted). A Tree has globally applied information
for the phylogeny, such as rootedness, and a reference to a single Clade; a
Clade has node- and clade-specific information, such as branch length, and a list of
its own descendent Clade instances, attached at the clades attribute.

So there is a distinction between tree and tree.root. In practice, though, you
rarely need to worry about it. To smooth over the difference, both Tree and
Clade inherit from TreeMixin, which contains the implementations for methods
that would be commonly used to search, inspect or modify a tree or any of its clades. This
means that almost all of the methods supported by tree are also available on
tree.root and any clade below it. (Clade also has a root property, which
returns the clade object itself.)

For convenience, we provide a couple of simplified methods that return all external or internal
nodes directly as a list:

get_terminals

makes a list of all of this tree’s terminal (leaf) nodes.

get_nonterminals

makes a list of all of this tree’s nonterminal (internal)
nodes.

These both wrap a method with full control over tree traversal, find_clades. Two more
traversal methods, find_elements and find_any, rely on the same core
functionality and accept the same arguments, which we’ll call a “target specification” for
lack of a better description. These specify which objects in the tree will be matched and
returned during iteration. The first argument can be any of the following types:

A TreeElement instance, which tree elements will match by identity — so
searching with a Clade instance as the target will find that clade in the tree;

A class or type, where every tree element of the same type (or
sub-type) will be matched;

A dictionary where keys are tree element attributes and values are matched to the
corresponding attribute of each tree element. This one gets even more elaborate:

If an int is given, it matches numerically equal attributes, e.g. 1 will
match 1 or 1.0

If a boolean is given (True or False), the corresponding attribute value is
evaluated as a boolean and checked for the same

None matches None

If a string is given, the value is treated as a regular expression (which must
match the whole string in the corresponding element attribute, not just a prefix). A
given string without special regex characters will match string attributes exactly, so
if you don’t use regexes, don’t worry about it. For example, in a tree with clade
names Foo1, Foo2 and Foo3, tree.find_clades({"name": "Foo1"}) matches Foo1,
{"name": "Foo.*"} matches all three clades, and {"name": "Foo"} doesn’t
match anything.

Since floating-point arithmetic can produce some strange behavior, we don’t support
matching floats directly. Instead, use the boolean True to match every
element with a nonzero value in the specified attribute, then filter on that attribute
manually with an inequality (or exact number, if you like living dangerously).

If the dictionary contains multiple entries, a matching element must match each of the
given attribute values — think “and”, not “or”.

A function taking a single argument (it will be applied to each element in the
tree), returning True or False. For convenience, LookupError, AttributeError and ValueError
are silenced, so this provides another safe way to search for floating-point values in the
tree, or some more complex characteristic.

After the target, there are two optional keyword arguments:

terminal

— A boolean value to select for or against terminal clades (a.k.a. leaf
nodes): True searches for only terminal clades, False for non-terminal (internal) clades,
and the default, None, searches both terminal and non-terminal clades, as well as any tree
elements lacking the is_terminal method.

Finally, the methods accept arbitrary keyword arguments which are treated the same way as a
dictionary target specification: keys indicate the name of the element attribute to search for,
and the argument value (string, integer, None or boolean) is compared to the value of each
attribute found. If no keyword arguments are given, then any TreeElement types are matched.
The code for this is generally shorter than passing a dictionary as the target specification:
tree.find_clades({"name": "Foo1"}) can be shortened to
tree.find_clades(name="Foo1").

(In Biopython 1.56 or later, this can be even shorter: tree.find_clades("Foo1"))

Now that we’ve mastered target specifications, here are the methods used to traverse a tree:

find_clades

Find each clade containing a matching element. That is, find each element as with
find_elements, but return the corresponding clade object. (This is usually what you
want.)

The result is an iterable through all matching objects, searching depth-first by default.
This is not necessarily the same order as the elements appear in the Newick, Nexus or XML
source file!

find_elements

Find all tree elements matching the given attributes, and return the matching elements
themselves. Simple Newick trees don’t have complex sub-elements, so this behaves the same
as find_clades on them. PhyloXML trees often do have complex objects attached to
clades, so this method is useful for extracting those.

find_any

Return the first element found by find_elements(), or None. This is also useful for
checking whether any matching element exists in the tree, and can be used in a conditional.

Two more methods help navigating between nodes in the tree:

get_path

List the clades directly between the tree root (or current clade) and the given target.
Returns a list of all clade objects along this path, ending with the given target, but
excluding the root clade.

trace

List of all clade object between two targets in this tree. Excluding start, including
finish.

These methods provide information about the whole tree (or any clade).

common_ancestor

Find the most recent common ancestor of all the given targets. (This will be a Clade object).
If no target is given, returns the root of the current clade (the one this method is called
from); if 1 target is given, this returns the target itself. However, if any of the
specified targets are not found in the current tree (or clade), an exception is raised.

count_terminals

Counts the number of terminal (leaf) nodes within the tree.

depths

Create a mapping of tree clades to depths. The result is a dictionary where the keys are
all of the Clade instances in the tree, and the values are the distance from the root to
each clade (including terminals). By default the distance is the cumulative branch length
leading to the clade, but with the unit_branch_lengths=True option, only the number
of branches (levels in the tree) is counted.

distance

Calculate the sum of the branch lengths between two targets. If only one target is
specified, the other is the root of this tree.

total_branch_length

Calculate the sum of all the branch lengths in this tree. This is usually just called the
“length” of the tree in phylogenetics, but we use a more explicit name to avoid confusion
with Python terminology.

The rest of these methods are boolean checks:

is_bifurcating

True if the tree is strictly bifurcating; i.e. all nodes have either 2 or 0 children
(internal or external, respectively). The root may have 3 descendents and still be
considered part of a bifurcating tree.

is_monophyletic

Test if all of the given targets comprise a complete subclade — i.e., there
exists a clade such that its terminals are the same set as the given targets. The targets
should be terminals of the tree. For convenience, this method returns the common ancestor
(MCRA) of the targets if they are monophyletic (instead of the value True), and
False otherwise.

is_parent_of

True if target is a descendent of this tree — not required
to be a direct descendent. To check direct descendents of a clade, simply use list
membership testing: if subclade in clade: ...

is_preterminal

True if all direct descendents are terminal; False if any
direct descendent is not terminal.

Deletes the target from the tree, relinking its children to its parent.

collapse_all

Collapse all the descendents of this tree, leaving only terminals. Branch lengths are
preserved, i.e. the distance to each terminal stays the same. With a target specification
(see above), collapses only the internal nodes matching the specification.

ladderize

Sort clades in-place according to the number of terminal nodes. Deepest clades are placed
last by default. Use reverse=True to sort clades deepest-to-shallowest.

prune

Prunes a terminal clade from the tree. If taxon is from a bifurcation, the connecting node
will be collapsed and its branch length added to remaining terminal node. This might no
longer be a meaningful value.

root_with_outgroup

Reroot this tree with the outgroup clade containing the given targets, i.e. the common
ancestor of the outgroup. This method is only available on Tree objects, not Clades.

If the outgroup is identical to self.root, no change occurs. If the outgroup clade is
terminal (e.g. a single terminal node is given as the outgroup), a new bifurcating root
clade is created with a 0-length branch to the given outgroup. Otherwise, the internal node
at the base of the outgroup becomes a trifurcating root for the whole tree. If the original
root was bifurcating, it is dropped from the tree.

In all cases, the total branch length of the tree stays the same.

root_at_midpoint

Reroot this tree at the calculated midpoint between the two most distant
tips of the tree. (This uses root_with_outgroup under the hood.)

split

Generate n (default 2) new descendants. In a species tree, this is a speciation
event. New clades have the given branch_length and the same name as this clade’s
root plus an integer suffix (counting from 0) — for example, splitting a clade named
“A” produces the sub-clades “A0” and “A1”.

While Bio.Phylo doesn’t infer trees from alignments itself, there are third-party
programs available that do. These are supported through the module
Bio.Phylo.Applications, using the same general framework as
Bio.Emboss.Applications, Bio.Align.Applications and others.

Biopython 1.58 introduced a wrapper for PhyML
(http://www.atgc-montpellier.fr/phyml/). The program accepts an input alignment in
phylip-relaxed format (that’s Phylip format, but without the 10-character limit
on taxon names) and a variety of options. A quick example:

Note that some popular Phylip programs, including dnaml and protml,
are already available through the EMBOSS wrappers in Bio.Emboss.Applications if
you have the Phylip extensions to EMBOSS installed on your system.
See Section 6.4 for some examples and clues on how to use
programs like these.

Biopython 1.58 brought support for PAML
(http://abacus.gene.ucl.ac.uk/software/paml.html), a suite of programs for
phylogenetic analysis by maximum likelihood. Currently the programs codeml, baseml and
yn00 are implemented. Due to PAML’s usage of control files rather than command line
arguments to control runtime options, usage of this wrapper strays from the format of
other application wrappers in Biopython.

A typical workflow would be to initialize a PAML object, specifying an alignment file, a
tree file, an output file and a working directory. Next, runtime options are set via the
set_options() method or by reading an existing control file. Finally, the
program is run via the run() method and the output file is automatically parsed
to a results dictionary.

Much of this module was written during Google Summer of Code 2009, under the auspices of
NESCent, as a project to implement Python support for the phyloXML data format (see
12.4.4). Support for Newick and Nexus formats was added by porting part of the
existing Bio.Nexus module to the new classes used by Bio.Phylo.

Currently, Bio.Nexus contains some useful features that have not yet been ported to
Bio.Phylo classes — notably, calculating a consensus tree. If you find some functionality
lacking in Bio.Phylo, try poking throught Bio.Nexus to see if it’s there instead.

We’re open to any suggestions for improving the functionality and usability of this module;
just let us know on the mailing list or our bug database.

Finally, if you need additional functionality not yet included in the Phylo
module, check if it’s available in another of the high-quality Python libraries
for phylogenetics such as DendroPy (http://pythonhosted.org/DendroPy/) or
PyCogent (http://pycogent.org/). Since these libraries also support
standard file formats for phylogenetic trees, you can easily transfer data
between libraries by writing to a temporary file or StringIO object.

This chapter gives an overview of the functionality of the
Bio.motifs package included in Biopython. It is intended
for people who are involved in the analysis of sequence motifs, so I’ll
assume that you are familiar with basic notions of motif analysis. In
case something is unclear, please look at Section 13.10
for some relevant links.

Most of this chapter describes the new Bio.motifs package included
in Biopython 1.61 onwards, which is replacing the older Bio.Motif package
introduced with Biopython 1.50, which was in turn based on two older former
Biopython modules, Bio.AlignAce and Bio.MEME. It provides
most of their functionality with a unified motif object implementation.

Speaking of other libraries, if you are reading this you might be
interested in TAMO, another python library
designed to deal with sequence motifs. It supports more de-novo
motif finders, but it is not a part of Biopython and has some restrictions
on commercial use.

Since we are interested in motif analysis, we need to take a look at
Motif objects in the first place. For that we need to import
the Bio.motifs library:

>>> from Bio import motifs

and we can start creating our first motif objects. We can either create
a Motif object from a list of instances of the motif, or we can
obtain a Motif object by parsing a file from a motif database
or motif finding software.

The instances are saved in an attribute m.instances, which is essentially a Python list with some added functionality, as described below.
Printing out the Motif object shows the instances from which it was constructed:

>>> print(m)
TACAA
TACGC
TACAC
TACCC
AACCC
AATGC
AATGC
<BLANKLINE>

The length of the motif defined as the sequence length, which should be the same for all instances:

>>> len(m)
5

The Motif object has an attribute .counts containing the counts of each
nucleotide at each position. Printing this counts matrix shows it in an easily readable format:

The motif has an associated consensus sequence, defined as the sequence of
letters along the positions of the motif for which the largest value in the
corresponding columns of the .counts matrix is obtained:

>>> m.consensus
Seq('TACGC', IUPACUnambiguousDNA())

as well as an anticonsensus sequence, corresponding to the smallest values in
the columns of the .counts matrix:

>>> m.anticonsensus
Seq('GGGTG', IUPACUnambiguousDNA())

You can also ask for a degenerate consensus sequence, in which ambiguous
nucleotides are used for positions where there are multiple nucleotides with
high counts:

>>> m.degenerate_consensus
Seq('WACVC', IUPACAmbiguousDNA())

Here, W and R follow the IUPAC nucleotide ambiguity codes: W is either A or T,
and V is A, C, or G [10]. The degenerate consensus sequence is
constructed following the rules specified by Cavener [11].

Creating motifs from instances by hand is a bit boring, so it’s
useful to have some I/O functions for reading and writing
motifs. There are not any really well established standards for storing
motifs, but there are a couple of formats that are more used than
others.

One of the most popular motif databases is JASPAR. In addition to the motif sequence information, the JASPAR database stores a lot of meta-information for each motif. The module Bio.motifs contains a specialized class jaspar.Motif in which this meta-information is represented as attributes:

matrix_id - the unique JASPAR motif ID, e.g. ’MA0004.1’

name - the name of the TF, e.g. ’Arnt’

collection - the JASPAR collection to which the motif belongs, e.g. ’CORE’

tf_class - the structual class of this TF, e.g. ’Zipper-Type’

tf_family - the family to which this TF belongs, e.g. ’Helix-Loop-Helix’

species - the species to which this TF belongs, may have multiple values, these are specified as taxonomy IDs, e.g. 10090

tax_group - the taxonomic supergroup to which this motif belongs, e.g. ’vertebrates’

acc - the accesion number of the TF protein, e.g. ’P53762’

data_type - the type of data used to construct this motif, e.g. ’SELEX’

medline - the Pubmed ID of literature supporting this motif, may be multiple values, e.g. 7592839

pazar_id - external reference to the TF in the PAZAR database, e.g. ’TF0000003’

comment - free form text containing notes about the construction of the motif

The jaspar.Motif class inherits from the generic Motif class and therefore provides all the facilities of any of the motif formats — reading motifs, writing motifs, scanning sequences for motif instances etc.

JASPAR stores motifs in several different ways including three different flat file formats and as an SQL database. All of these formats facilitate the construction of a counts matrix. However, the amount of meta information described above that is available varies with the format.

The JASPAR sites format

The first of the three flat file formats contains a list of instances. As an example, these are the beginning and ending lines of the JASPAR Arnt.sites file showing known binding sites of the mouse helix-loop-helix transcription factor Arnt.

The JASPAR pfm format

JASPAR also makes motifs available directly as a count matrix,
without the instances from which it was created. This pfm format only
stores the counts matrix for a single motif.
For example, this is the JASPAR file SRF.pfm containing the counts matrix for the human SRF transcription factor:

As with the instances file, not meta information is stored in this format.

The JASPAR format jaspar

The jaspar file format allows multiple motifs to be specified in a single file. In this format each of the motif records consist of a header line followed by four lines defining the counts matrix. The header line begins with a > character (similar to the Fasta file format) and is followed by the unique JASPAR matrix ID and the TF name. The following example shows a jaspar formatted file containing the three motifs Arnt, RUNX1 and MEF2A:

Note that printing a JASPAR motif yields both the counts data and the available meta-information.

Accessing the JASPAR database

In addition to parsing these flat file formats, we can also retrieve motifs from a JASPAR SQL database. Unlike the flat file formats, a JASPAR database allows storing of all possible meta information defined in the JASPAR Motif class. It is beyond the scope of this document to describe how to set up a JASPAR database (please see the main JASPAR website). Motifs are read from a JASPAR database using the Bio.motifs.jaspar.db module. First connect to the JASPAR database using the JASPAR5 class which models the the latest JASPAR schema:

Now we can fetch a single motif by its unique JASPAR ID with the fetch_motif_by_id method. Note that a JASPAR ID conists of a base ID and a version number seperated by a decimal point, e.g. ’MA0004.1’. The fetch_motif_by_id method allows you to use either the fully specified ID or just the base ID. If only the base ID is provided, the latest version of the motif is returned.

>>> arnt = jdb.fetch_motif_by_id("MA0004")

Printing the motif reveals that the JASPAR SQL database stores much more meeta-information than the flat files:

We can also fetch motifs by name. The name must be an exact match (partial matches or database wildcards are not currently supported). Note that as the name is not guaranteed to be unique, the fetch_motifs_by_name method actually returns a list.

The fetch_motifs method allows you to fetch motifs which match a specified set of criteria. These criteria include any of the above described meta information as well as certain matrix properties such as the minimum information content (min_ic in the example below), the minimum length of the matrix or the minimum number of sites used to construct the matrix. Only motifs which pass ALL the specified criteria are returned. Note that selection criteria which correspond to meta information which allow for multiple values may be specified as either a single value or a list of values, e.g. tax_group and tf_family in the example below.

Compatibility with Perl TFBS modules

An important thing to note is that the JASPAR Motif class was designed to be compatible with the popular Perl TFBS modules. Therefore some specifics about the choice of defaults for background and pseudocounts as well as how information content is computed and sequences searched for instances is based on this compatibility criteria. These choices are noted in the specific subsections below.

Choice of background:
The Perl TFBS modules appear to allow a choice of custom background probabilities (although the documentation states that uniform background is assumed). However the default is to use a uniform background. Therefore it is recommended that you use a uniform background for computing the position-specific scoring matrix (PSSM). This is the default when using the Biopython motifs module.

Choice of pseudocounts:
By default, the Perl TFBS modules use a pseudocount equal to √N * bg[nucleotide], where N represents the total number of sequences used to construct the matrix. To apply this same pseudocount formula, set the motif pseudocounts attribute using the jaspar.calculate\_pseudcounts() funtion:

>>> motif.pseudocounts = motifs.jaspar.calculate_pseudocounts(motif)

Note that it is possible for the counts matrix to have an unequal number of sequences making up the columns. The pseudocount computation uses the average number of sequences making up the matrix. However, when normalize is called on the counts matrix, each count value in a column is divided by the total number of sequences making up that specific column, not by the average number of sequences. This differs from the Perl TFBS modules because the normalization is not done as a separate step and so the average number of sequences is used throughout the computation of the pssm. Therefore, for matrices with unequal column counts, the pssm computed by the motifs module will differ somewhat from the pssm computed by the Perl TFBS modules.

Computation of matrix information content:
The information content (IC) or specificity of a matrix is computed using the mean method of the PositionSpecificScoringMatrix class. However of note, in the Perl TFBS modules the default behaviour is to compute the IC without first applying pseudocounts, even though by default the PSSMs are computed using pseudocounts as described above.

Searching for instances:
Searching for instances with the Perl TFBS motifs was usually performed using a relative score threshold, i.e. a score in the range 0 to 1. In order to compute the absolute PSSM score corresponding to a relative score one can use the equation:

>>> abs_score = (pssm.max - pssm.min) * rel_score + pssm.min

To convert the absolute score of an instance back to a relative score, one can use the equation:

>>> rel_score = (abs_score - pssm.min) / (pssm.max - pssm.min)

For example, using the Arnt motif before, let’s search a sequence with a relative score threshold of 0.8.

MEME [12] is a tool for discovering motifs in a group of related
DNA or protein sequences. It takes as input a group of DNA or protein sequences
and outputs as many motifs as requested. Therefore, in contrast to JASPAR
files, MEME output files typically contain multiple motifs. This is an example.

At the top of an output file generated by MEME shows some background information
about the MEME and the version of MEME used:

********************************************************************************
COMMAND LINE SUMMARY
********************************************************************************
This information can also be useful in the event you wish to report a
problem with the MEME software.
command: meme -mod oops -dna -revcomp -nmotifs 2 -bfile yeast.nc.6.freq INO_up800.s
...

MAST

TRANSFAC is a manually curated database of transcription factors, together
with their genomic binding sites and DNA binding profiles [27].
While the file format used in the TRANSFAC database is nowadays also used
by others, we will refer to it as the TRANSFAC file format.

This file shows the frequency matrix of motif motif1 of 12 nucleotides.
In general, one file in the TRANSFAC format can contain multiple motifs. For
example, this is the contents of the example TRANSFAC file transfac.dat:

The overall version number, if available, is stored as record.version:

>>> record.version
'EXAMPLE January 15, 2013'

Each motif in record is in instance of the Bio.motifs.transfac.Motif
class, which inherits both from the Bio.motifs.Motif class and
from a Python dictionary. The dictionary uses the two-letter keys to
store any additional information about the motif:

TRANSFAC files are typically much more elaborate than this example, containing
lots of additional information about the motif. Table 13.2.3
lists the two-letter field codes that are commonly found in TRANSFAC files:

Table 13.1: Fields commonly found in TRANSFAC files

AC

Accession number

AS

Accession numbers, secondary

BA

Statistical basis

BF

Binding factors

BS

Factor binding sites underlying the matrix

CC

Comments

CO

Copyright notice

DE

Short factor description

DR

External databases

DT

Date created/updated

HC

Subfamilies

HP

Superfamilies

ID

Identifier

NA

Name of the binding factor

OC

Taxonomic classification

OS

Species/Taxon

OV

Older version

PV

Preferred version

TY

Type

XX

Empty line; these are not stored in the Record.

Each motif also has an attribute .references containing the
references associated with the motif, using these two-letter keys:

The .counts attribute of a Motif object shows how often each
nucleotide appeared at each position along the alignment. We can
normalize this matrix by dividing by the number of instances in the
alignment, resulting in the probability of each nucleotide at each
position along the alignment. We refer to these probabilities as
the position-weight matrix. However, beware that in the literature
this term may also be used to refer to the position-specific scoring
matrix, which we discuss below.

Usually, pseudocounts are added to each position before normalizing.
This avoids overfitting of the position-weight matrix to the limited
number of motif instances in the alignment, and can also prevent
probabilities from becoming zero. To add a fixed pseudocount to all
nucleotides at all positions, specify a number for the
pseudocounts argument:

Alternatively, pseudocounts can be a dictionary specifying the
pseudocounts for each nucleotide. For example, as the GC content of
the human genome is about 40%, you may want to choose the
pseudocounts accordingly:

Note that due to the pseudocounts, the degenerate consensus sequence
calculated from the position-weight matrix is slightly different
from the degenerate consensus sequence calculated from the instances
in the motif:

>>> m.degenerate_consensus
Seq('WACVC', IUPACAmbiguousDNA())

The reverse complement of the position-weight matrix can be calculated directly from the pwm:

Using the background distribution and PWM with pseudo-counts added,
it’s easy to compute the log-odds ratios, telling us what are the log
odds of a particular symbol to be coming from a motif against the
background. We can use the .log_odds() method on the position-weight
matrix:

Here we can see positive values for symbols more frequent in the motif
than in the background and negative for symbols more frequent in the
background. 0.0 means that it’s equally likely to see a symbol in the
background and in the motif.

This assumes that A, C, G, and T are equally likely in the background. To
calculate the position-specific scoring matrix against a background with
unequal probabilities for A, C, G, T, use the background argument.
For example, against a background with a 40% GC content, use

A uniform background is used if background is not specified.
The mean is particularly important, as its value is equal to the
Kullback-Leibler divergence or relative entropy, and is a measure for the
information content of the motif compared to the background. As in Biopython
the base-2 logarithm is used in the calculation of the log-odds scores, the
information content has units of bits.

The .reverse_complement, .consensus, .anticonsensus, and
.degenerate_consensus methods can be applied directly to PSSM objects.

The negative positions refer to instances of the motif found on the
reverse strand of the test sequence, and follow the Python convention
on negative indices. Therefore, the instance of the motif at pos
is located at test_seq[pos:pos+len(m)] both for positive and for
negative values of pos.

You may notice the threshold parameter, here set arbitrarily to
3.0. This is in log2, so we are now looking only for words, which
are eight times more likely to occur under the motif model than in the
background. The default threshold is 0.0, which selects everything
that looks more like the motif than the background.

You can also calculate the scores at all positions along the sequence:

In general, this is the fastest way to calculate PSSM scores.
The scores returned by pssm.calculate are for the forward strand
only. To obtain the scores on the reverse strand, you can take the reverse
complement of the PSSM:

If you want to use a less arbitrary way of selecting thresholds, you
can explore the distribution of PSSM scores. Since the space for a score
distribution grows exponentially with motif length, we are using an
approximation with a given precision to keep computation cost manageable:

The distribution object can be used to determine a number of different thresholds.
We can specify the requested false-positive rate (probability of “finding” a motif instance in background generated sequence):

You can also set the .pseudocounts to a dictionary over the four nucleotides if you want to use different pseudocounts for them. Setting motif.pseudocounts to None resets it to its default value of zero.

The position-specific scoring matrix depends on the background distribution, which is uniform by default:

Note that the position-weight matrix and the position-specific scoring matrix are recalculated each time you call motif.pwm or motif.pssm, respectively. If speed is an issue and you want to use the PWM or PSSM repeatedly, you can save them as a variable, as in

Before we start comparing motifs, I should point out that motif
boundaries are usually quite arbitrary. This means we often need
to compare motifs of different lengths, so comparison needs to involve
some kind of alignment. This means we have to take into account two things:

alignment of motifs

some function to compare aligned motifs

To align the motifs, we use ungapped alignment of PSSMs and substitute zeros
for any missing columns at the beginning and end of the matrices. This means
that effectively we are using the background distribution for columns missing
from the PSSM.
The distance function then returns the minimal distance between motifs, as
well as the corresponding offset in their alignment.

To give an exmaple, let us first load another motif,
which is similar to our test motif m:

Currently, Biopython has only limited support for de novo motif
finding. Namely, we support running and parsing of AlignAce and
MEME. Since the number of motif finding tools is growing rapidly,
contributions of new parsers are welcome.

Let’s assume, you have run MEME on sequences of your choice with your
favorite parameters and saved the output in the file
meme.out. You can retrieve the motifs reported by MEME by
running the following piece of code:

Besides the most wanted list of motifs, the result object contains more useful information, accessible through properties with self-explanatory names:

.alphabet

.datafile

.sequence_names

.version

.command

The motifs returned by the MEME Parser can be treated exactly like regular
Motif objects (with instances), they also provide some extra
functionality, by adding additional information about the instances.

If you have AlignAce installed on the same machine, you can also run
it directly from Biopython. A short example of how this can be done is
shown below (other parameters can be specified as keyword parameters):

Cluster analysis is the grouping of items into clusters based on the similarity of the items to each other. In bioinformatics, clustering is widely used in gene expression data analysis to find groups of genes with similar gene expression profiles. This may identify functionally related genes, as well as suggest the function of presently unknown genes.

The Biopython module Bio.Cluster provides commonly used clustering algorithms and was designed with the application to gene expression data in mind. However, this module can also be used for cluster analysis of other types of data. Bio.Cluster and the underlying C Clustering Library is described by De Hoon et al. [14].

The following four clustering approaches are implemented in Bio.Cluster:

Data representation

The data to be clustered are represented by a n × m Numerical Python array data. Within the context of gene expression data clustering, typically the rows correspond to different genes whereas the columns correspond to different experimental conditions. The clustering algorithms in Bio.Cluster can be applied both to rows (genes) and to columns (experiments).

Missing values

Often in microarray experiments, some of the data values are missing, which is indicated by an additional n × m Numerical Python integer array mask. If mask[i,j]==0, then data[i,j] is missing and is ignored in the analysis.

Random number generator

The k-means/medians/medoids clustering algorithms and Self-Organizing Maps (SOMs) include the use of a random number generator. The uniform random number generator in Bio.Cluster is based on the algorithm by L’Ecuyer [25], while random numbers following the binomial distribution are generated using the BTPE algorithm by Kachitvichyanukul and Schmeiser [23]. The random number generator is initialized automatically during its first call. As this random number generator uses a combination of two multiplicative linear congruential generators, two (integer) seeds are needed for initialization, for which we use the system-supplied random number generator rand (in the C standard library). We initialize this generator by calling srand with the epoch time in seconds, and use the first two random numbers generated by rand as seeds for the uniform random number generator in Bio.Cluster.

In order to cluster items into groups based on their similarity, we should first define what exactly we mean by similar. Bio.Cluster provides eight distance functions, indicated by a single character, to measure similarity, or conversely, distance:

'e':
Euclidean distance;

'b':
City-block distance.

'c':
Pearson correlation coefficient;

'a':
Absolute value of the Pearson correlation coefficient;

'u':
Uncentered Pearson correlation (equivalent to the cosine of the angle between two data vectors);

'x':
Absolute uncentered Pearson correlation;

's':
Spearman’s rank correlation;

'k':
Kendall’s τ.

The first two are true distance functions that satisfy the triangle inequality:

d

⎛
⎜
⎝

u

,

v

⎞
⎟
⎠

≤ d

⎛
⎜
⎝

u

,

w

⎞
⎟
⎠

+ d

⎛
⎜
⎝

w

,

v

⎞
⎟
⎠

for all

u

,

v

,

w

,

and are therefore refered to as metrics. In everyday language, this means that the shortest distance between two points is a straight line.

The remaining six distance measures are related to the correlation coefficient, where the distance d is defined in terms of the correlation r by d=1−r. Note that these distance functions are semi-metrics that do not satisfy the triangle inequality. For example, for

Euclidean distance

In Bio.Cluster, we define the Euclidean distance as

d =

1

n

n

∑

i=1

⎛
⎝

xi−yi

⎞
⎠

2.

Only those terms are included in the summation for which both
xi and yi are present, and the denominator n is chosen accordingly.
As the expression data xi and yi are subtracted directly from each other, we should make sure that the expression data are properly normalized when using the Euclidean distance.

City-block distance

The city-block distance, alternatively known as the Manhattan distance, is related to the Euclidean distance. Whereas the Euclidean distance corresponds to the length of the shortest path between two points, the city-block distance is the sum of distances along each dimension. As gene expression data tend to have missing values, in Bio.Cluster we define the city-block distance as the sum of distances divided by the number of dimensions:

d =

1

n

n

∑

i=1

⎪
⎪

xi−yi

⎪
⎪

.

This is equal to the distance you would have to walk between two points in a city, where you have to walk along city blocks. As for the Euclidean distance,
the expression data are subtracted directly from each other, and we should therefore make sure that they are properly normalized.

The Pearson correlation coefficient

The Pearson correlation coefficient is defined as

r =

1

n

n

∑

i=1

⎛
⎜
⎜
⎝

xi −x

σx

⎞
⎟
⎟
⎠

⎛
⎜
⎜
⎝

yi −ȳ

σy

⎞
⎟
⎟
⎠

,

in which
x, ȳ
are the sample mean of x and y respectively, and
σx, σy
are the sample standard deviation of x and y.
The Pearson correlation coefficient is a measure for how well a straight line can be fitted to a scatterplot of x and y.
If all the points in the scatterplot lie on a straight line, the Pearson correlation coefficient is either +1 or -1, depending on whether the slope of line is positive or negative. If the Pearson correlation coefficient is equal to zero, there is no correlation between x and y.

The Pearson distance is then defined as

dP ≡ 1 − r.

As the Pearson correlation coefficient lies between -1 and 1, the Pearson distance lies between 0 and 2.

Absolute Pearson correlation

By taking the absolute value of the Pearson correlation, we find a number between 0 and 1. If the absolute value is 1, all the points in the scatter plot lie on a straight line with either a positive or a negative slope. If the absolute value is equal to zero, there is no correlation between x and y.

The corresponding distance is defined as

dA ≡ 1 −

⎪
⎪

r

⎪
⎪

,

where r is the Pearson correlation coefficient. As the absolute value of the Pearson correlation coefficient lies between 0 and 1, the corresponding distance lies between 0 and 1 as well.

In the context of gene expression experiments, the absolute correlation is equal to 1 if the gene expression profiles of two genes are either exactly the same or exactly opposite. The absolute correlation coefficient should therefore be used with care.

Uncentered correlation (cosine of the angle)

In some cases, it may be preferable to use the uncentered correlation instead of the regular Pearson correlation coefficient. The uncentered correlation is defined as

rU =

1

n

n

∑

i=1

⎛
⎜
⎜
⎝

xi

σx(0)

⎞
⎟
⎟
⎠

⎛
⎜
⎜
⎝

yi

σy(0)

⎞
⎟
⎟
⎠

,

where

σx(0)

=

√

1

n

n

∑

i=1

xi2

;

σy(0)

=

√

1

n

n

∑

i=1

yi2

.

This is the same expression as for the regular Pearson correlation coefficient, except that the sample means
x, ȳ
are set equal to zero. The uncentered correlation may be appropriate if there is a zero reference state. For instance, in the case of gene expression data given in terms of log-ratios, a log-ratio equal to zero corresponds to the green and red signal being equal, which means that the experimental manipulation did not affect the gene expression.

The distance corresponding to the uncentered correlation coefficient is defined as

dU ≡ 1 − rU,

where
rU
is the uncentered correlation.
As the uncentered correlation coefficient lies between -1 and 1, the corresponding distance lies between 0 and 2.

The uncentered correlation is equal to the cosine of the angle of the two data vectors in n-dimensional space, and is often referred to as such.

Absolute uncentered correlation

As for the regular Pearson correlation, we can define a distance measure using the absolute value of the uncentered correlation:

dAU ≡ 1 −

⎪
⎪

rU

⎪
⎪

,

where
rU
is the uncentered correlation coefficient. As the absolute value of the uncentered correlation coefficient lies between 0 and 1, the corresponding distance lies between 0 and 1 as well.

Geometrically, the absolute value of the uncentered correlation is equal to the cosine between the supporting lines of the two data vectors (i.e., the angle without taking the direction of the vectors into consideration).

Spearman rank correlation

The Spearman rank correlation is an example of a non-parametric similarity measure, and tends to be more robust against outliers than the Pearson correlation.

To calculate the Spearman rank correlation, we replace each data value by their rank if we would order the data in each vector by their value. We then calculate the Pearson correlation between the two rank vectors instead of the data vectors.

As in the case of the Pearson correlation, we can define a distance measure corresponding to the Spearman rank correlation as

dS ≡ 1 − rS,

where
rS
is the Spearman rank correlation.

Kendall’s τ

Kendall’s τ
is another example of a non-parametric similarity measure. It is similar to the Spearman rank correlation, but instead of the ranks themselves only the relative ranks are used to calculate τ (see Snedecor & Cochran [29]).

We can define a distance measure corresponding to Kendall’s τ
as

dK ≡ 1 − τ.

As Kendall’s τ is always between -1 and 1, the corresponding distance will be between 0 and 2.

Weighting

For most of the distance functions available in Bio.Cluster, a weight vector can be applied. The weight vector contains weights for the items in the data vector. If the weight for item i is wi, then that item is treated as if it occurred wi times in the data. The weight do not have to be integers.
For the Spearman rank correlation and Kendall’s
τ,
weights do not have a well-defined meaning and are therefore not implemented.

Calculating the distance matrix

The distance matrix is a square matrix with all pairwise distances between the items in data, and can be calculated by the function distancematrix in the Bio.Cluster module:

To save memory, the distance matrix is returned as a list of 1D arrays.
The number of columns in each row is equal to the row number. Hence, the first row has zero elements. An example of the return value is

mask (default: None)
Array of integers showing which data are missing. If mask[i,j]==0, then data[i,j] is missing. If mask==None, then all data are present.

clusterid (default: None)
Vector of integers showing to which cluster each item belongs. If clusterid is None, then all items are assumed to belong to the same cluster.

method (default: 'a')
Specifies whether the arithmetic mean (method=='a') or the median (method=='m') is used to calculate the cluster center.

transpose (default: 0)
Determines if the centroids of the rows of data are to be calculated (transpose==0), or the centroids of the columns of data (transpose==1).

This function returns the tuple (cdata, cmask). The centroid data are stored in the 2D Numerical Python array cdata, with missing data indicated by the 2D Numerical Python integer array cmask. The dimensions of these arrays are (number of clusters, number of columns) if transpose is 0, or (number of rows, number of clusters) if transpose is 1. Each row (if transpose is 0) or column (if transpose is 1) contains the averaged data corresponding to the centroid of each cluster.

Calculating the distance between clusters

Given a distance function between items, we can define the distance between two clusters in several ways. The distance between the arithmetic means of the two clusters is used in pairwise centroid-linkage clustering and in k-means clustering. In k-medoids clustering, the distance between the medians of the two clusters is used instead. The shortest pairwise distance between items of the two clusters is used in pairwise single-linkage clustering, while the longest pairwise distance is used in pairwise maximum-linkage clustering. In pairwise average-linkage clustering, the distance between two clusters is defined as the average over the pairwise distances.

Partitioning algorithms divide items into k clusters such that the sum of distances over the items to their cluster centers is minimal.
The number of clusters k is specified by the user.
Three partitioning algorithms are available in Bio.Cluster:

k-means clustering

k-medians clustering

k-medoids clustering

These algorithms differ in how the cluster center is defined. In k-means clustering, the cluster center is defined as the mean data vector averaged over all items in the cluster. Instead of the mean, in k-medians clustering the median is calculated for each dimension in the data vector. Finally, in k-medoids clustering the cluster center is defined as the item which has the smallest sum of distances to the other items in the cluster. This clustering algorithm is suitable for cases in which the distance matrix is known but the original data matrix is not available, for example when clustering proteins based on their structural similarity.

The expectation-maximization (EM) algorithm is used to find this partitioning into k groups.
In the initialization of the EM algorithm, we randomly assign items to clusters. To ensure that no empty clusters are produced, we use the binomial distribution to randomly choose the number of items in each cluster to be one or more. We then randomly permute the cluster assignments to items such that each item has an equal probability to be in any cluster. Each cluster is thus guaranteed to contain at least one item.

We then iterate:

Calculate the centroid of each cluster, defined as either the mean, the median, or the medoid of the cluster;

Calculate the distances of each item to the cluster centers;

For each item, determine which cluster centroid is closest;

Reassign each item to its closest cluster, or stop the iteration if no further item reassignments take place.

To avoid clusters becoming empty during the iteration, in k-means and k-medians clustering the algorithm keeps track of the number of items in each cluster, and prohibits the last remaining item in a cluster from being reassigned to a different cluster. For k-medoids clustering, such a check is not needed, as the item that functions as the cluster centroid has a zero distance to itself, and will therefore never be closer to a different cluster.

As the initial assignment of items to clusters is done randomly, usually a different clustering solution is found each time the EM algorithm is executed.
To find the optimal clustering solution, the k-means algorithm is repeated many times, each time starting from a different initial random clustering. The sum of distances of the items to their cluster center is saved for each run, and the solution with the smallest value of this sum will be returned as the overall clustering solution.

How often the EM algorithm should be run depends on the number of items being clustered. As a rule of thumb, we can consider how often the optimal solution was found; this number is returned by the partitioning algorithms as implemented in this library. If the optimal solution was found many times, it is unlikely that better solutions exist than the one that was found. However, if the optimal solution was found only once, there may well be other solutions with a smaller within-cluster sum of distances. If the number of items is large (more than several hundreds), it may be difficult to find the globally optimal solution.

The EM algorithm terminates when no further reassignments take place. We noticed that for some sets of initial cluster assignments, the EM algorithm fails to converge due to the same clustering solution reappearing periodically after a small number of iteration steps. We therefore check for the occurrence of such periodic solutions during the iteration. After a given number of iteration steps, the current clustering result is saved as a reference. By comparing the clustering result after each subsequent iteration step to the reference state, we can determine if a previously encountered clustering result is found. In such a case, the iteration is halted. If after a given number of iterations the reference state has not yet been encountered, the current clustering solution is saved to be used as the new reference state. Initially, ten iteration steps are executed before resaving the reference state. This number of iteration steps is doubled each time, to ensure that periodic behavior with longer periods can also be detected.

k-means and k-medians

The k-means and k-medians algorithms are implemented as the function kcluster in Bio.Cluster:

mask (default: None)
Array of integers showing which data are missing. If mask[i,j]==0, then data[i,j] is missing. If mask==None, then all data are present.

weight (default: None)
The weights to be used when calculating distances. If weight==None, then equal weights are assumed.

transpose (default: 0)
Determines if rows (transpose is 0) or columns (transpose is 1) are to be clustered.

npass (default: 1)
The number of times the k-means/-medians clustering algorithm is performed, each time with a different (random) initial condition. If initialid is given, the value of npass is ignored and the clustering algorithm is run only once, as it behaves deterministically in that case.

method (default: a)
describes how the center of a cluster is found:

method=='a': arithmetic mean (k-means clustering);

method=='m': median (k-medians clustering).

For other values of method, the arithmetic mean is used.

dist (default: 'e', Euclidean distance)
Defines the distance function to be used (see 14.1).
Whereas all eight distance measures are accepted by kcluster, from a theoretical viewpoint it is best to use the Euclidean distance for the k-means algorithm, and the city-block distance for k-medians.

initialid (default: None)
Specifies the initial clustering to be used for the EM algorithm. If initialid==None, then a different random initial clustering is used for each of the npass runs of the EM algorithm. If initialid is not None, then it should be equal to a 1D array containing the cluster number (between 0 and nclusters-1) for each item. Each cluster should contain at least one item. With the initial clustering specified, the EM algorithm is deterministic.

This function returns a tuple (clusterid, error, nfound), where clusterid is an integer array containing the number of the cluster to which each row or cluster was assigned, error is the within-cluster sum of distances for the optimal clustering solution, and nfound is the number of times this optimal solution was found.

k-medoids clustering

The kmedoids routine performs k-medoids clustering on a given set of items, using the distance matrix and the number of clusters passed by the user:

where the following arguments are defined:
, nclusters=2, npass=1, initialid=None)|

distance (required)
The matrix containing the distances between the items; this matrix can be specified in three ways:

as a 2D Numerical Python array (in which only the left-lower part of the array will be accessed):

distance = array([[0.0, 1.1, 2.3],
[1.1, 0.0, 4.5],
[2.3, 4.5, 0.0]])

as a 1D Numerical Python array containing consecutively the distances in the left-lower part of the distance matrix:

distance = array([1.1, 2.3, 4.5])

as a list containing the rows of the left-lower part of the distance matrix:

distance = [array([]|,
array([1.1]),
array([2.3, 4.5])
]

These three expressions correspond to the same distance matrix.

nclusters (default: 2)
The number of clusters k.

npass (default: 1)
The number of times the k-medoids clustering algorithm is performed, each time with a different (random) initial condition. If initialid is given, the value of npass is ignored, as the clustering algorithm behaves deterministically in that case.

initialid (default: None)
Specifies the initial clustering to be used for the EM algorithm. If initialid==None, then a different random initial clustering is used for each of the npass runs of the EM algorithm. If initialid is not None, then it should be equal to a 1D array containing the cluster number (between 0 and nclusters-1) for each item. Each cluster should contain at least one item. With the initial clustering specified, the EM algorithm is deterministic.

This function returns a tuple (clusterid, error, nfound), where clusterid is an array containing the number of the cluster to which each item was assigned, error is the within-cluster sum of distances for the optimal k-medoids clustering solution, and nfound is the number of times the optimal solution was found. Note that the cluster number in clusterid is defined as the item number of the item representing the cluster centroid.

Hierarchical clustering methods are inherently different from the k-means clustering method. In hierarchical clustering, the similarity in the expression profile between genes or experimental conditions are represented in the form of a tree structure. This tree structure can be shown graphically by programs such as Treeview and Java Treeview, which has contributed to the popularity of hierarchical clustering in the analysis of gene expression data.

The first step in hierarchical clustering is to calculate the distance matrix, specifying all the distances between the items to be clustered. Next, we create a node by joining the two closest items. Subsequent nodes are created by pairwise joining of items or nodes based on the distance between them, until all items belong to the same node. A tree structure can then be created by retracing which items and nodes were merged. Unlike the EM algorithm, which is used in k-means clustering, the complete process of hierarchical clustering is deterministic.

Several flavors of hierarchical clustering exist, which differ in how the distance between subnodes is defined in terms of their members. In Bio.Cluster, pairwise single, maximum, average, and centroid linkage are available.

In pairwise single-linkage clustering, the distance between two nodes is defined as the shortest distance among the pairwise distances between the members of the two nodes.

In pairwise maximum-linkage clustering, alternatively known as pairwise complete-linkage clustering, the distance between two nodes is defined as the longest distance among the pairwise distances between the members of the two nodes.

In pairwise average-linkage clustering, the distance between two nodes is defined as the average over all pairwise distances between the items of the two nodes.

In pairwise centroid-linkage clustering, the distance between two nodes is defined as the distance between their centroids. The centroids are calculated by taking the mean over all the items in a cluster. As the distance from each newly formed node to existing nodes and items need to be calculated at each step, the computing time of pairwise centroid-linkage clustering may be significantly longer than for the other hierarchical clustering methods. Another peculiarity is that (for a distance measure based on the Pearson correlation), the distances do not necessarily increase when going up in the clustering tree, and may even decrease. This is caused by an inconsistency between the centroid calculation and the distance calculation when using the Pearson correlation: Whereas the Pearson correlation effectively normalizes the data for the distance calculation, no such normalization occurs for the centroid calculation.

For pairwise single-, complete-, and average-linkage clustering, the distance between two nodes can be found directly from the distances between the individual items. Therefore, the clustering algorithm does not need access to the original gene expression data, once the distance matrix is known. For pairwise centroid-linkage clustering, however, the centroids of newly formed subnodes can only be calculated from the original data and not from the distance matrix.

The implementation of pairwise single-linkage hierarchical clustering is based on the SLINK algorithm (R. Sibson, 1973), which is much faster and more memory-efficient than a straightforward implementation of pairwise single-linkage clustering. The clustering result produced by this algorithm is identical to the clustering solution found by the conventional single-linkage algorithm. The single-linkage hierarchical clustering algorithm implemented in this library can be used to cluster large gene expression data sets, for which conventional hierarchical clustering algorithms fail due to excessive memory requirements and running time.

Representing a hierarchical clustering solution

The result of hierarchical clustering consists of a tree of nodes, in which each node joins two items or subnodes. Usually, we are not only interested in which items or subnodes are joined at each node, but also in their similarity (or distance) as they are joined. To store one node in the hierarchical clustering tree, we make use of the class Node, which defined in Bio.Cluster. An instance of Node has three attributes:

left

right

distance

Here, left and right are integers referring to the two items or subnodes that are joined at this node, and distance is the distance between them. The items being clustered are numbered from 0 to (number of items − 1), while clusters are numbered from -1 to −(number of items−1). Note that the number of nodes is one less than the number of items.

To create a new Node object, we need to specify left and right; distance is optional.

To display a hierarchical clustering solution with visualization programs such as Java Treeview, it is better to scale all node distances such that they are between zero and one. This can be accomplished by calling the scale method on an existing Tree object:

>>> tree.scale()

This method takes no arguments, and returns None.

After hierarchical clustering, the items can be grouped into k clusters based on the tree structure stored in the Tree object by cutting the tree:

>>> clusterid = tree.cut(nclusters=1)

where nclusters (defaulting to 1) is the desired number of clusters k.
This method ignores the top k−1 linking events in the tree structure, resulting in k separated clusters of items. The number of clusters k should be positive, and less than or equal to the number of items.
This method returns an array clusterid containing the number of the cluster to which each item is assigned.

Performing hierarchical clustering

To perform hierarchical clustering, use the treecluster function in Bio.Cluster.

>>> from Bio.Cluster import treecluster
>>> tree = treecluster(data)

where the following arguments are defined:

data
Array containing the data for the items.

mask (default: None)
Array of integers showing which data are missing. If mask[i,j]==0, then data[i,j] is missing. If mask==None, then all data are present.

weight (default: None)
The weights to be used when calculating distances. If weight==None, then equal weights are assumed.

transpose (default: 0)
Determines if rows (transpose==0) or columns (transpose==1) are to be clustered.

distancematrix
The distance matrix, which can be specified in three ways:

as a 2D Numerical Python array (in which only the left-lower part of the array will be accessed):

distance = array([[0.0, 1.1, 2.3],
[1.1, 0.0, 4.5],
[2.3, 4.5, 0.0]])

as a 1D Numerical Python array containing consecutively the distances in the left-lower part of the distance matrix:

distance = array([1.1, 2.3, 4.5])

as a list containing the rows of the left-lower part of the distance matrix:

distance = [array([]),
array([1.1]),
array([2.3, 4.5])

These three expressions correspond to the same distance matrix.
As treecluster may shuffle the values in the distance matrix as part of the clustering algorithm, be sure to save this array in a different variable before calling treecluster if you need it later.

method
The linkage method to be used:

method=='s': pairwise single-linkage clustering

method=='m': pairwise maximum- (or complete-) linkage clustering

method=='a': pairwise average-linkage clustering

While pairwise single-, maximum-, and average-linkage clustering can be calculated from the distance matrix alone, pairwise centroid-linkage cannot.

When calling treecluster, either data or distancematrix should be None.

This function returns a Tree object. This object contains (number of items − 1) nodes, where the number of items is the number of rows if rows were clustered, or the number of columns if columns were clustered. Each node describes a pairwise linking event, where the node attributes left and right each contain the number of one item or subnode, and distance the distance between them. Items are numbered from 0 to (number of items − 1), while clusters are numbered -1 to −(number of items−1).

SOMs organize items into clusters that are situated in some topology. Usually a rectangular topology is chosen. The clusters generated by SOMs are such that neighboring clusters in the topology are more similar to each other than clusters far from each other in the topology.

The first step to calculate a SOM is to randomly assign a data vector to each cluster in the topology. If rows are being clustered, then the number of elements in each data vector is equal to the number of columns.

An SOM is then generated by taking rows one at a time, and finding which cluster in the topology has the closest data vector. The data vector of that cluster, as well as those of the neighboring clusters, are adjusted using the data vector of the row under consideration. The adjustment is given by

Δ

x

cell = τ ·

⎛
⎜
⎝

x

row −

x

cell

⎞
⎟
⎠

.

The parameter
τ
is a parameter that decreases at each iteration step. We have used a simple linear function of the iteration step:

τ = τinit ·

⎛
⎜
⎜
⎝

1 −

i

n

⎞
⎟
⎟
⎠

,

τinit
is the initial value of τ as specified by the user, i is the number of the current iteration step, and n is the total number of iteration steps to be performed. While changes are made rapidly in the beginning of the iteration, at the end of iteration only small changes are made.

All clusters within a radius R are adjusted to the gene under consideration. This radius decreases as the calculation progresses as

R = Rmax ·

⎛
⎜
⎜
⎝

1 −

i

n

⎞
⎟
⎟
⎠

,

in which the maximum radius is defined as

Rmax =

√

Nx2 + Ny2

,

where
(Nx, Ny)
are the dimensions of the rectangle defining the topology.

The function somcluster implements the complete algorithm to calculate a Self-Organizing Map on a rectangular grid. First it initializes the random number generator. The node data are then initialized using the random number generator. The order in which genes or microarrays are used to modify the SOM is also randomized. The total number of iterations in the SOM algorithm is specified by the user.

clusterid:
An array with two columns, where the number of rows is equal to the number of items that were clustered. Each row contains the x and y coordinates of the cell in the rectangular SOM grid to which the item was assigned.

celldata:
An array with dimensions (nxgrid, nygrid, number of columns) if rows are being clustered, or (nxgrid, nygrid, number of rows) if columns are being clustered. Each element [ix][iy] of this array is a 1D vector containing the gene expression data for the centroid of the cluster in the grid cell with coordinates [ix][iy].

Principal Component Analysis (PCA) is a widely used technique for analyzing multivariate data. A practical example of applying Principal Component Analysis to gene expression data is presented by Yeung and Ruzzo (2001) [33].

In essence, PCA is a coordinate transformation in which each row in the data matrix is written as a linear sum over basis vectors called principal components, which are ordered and chosen such that each maximally explains the remaining variance in the data vectors. For example, an n × 3 data matrix can be represented as an ellipsoidal cloud of n points in three dimensional space. The first principal component is the longest axis of the ellipsoid, the second principal component the second longest axis of the ellipsoid, and the third principal component is the shortest axis. Each row in the data matrix can be reconstructed as a suitable linear combination of the principal components. However, in order to reduce the dimensionality of the data, usually only the most important principal components are retained. The remaining variance present in the data is then regarded as unexplained variance.

The principal components can be found by calculating the eigenvectors of the covariance matrix of the data. The corresponding eigenvalues determine how much of the variance present in the data is explained by each principal component.

Before applying principal component analysis, typically the mean is subtracted from each column in the data matrix. In the example above, this effectively centers the ellipsoidal cloud around its centroid in 3D space, with the principal components describing the variation of points in the ellipsoidal cloud with respect to their centroid.

The function pca below first uses the singular value decomposition to calculate the eigenvalues and eigenvectors of the data matrix. The singular value decomposition is implemented as a translation in C of the Algol procedure svd [16], which uses Householder bidiagonalization and a variant of the QR algorithm. The principal components, the coordinates of each data vector along the principal components, and the eigenvalues corresponding to the principal components are then evaluated and returned in decreasing order of the magnitude of the eigenvalue. If data centering is desired, the mean should be subtracted from each column in the data matrix before calling the pca routine.

To apply Principal Component Analysis to a rectangular matrix data, use

Cluster/TreeView are GUI-based codes for clustering gene expression data. They were originally written by Michael Eisen while at Stanford University. Bio.Cluster contains functions for reading and writing data files that correspond to the format specified for Cluster/TreeView. In particular, by saving a clustering result in that format, TreeView can be used to visualize the clustering results. We recommend using Alok Saldanha’s http://jtreeview.sourceforge.net/Java TreeView program, which can display hierarchical as well as k-means clustering results.

An object of the class Record contains all information stored in a Cluster/TreeView-type data file. To store the information contained in the data file in a Record object, we first open the file and then read it:

The read command reads the tab-delimited text file mydatafile.txt containing gene expression data in the format specified for Michael Eisen’s Cluster/TreeView program. For a description of this file format, see the manual to Cluster/TreeView. It is available at Michael Eisen’s lab website and at our website.

transpose
Determines if genes or microarrays are being clustered. If transpose==0, genes (rows) are being clustered. If transpose==1, microarrays (columns) are clustered.

This function returns a Tree object. This object contains (number of items − 1) nodes, where the number of items is the number of rows if rows were clustered, or the number of columns if columns were clustered. Each node describes a pairwise linking event, where the node attributes left and right each contain the number of one item or subnode, and distance the distance between them. Items are numbered from 0 to (number of items − 1), while clusters are numbered -1 to −(number of items−1).

Performing k-means or k-medians clustering

To perform k-means or k-medians clustering on the items stored in the record, use

>>> clusterid, error, nfound = record.kcluster()

where the following arguments are defined:

nclusters (default: 2)
The number of clusters k.

transpose (default: 0)
Determines if rows (transpose is 0) or columns (transpose is 1) are to be clustered.

npass (default: 1)
The number of times the k-means/-medians clustering algorithm is performed, each time with a different (random) initial condition. If initialid is given, the value of npass is ignored and the clustering algorithm is run only once, as it behaves deterministically in that case.

This function returns a tuple (clusterid, error, nfound), where clusterid is an integer array containing the number of the cluster to which each row or cluster was assigned, error is the within-cluster sum of distances for the optimal clustering solution, and nfound is the number of times this optimal solution was found.

Calculating a Self-Organizing Map

To calculate a Self-Organizing Map of the items stored in the record, use

>>> clusterid, celldata = record.somcluster()

where the following arguments are defined:

transpose (default: 0)
Determines if rows (transpose is 0) or columns (transpose is 1) are to be clustered.

nxgrid, nygrid (default: 2, 1)
The number of cells horizontally and vertically in the rectangular grid on which the Self-Organizing Map is calculated.

inittau (default: 0.02)
The initial value for the parameter τ that is used in the SOM algorithm. The default value for inittau is 0.02, which was used in Michael Eisen’s Cluster/TreeView program.

clusterid:
An array with two columns, where the number of rows is equal to the number of items that were clustered. Each row contains the x and y coordinates of the cell in the rectangular SOM grid to which the item was assigned.

celldata:
An array with dimensions (nxgrid, nygrid, number of columns) if rows are being clustered, or (nxgrid, nygrid, number of rows) if columns are being clustered. Each element [ix][iy] of this array is a 1D vector containing the gene expression data for the centroid of the cluster in the grid cell with coordinates [ix][iy].

Saving the clustering result

To save the clustering result, use

>>> record.save(jobname, geneclusters, expclusters)

where the following arguments are defined:

jobname
The string jobname is used as the base name for names of the files that are to be saved.

geneclusters
This argument describes the gene (row-wise) clustering result. In case of k-means clustering, this is a 1D array containing the number of the cluster each gene belongs to. It can be calculated using kcluster. In case of hierarchical clustering, geneclusters is a Tree object.

expclusters
This argument describes the (column-wise) clustering result for the experimental conditions. In case of k-means clustering, this is a 1D array containing the number of the cluster each experimental condition belongs to. It can be calculated using kcluster. In case of hierarchical clustering, expclusters is a Tree object.

This method writes the text file jobname.cdt, jobname.gtr, jobname.atr, jobname*.kgg, and/or jobname*.kag for subsequent reading by the Java TreeView program. If geneclusters and expclusters are both None, this method only writes the text file jobname.cdt; this file can subsequently be read into a new Record object.

This is an example of a hierarchical clustering calculation, using single linkage clustering for genes and maximum linkage clustering for experimental conditions. As the Euclidean distance is being used for gene clustering, it is necessary to scale the node distances genetree such that they are all between zero and one. This is needed for the Java TreeView code to display the tree diagram correctly. To cluster the experimental conditions, the uncentered correlation is being used. No scaling is needed in this case, as the distances in exptree are already between zero and two. The example data cyano.txt can be found in the data subdirectory.

Logistic regression is a supervised learning approach that attempts to distinguish K classes from each other using a weighted sum of some predictor variables xi. The logistic regression model is used to calculate the weights βi of the predictor variables. In Biopython, the logistic regression model is currently implemented for two classes only (K = 2); the number of predictor variables has no predefined limit.

As an example, let’s try to predict the operon structure in bacteria. An operon is a set of adjacent genes on the same strand of DNA that are transcribed into a single mRNA molecule. Translation of the single mRNA molecule then yields the individual proteins. For Bacillus subtilis, whose data we will be using, the average number of genes in an operon is about 2.4.

As a first step in understanding gene regulation in bacteria, we need to know the operon structure. For about 10% of the genes in Bacillus subtilis, the operon structure is known from experiments. A supervised learning method can be used to predict the operon structure for the remaining 90% of the genes.

For such a supervised learning approach, we need to choose some predictor variables xi that can be measured easily and are somehow related to the operon structure. One predictor variable might be the distance in base pairs between genes. Adjacent genes belonging to the same operon tend to be separated by a relatively short distance, whereas adjacent genes in different operons tend to have a larger space between them to allow for promoter and terminator sequences. Another predictor variable is based on gene expression measurements. By definition, genes belonging to the same operon have equal gene expression profiles, while genes in different operons are expected to have different expression profiles. In practice, the measured expression profiles of genes in the same operon are not quite identical due to the presence of measurement errors. To assess the similarity in the gene expression profiles, we assume that the measurement errors follow a normal distribution and calculate the corresponding log-likelihood score.

We now have two predictor variables that we can use to predict if two adjacent genes on the same strand of DNA belong to the same operon:

x1: the number of base pairs between them;

x2: their similarity in expression profile.

In a logistic regression model, we use a weighted sum of these two predictors to calculate a joint score S:

S = β0 + β1x1 + β2x2.
(15.1)

The logistic regression model gives us appropriate values for the parameters β0, β1, β2 using two sets of example genes:

OP: Adjacent genes, on the same strand of DNA, known to belong to the same operon;

NOP: Adjacent genes, on the same strand of DNA, known to belong to different operons.

In the logistic regression model, the probability of belonging to a class depends on the score via the logistic function. For the two classes OP and NOP, we can write this as

Pr(OP|x1, x2)

=

exp(β0 + β1x1 + β2x2)

1+exp(β0 + β1x1 + β2x2)

(15.2)

Pr(NOP|x1, x2)

=

1

1+exp(β0 + β1x1 + β2x2)

(15.3)

Using a set of gene pairs for which it is known whether they belong to the same operon (class OP) or to different operons (class NOP), we can calculate the weights β0, β1, β2 by maximizing the log-likelihood corresponding to the probability functions (15.2) and (15.3).

Here, xs and ys are the training data: xs contains the predictor variables for each gene pair, and ys specifies if the gene pair belongs to the same operon (1, class OP) or different operons (0, class NOP). The resulting logistic regression model is stored in model, which contains the weights β0, β1, and β2:

Note that β1 is negative, as gene pairs with a shorter intergene distance have a higher probability of belonging to the same operon (class OP). On the other hand, β2 is positive, as gene pairs belonging to the same operon typically have a higher similarity score of their gene expression profiles.
The parameter β0 is positive due to the higher prevalence of operon gene pairs than non-operon gene pairs in the training data.

The function train has two optional arguments: update_fn and typecode. The update_fn can be used to specify a callback function, taking as arguments the iteration number and the log-likelihood. With the callback function, we can for example track the progress of the model calculation (which uses a Newton-Raphson iteration to maximize the log-likelihood function of the logistic regression model):

The iteration stops once the increase in the log-likelihood function is less than 0.01. If no convergence is reached after 500 iterations, the train function returns with an AssertionError.

The optional keyword typecode can almost always be ignored. This keyword allows the user to choose the type of Numeric matrix to use. In particular, to avoid memory problems for very large problems, it may be necessary to use single-precision floats (Float8, Float16, etc.) rather than double, which is used by default.

Classification is performed by calling the classify function. Given a logistic regression model and the values for x1 and x2 (e.g. for a gene pair of unknown operon structure), the classify function returns 1 or 0, corresponding to class OP and class NOP, respectively. For example, let’s consider the gene pairs yxcE, yxcD and yxiB, yxiA:

Table 15.2: Adjacent gene pairs of unknown operon status.

Gene pair

Intergene distance x1

Gene expression score x2

yxcE — yxcD

6

-173.143442352

yxiB — yxiA

309

-271.005880394

The logistic regression model classifies yxcE, yxcD as belonging to the same operon (class OP), while yxiB, yxiA are predicted to belong to different operons:

showing that the prediction is correct for all but one of the gene pairs. A more reliable estimate of the prediction accuracy can be found from a leave-one-out analysis, in which the model is recalculated from the training data after removing the gene to be predicted:

The logistic regression model is similar to linear discriminant analysis. In linear discriminant analysis, the class probabilities also follow equations (15.2) and (15.3). However, instead of estimating the coefficients β directly, we first fit a normal distribution to the predictor variables x. The coefficients β are then calculated from the means and covariances of the normal distribution. If the distribution of x is indeed normal, then we expect linear discriminant analysis to perform better than the logistic regression model. The logistic regression model, on the other hand, is more robust to deviations from normality.

Another similar approach is a support vector machine with a linear kernel. Such an SVM also uses a linear combination of the predictors, but estimates the coefficients β from the predictor variables x near the boundary region between the classes. If the logistic regression model (equations (15.2) and (15.3)) is a good description for x away from the boundary region, we expect the logistic regression model to perform better than an SVM with a linear kernel, as it relies on more data. If not, an SVM with a linear kernel may perform better.

The k-nearest neighbors method is a supervised learning approach that does not need to fit a model to the data. Instead, data points are classified based on the categories of the k nearest neighbors in the training data set.

In Biopython, the k-nearest neighbors method is available in Bio.kNN. To illustrate the use of the k-nearest neighbor method in Biopython, we will use the same operon data set as in section 15.1.

Using the data in Table 15.1, we create and initialize a k-nearest neighbors model as follows:

>>> from Bio import kNN
>>> k = 3
>>> model = kNN.train(xs, ys, k)

where xs and ys are the same as in Section 15.1.2. Here, k is the number of neighbors k that will be considered for the classification. For classification into two classes, choosing an odd number for k lets you avoid tied votes. The function name train is a bit of a misnomer, since no model training is done: this function simply stores xs, ys, and k in model.

To classify new data using the k-nearest neighbors model, we use the classify function. This function takes a data point (x1,x2) and finds the k-nearest neighbors in the training data set xs. The data point (x1, x2) is then classified based on which category (ys) occurs most among the k neighbors.

In agreement with the logistic regression model, yxcE, yxcD are classified as belonging to the same operon (class OP), while yxiB, yxiA are predicted to belong to different operons.

The classify function lets us specify both a distance function and a weight function as optional arguments. The distance function affects which k neighbors are chosen as the nearest neighbors, as these are defined as the neighbors with the smallest distance to the query point (x, y). By default, the Euclidean distance is used. Instead, we could for example use the city-block (Manhattan) distance:

To find out how confident we can be in these predictions, we can call the calculate function, which will calculate the total weight assigned to the classes OP and NOP. For the default weighting scheme, this reduces to the number of neighbors in each category. For yxcE, yxcD, we find

showing that the prediction is correct for all but two of the gene pairs. A more reliable estimate of the prediction accuracy can be found from a leave-one-out analysis, in which the model is recalculated from the training data after removing the gene to be predicted:

The Bio.Graphics module depends on the third party Python library
ReportLab. Although focused on producing PDF files,
ReportLab can also create encapsulated postscript (EPS) and (SVG) files. In addition
to these vector based images, provided certain further dependencies such as the
Python Imaging Library (PIL) are
installed, ReportLab can also output bitmap images (including JPEG, PNG, GIF, BMP
and PICT formats).

The Bio.Graphics.GenomeDiagram module was added to Biopython 1.50,
having previously been available as a separate Python module dependent on Biopython.
GenomeDiagram is described in the Bioinformatics journal publication by Pritchard et al. (2006) [2],
which includes some examples images. There is a PDF copy of the old manual here,
http://biopython.org/DIST/docs/GenomeDiagram/userguide.pdf which has some
more examples.

As the name might suggest, GenomeDiagram was designed for drawing whole genomes, in
particular prokaryotic genomes, either as linear diagrams (optionally broken up into
fragments to fit better) or as circular wheel diagrams. Have a look at Figure 2 in
Toth et al. (2006) [3]
for a good example. It proved also well suited to drawing quite detailed figures for
smaller genomes such as phage, plasmids or mitochrondia, for example see Figures 1
and 2 in Van der Auwera et al. (2009) [4]
(shown with additional manual editing).

This module is easiest to use if you have your genome loaded as a SeqRecord
object containing lots of SeqFeature objects - for example as loaded from a
GenBank file (see Chapters 4 and 5).

GenomeDiagram uses a nested set of objects. At the top level, you have a diagram
object representing a sequence (or sequence region) along the horizontal axis (or
circle). A diagram can contain one or more tracks, shown stacked vertically (or
radially on circular diagrams). These will typically all have the same length
and represent the same sequence region. You might use one track to show the gene
locations, another to show regulatory regions, and a third track to show the GC
percentage.

The most commonly used type of track will contain features, bundled together in
feature-sets. You might choose to use one feature-set for all your CDS features,
and another for tRNA features. This isn’t required - they can all go in the same
feature-set, but it makes it easier to update the properties of just selected
features (e.g. make all the tRNA features red).

There are two main ways to build up a complete diagram. Firstly, the top down
approach where you create a diagram object, and then using its methods add
track(s), and use the track methods to add feature-set(s), and use their
methods to add the features. Secondly, you can create the individual objects
separately (in whatever order suits your code), and then combine them.

We’re going to draw a whole genome from a SeqRecord object read in from
a GenBank file (see Chapter 5). This example uses the
pPCP1 plasmid from Yersinia pestis biovar Microtus, the file is
included with the Biopython unit tests under the GenBank folder, or online
NC_005816.gb from our website.

Now the fun part - we take each gene SeqFeature object in our
SeqRecord, and use it to generate a feature on the diagram. We’re
going to color them blue, alternating between a dark blue and a light blue.

Now we come to actually making the output file. This happens in two steps,
first we call the draw method, which creates all the shapes using
ReportLab objects. Then we call the write method which renders these
to the requested file format. Note you can output in multiple file formats:

In the above example we used a SeqRecord’s SeqFeature objects
to build our diagram (see also Section 4.3).
Sometimes you won’t have SeqFeature objects,
but just the coordinates for a feature you want to draw. You have to create
minimal SeqFeature object, but this is easy:

Recall we used the following (where feature was a
SeqFeature object) to add a feature to the diagram:

gd_feature_set.add_feature(feature, color=color, label=True)

In the example above the SeqFeature annotation was used to pick a
sensible caption for the features. By default the following possible entries
under the SeqFeature object’s qualifiers dictionary are used:
gene, label, name, locus_tag, and
product. More simply, you can specify a name directly:

In addition to the caption text for each feature’s label, you can also choose
the font, position (this defaults to the start of the sigil, you can also
choose the middle or at the end) and orientation (for linear diagrams only,
where this defaults to rotated by 45 degrees):

The examples above have all just used the default sigil for the feature, a
plain box, which was all that was available in the last publicly released standalone version of GenomeDiagram. Arrow sigils were included when
GenomeDiagram was added to Biopython 1.50:

#Default uses a BOX sigil
gd_feature_set.add_feature(feature)
#You can make this explicit:
gd_feature_set.add_feature(feature, sigil="BOX")
#Or opt for an arrow:
gd_feature_set.add_feature(feature, sigil="ARROW")

Biopython 1.61 added three more sigils,

#Box with corners cut off (making it an octagon)
gd_feature_set.add_feature(feature, sigil="OCTO")
#Box with jagged edges (useful for showing breaks in contains)
gd_feature_set.add_feature(feature, sigil="JAGGY")
#Arrow which spans the axis with strand used only for direction
gd_feature_set.add_feature(feature, sigil="BIGARROW")

These are shown
below.
Most sigils fit into a bounding box (as given by the default BOX sigil),
either above or below the axis for the forward or reverse strand, or
straddling it (double the height) for strand-less features.
The BIGARROW sigil is different, always straddling the axis with the
direction taken from the feature’s stand.

We introduced the arrow sigils in the previous section.
There are two additional options to adjust the shapes of the arrows, firstly
the thickness of the arrow shaft, given as a proportion of the height of the
bounding box:

Now let’s return to the pPCP1 plasmid from Yersinia pestis biovar
Microtus, and the top down approach used in Section 16.1.3,
but take advantage of the sigil options we’ve now discussed. This time
we’ll use arrows for the genes, and overlay them with strand-less features
(as plain boxes) showing the position of some restriction digest sites.

All the examples so far have used a single track, but you can have more than
one track – for example show the genes on one, and repeat regions on another.
In this example we’re going to show three phage genomes side by side to scale,
inspired by Figure 6 in Proux et al. (2002) [5].
We’ll need the GenBank files for the following three phage:

NC_002703 – Lactococcus phage Tuc2009, complete genome (38347 bp)

AF323668 – Bacteriophage bIL285, complete genome (35538 bp)

NC_003212 – Listeria innocua Clip11262, complete genome,
of which we are focussing only on integrated prophage 5 (similar length).

You can download these using Entrez if you like, see Section 9.6
for more details. For the third record we’ve worked out where the phage is
integrated into the genome, and slice the record to extract it (with the
features preserved, see Section 4.6), and must also
reverse complement to match the orientation of the first two phage (again
preserving the features, see Section 4.8):

The figure we are imitating used different colors for different gene functions.
One way to do this is to edit the GenBank file to record color preferences for
each feature - something Sanger’s Artemis editor does, and which GenomeDiagram should understand. Here
however, we’ll just hard code three lists of colors.

Note that the annotation in the GenBank files doesn’t exactly match that shown
in Proux et al., they have drawn some unannotated genes.

I did wonder why in the original manuscript there were no red or orange genes
marked in the bottom phage. Another important point is here the phage are
shown with different lengths - this is because they are all drawn to the same
scale (they are different lengths).

The key difference from the published figure is they have color-coded links
between similar proteins – which is what we will do in the next section.

Biopython 1.59 added the ability to draw cross links between tracks - both
simple linear diagrams as we will show here, but also linear diagrams split
into fragments and circular diagrams.

Continuing the example from the previous section inspired by Figure 6 from
Proux et al. 2002 [5],
we would need a list of cross links between pairs of genes, along with a score
or color to use. Realistically you might extract this from a BLAST file
computationally, but here I have manually typed them in.

My naming convention continues to refer to the three phage as A, B and C.
Here are the links we want to show between A and B, given as a list of
tuples (percentage similarity score, gene in A, gene in B).

For the first and last phage these identifiers are locus tags, for the middle
phage there are no locus tags so I’ve used gene names instead. The following
little helper function lets us lookup a feature using either a locus tag or
gene name:

def get_feature(features, id, tags=["locus_tag", "gene"]):
"""Search list of SeqFeature objects for an identifier under the given tags."""
for f in features:
for key in tags:
#tag may not be present in this feature
for x in f.qualifiers.get(key, []):
if x == id:
return f
raise KeyError(id)

We can now turn those list of identifier pairs into SeqFeature pairs, and thus
find their location co-ordinates. We can now add all that code and the following
snippet to the previous example (just before the gd_diagram.draw(...)
line – see the finished example script
Proux_et_al_2002_Figure_6.py
included in the Doc/examples folder of the Biopython source code)
to add cross links to the figure:

There are several important pieces to this code. First the GenomeDiagram object
has a cross_track_links attribute which is just a list of CrossLink objects.
Each CrossLink object takes two sets of track-specific co-ordinates (here given
as tuples, you can alternatively use a GenomeDiagram.Feature object instead).
You can optionally supply a colour, border color, and say if this link should be drawn
flipped (useful for showing inversions).

You can also see how we turn the BLAST percentage identity score into a colour,
interpolating between white (0%) and a dark red (100%). In this example
we don’t have any problems with overlapping cross-links. One way to tackle that
is to use transparency in ReportLab, by using colors with their alpha channel set.
However, this kind of shaded color scheme combined with overlap transparency
would be difficult to interpret.
The result:

There is still a lot more that can be done within Biopython to help
improve this figure. First of all, the cross links in this case are
between proteins which are drawn in a strand specific manor. It can
help to add a background region (a feature using the ‘BOX’ sigil) on the
feature track to extend the cross link. Also, we could reduce the vertical
height of the feature tracks to allocate more to the links instead – one
way to do that is to allocate space for empty tracks. Furthermore,
in cases like this where there are no large gene overlaps, we can use
the axis-straddling BIGARROW sigil, which allows us to further
reduce the vertical space needed for the track. These improvements
are demonstrated in the example script
Proux_et_al_2002_Figure_6.py
included in the Doc/examples folder of the Biopython source code.
The result:

Beyond that, finishing touches you might want to do manually in a vector
image editor include fine tuning the placement of gene labels, and adding
other custom annotation such as highlighting particular regions.

Although not really necessary in this example since none of the cross-links
overlap, using a transparent color in ReportLab is a very useful technique
for superimposing multiple links. However, in this case a shaded color
scheme should be avoided.

You can control the tick marks to show the scale – after all every graph
should show its units, and the number of the grey-track labels.

Also, we have only used the FeatureSet so far. GenomeDiagram also has
a GraphSet which can be used for show line graphs, bar charts and heat
plots (e.g. to show plots of GC% on a track parallel to the features).

These options are not covered here yet, so for now we refer you to the
User Guide (PDF) included with the standalone version of GenomeDiagram (but
please read the next section first), and the docstrings.

If you have old code written using the standalone version of GenomeDiagram, and
you want to switch it over to using the new version included with Biopython then
you will have to make a few changes - most importantly to your import statements.

Also, the older version of GenomeDiagram used only the UK spellings of color and
center (colour and centre). You will need to change to the American spellings,
although for several years the Biopython version of GenomeDiagram supported both.

If you run into difficulties, please ask on the Biopython mailing list for
advice. One catch is that we have not included the old module
GenomeDiagram.GDUtilities yet. This included a number of
GC% related functions, which will probably be merged under
Bio.SeqUtils later on.

Here is a very simple example - for which we’ll use Arabidopsis thaliana.

You can skip this bit, but first I downloaded the five sequenced chromosomes
from the NCBI’s FTP site
ftp://ftp.ncbi.nlm.nih.gov/genomes/Arabidopsis_thaliana and then parsed
them with Bio.SeqIO to find out their lengths. You could use the
GenBank files for this, but it is faster to use the FASTA files for the
whole chromosomes:

Continuing from the previous example, let’s also show the tRNA genes.
We’ll get their locations by parsing the GenBank files for the five
Arabidopsis thaliana chromosomes. You’ll need to download these
files from the NCBI FTP site
ftp://ftp.ncbi.nlm.nih.gov/genomes/Arabidopsis_thaliana,
and preserve the subdirectory names or edit the paths below:

KEGG (http://www.kegg.jp/) is a database resource for understanding high-level functions and utilities of the biological system, such as the cell, the organism and the ecosystem, from molecular-level information, especially large-scale molecular datasets generated by genome sequencing and other high-throughput experimental technologies.

Please note that the KEGG parser implementation in Biopython is incomplete. While the KEGG website indicates many flat file formats, only parsers and writers for compound, enzyme, and map are currently implemented. However, a generic parser is implemented to handle the other formats.

Biopython has full support for the querying of the KEGG api. Querying all KEGG endpoints are supported; all methods documented by KEGG (http://www.kegg.jp/kegg/rest/keggapi.html) are supported. The interface has some validation of queries which follow rules defined on the KEGG site. However, invalid queries which return a 400 or 404 must be handled by the user.

First, here is how to extend the above example by downloading the relevant enzyme and passing it through the Enzyme parser.

Now, here’s a more realistic example which shows a combination of querying the KEGG API. This will demonstrate how to extract a unique set of all human pathway gene symbols which relate to DNA repair. The steps that need to be taken to do so are as follows. First, we need to get a list of all human pathways. Secondly, we need to filter those for ones which relate to "repair". Lastly, we need to get a list of all the gene symbols in all repair pathways.

The KEGG API wrapper is compatible with all endpoints. Usage is essentially replacing all slashes in the url with commas and using that list as arguments to the corresponding method in the KEGG module. Here are a few examples from the api documentation (http://www.kegg.jp/kegg/docs/keggapi.html).

Biopython now has two collections of “cookbook” examples – this chapter
(which has been included in this tutorial for many years and has gradually
grown), and http://biopython.org/wiki/Category:Cookbook which is a
user contributed collection on our wiki.

We’re trying to encourage Biopython users to contribute their own examples
to the wiki. In addition to helping the community, one direct benefit of
sharing an example like this is that you could also get some feedback on
the code from other Biopython users and developers - which could help you
improve all your Python code.

In the long term, we may end up moving all of the examples in this chapter
to the wiki, or elsewhere within the tutorial.

Often you’ll have a large file with many sequences in it (e.g. FASTA file
or genes, or a FASTQ or SFF file of reads), a separate shorter list of
the IDs for a subset of sequences of interest, and want to make a new
sequence file for this subset.

Let’s say the list of IDs is in a simple text file, as the first word on
each line. This could be a tabular file where the first column is the ID.
Try something like this:

Let’s suppose you are looking at genome sequence, hunting for some sequence
feature – maybe extreme local GC% bias, or possible restriction digest sites.
Once you’ve got your Python code working on the real genome it may be sensible
to try running the same search on randomised versions of the same genome for
statistical analysis (after all, any “features” you’ve found could just be
there just by chance).

For this discussion, we’ll use the GenBank file for the pPCP1 plasmid from
Yersinia pestis biovar Microtus. The file is included with the
Biopython unit tests under the GenBank folder, or you can get it from our
website, NC_005816.gb.
This file contains one and only one record, so we can read it in as a
SeqRecord using the Bio.SeqIO.read() function:

So, how can we generate a shuffled versions of the original sequence? I would
use the built in Python random module for this, in particular the function
random.shuffle – but this works on a Python list. Our sequence is a
Seq object, so in order to shuffle it we need to turn it into a list:

Now, in order to use Bio.SeqIO to output the shuffled sequence, we need
to construct a new SeqRecord with a new Seq object using this
shuffled list. In order to do this, we need to turn the list of nucleotides
(single letter strings) into a long string – the standard Python way to do
this is with the string object’s join method.

Suppose you’ve got an input file of CDS entries for some organism, and you
want to generate a new FASTA file containing their protein sequences. i.e.
Take each nucleotide sequence from the original file, and translate it.
Back in Section 3.9 we saw how to use the Seq
object’s translate method, and the optional cds argument
which enables correct translation of alternative start codons.

We can combine this with Bio.SeqIO as
shown in the reverse complement example in Section 5.5.3.
The key point is that for each nucleotide SeqRecord, we need to create
a protein SeqRecord - and take care of naming it.

You can write you own function to do this, choosing suitable protein identifiers
for your sequences, and the appropriate genetic code. In this example we just
use the default table and add a prefix to the identifier:

This should work on any FASTA file of complete coding sequences.
If you are working on partial coding sequences, you may prefer to use
nuc_record.seq.translate(to_stop=True) in the example above, as
this wouldn’t check for a valid start codon etc.

Often you’ll get data from collaborators as FASTA files, and sometimes the
sequences can be in a mixture of upper and lower case. In some cases this is
deliberate (e.g. lower case for poor quality regions), but usually it is not
important. You may want to edit the file to make everything consistent (e.g.
all upper case), and you can do this easily using the upper() method
of the SeqRecord object (added in Biopython 1.55):

How does this work? The first line is just importing the Bio.SeqIO
module. The second line is the interesting bit – this is a Python
generator expression which gives an upper case version of each record
parsed from the input file (mixed.fas). In the third line we give
this generator expression to the Bio.SeqIO.write() function and it
saves the new upper cases records to our output file (upper.fas).

The reason we use a generator expression (rather than a list or list
comprehension) is this means only one record is kept in memory at a time.
This can be really important if you are dealing with large files with
millions of entries.

The only clever bit is specifying a comparison function for how to
sort the records (here we sort them by length). If you wanted the
longest records first, you could flip the comparison or use the
reverse argument:

Now that’s pretty straight forward - but what happens if you have a
very large file and you can’t load it all into memory like this?
For example, you might have some next-generation sequencing reads
to sort by length. This can be solved using the
Bio.SeqIO.index() function.

First we scan through the file once using Bio.SeqIO.parse(),
recording the record identifiers and their lengths in a list of tuples.
We then sort this list to get them in length order, and discard the lengths.
Using this sorted list of identifiers Bio.SeqIO.index() allows us to
retrieve the records one by one, and we pass them to Bio.SeqIO.write()
for output.

These examples all use Bio.SeqIO to parse the records into
SeqRecord objects which are output using Bio.SeqIO.write().
What if you want to sort a file format which Bio.SeqIO.write() doesn’t
support, like the plain text SwissProt format? Here is an alternative
solution using the get_raw() method added to Bio.SeqIO.index()
in Biopython 1.54 (see Section 5.4.2.2).

The FASTQ file format was introduced at Sanger and is now widely used for
holding nucleotide sequencing reads together with their quality scores.
FASTQ files (and the related QUAL files) are an excellent example of
per-letter-annotation, because for each nucleotide in the sequence there is
an associated quality score. Any per-letter-annotation is held in a
SeqRecord in the letter_annotations dictionary as a list,
tuple or string (with the same number of elements as the sequence length).

One common task is taking a large set of sequencing reads and filtering them
(or cropping them) based on their quality scores.
The following example is very simplistic, but should illustrate the basics of
working with quality data in a SeqRecord object. All we are going to
do here is read in a file of FASTQ data, and filter it to pick out only those
records whose PHRED quality scores are all above some threshold (here 20).

This pulled out only 14580 reads out of the 41892 present.
A more sensible thing to do would be to quality trim the reads, but this
is intended as an example only.

FASTQ files can contain millions of entries, so it is best to avoid loading
them all into memory at once. This example uses a generator expression, which
means only one SeqRecord is created at a time - avoiding any memory
limitations.

For this example we’re going to pretend that GATGACGGTGT is a 5’ primer
sequence we want to look for in some FASTQ formatted read data. As in the example
above, we’ll use the SRR020192.fastq file downloaded from the ENA
(ftp://ftp.sra.ebi.ac.uk/vol1/fastq/SRR020/SRR020192/SRR020192.fastq.gz).
The same approach would work with any other supported file format (e.g. FASTA files).

This code uses Bio.SeqIO with a generator expression (to avoid loading
all the sequences into memory at once), and the Seq object’s
startswith method to see if the read starts with the primer sequence:

That should find 13819 reads from SRR014849.fastq and save them to
a new FASTQ file, with_primer.fastq.

Now suppose that instead you wanted to make a FASTQ file containing these reads
but with the primer sequence removed? That’s just a small change as we can slice the
SeqRecord (see Section 4.6) to remove the first eleven
letters (the length of our primer):

Again, that should pull out the 13819 reads from SRR020192.fastq,
but this time strip off the first ten characters, and save them to another new
FASTQ file, with_primer_trimmed.fastq.

Finally, suppose you want to create a new FASTQ file where these reads have
their primer removed, but all the other reads are kept as they were?
If we want to still use a generator expression, it is probably clearest to
define our own trim function:

This takes longer, as this time the output file contains all 41892 reads.
Again, we’re used a generator expression to avoid any memory problems.
You could alternatively use a generator function rather than a generator
expression.

Because we are using a FASTQ input file in this example, the SeqRecord
objects have per-letter-annotation for the quality scores. By slicing the
SeqRecord object the appropriate scores are used on the trimmed
records, so we can output them as a FASTQ file too.

Compared to the output of the previous example where we only looked for
a primer/adaptor at the start of each read, you may find some of the
trimmed reads are quite short after trimming (e.g. if the adaptor was
found in the middle rather than near the start). So, let’s add a minimum
length requirement as well:

By changing the format names, you could apply this to FASTA files instead.
This code also could be extended to do a fuzzy match instead of an exact
match (maybe using a pairwise alignment, or taking into account the read
quality scores), but that will be much slower.

Back in Section 5.5.2 we showed how to use
Bio.SeqIO to convert between two file formats. Here we’ll go into a
little more detail regarding FASTQ files which are used in second generation
DNA sequencing. Please refer to Cock et al. (2009) [7]
for a longer description. FASTQ files store both the DNA sequence (as a string)
and the associated read qualities.

PHRED scores (used in most FASTQ files, and also in QUAL files, ACE files
and SFF files) have become a de facto standard for representing
the probability of a sequencing error (here denoted by Pe) at a given
base using a simple base ten log transformation:

QPHRED = − 10 × log10 ( Pe )
(18.1)

This means a wrong read (Pe = 1) gets a PHRED quality of 0, while a very
good read like Pe = 0.00001 gets a PHRED quality of 50. While for raw
sequencing data qualities higher than this are rare, with post processing
such as read mapping or assembly, qualities of up to about 90 are possible
(indeed, the MAQ tool allows for PHRED scores in the range 0 to 93 inclusive).

The FASTQ format has the potential to become a de facto standard for
storing the letters and quality scores for a sequencing read in a single plain
text file. The only fly in the ointment is that there are at least three
versions of the FASTQ format which are incompatible and difficult to
distinguish...

The original Sanger FASTQ format uses PHRED qualities encoded with an
ASCII offset of 33. The NCBI are using this format in their Short Read
Archive. We call this the fastq (or fastq-sanger) format
in Bio.SeqIO.

Solexa (later bought by Illumina) introduced their own version using
Solexa qualities encoded with an ASCII offset of 64. We call this the
fastq-solexa format.

Illumina pipeline 1.3 onwards produces FASTQ files with PHRED qualities
(which is more consistent), but encoded with an ASCII offset of 64. We call
this the fastq-illumina format.

The Solexa quality scores are defined using a different log transformation:

QSolexa = − 10 × log10

⎛
⎜
⎜
⎝

Pe

1−Pe

⎞
⎟
⎟
⎠

(18.2)

Given Solexa/Illumina have now moved to using PHRED scores in version 1.3 of
their pipeline, the Solexa quality scores will gradually fall out of use.
If you equate the error estimates (Pe) these two equations allow conversion
between the two scoring systems - and Biopython includes functions to do this
in the Bio.SeqIO.QualityIO module, which are called if you use
Bio.SeqIO to convert an old Solexa/Illumina file into a standard Sanger
FASTQ file:

Note that using Bio.SeqIO.convert() like this is much faster
than combining Bio.SeqIO.parse() and Bio.SeqIO.write()
because optimised code is used for converting between FASTQ variants
(and also for FASTQ to FASTA conversion).

For good quality reads, PHRED and Solexa scores are approximately equal,
which means since both the fasta-solexa and fastq-illumina
formats use an ASCII offset of 64 the files are almost the same. This was a
deliberate design choice by Illumina, meaning applications expecting the old
fasta-solexa style files will probably be OK using the newer
fastq-illumina files (on good data). Of course, both variants are
very different from the original FASTQ standard as used by Sanger,
the NCBI, and elsewhere (format name fastq or fastq-sanger).

FASTQ files hold both sequences and their quality strings.
FASTA files hold just sequences, while QUAL files hold just
the qualities. Therefore a single FASTQ file can be converted to or from
paired FASTA and QUAL files.

However, the reverse is a little more tricky. You can use Bio.SeqIO.parse()
to iterate over the records in a single file, but in this case we have
two input files. There are several strategies possible, but assuming that the
two files are really paired the most memory efficient way is to loop over both
together. The code is a little fiddly, so we provide a function called
PairedFastaQualIterator in the Bio.SeqIO.QualityIO module to do
this. This takes two handles (the FASTA file and the QUAL file) and returns
a SeqRecord iterator:

from Bio.SeqIO.QualityIO import PairedFastaQualIterator
for record in PairedFastaQualIterator(open("example.fasta"), open("example.qual")):
print(record)

This function will check that the FASTA and QUAL files are consistent (e.g.
the records are in the same order, and have the same sequence length).
You can combine this with the Bio.SeqIO.write() function to convert a
pair of FASTA and QUAL files into a single FASTQ files:

FASTQ files are often very large, with millions of reads in them. Due to the
sheer amount of data, you can’t load all the records into memory at once.
This is why the examples above (filtering and trimming) iterate over the file
looking at just one SeqRecord at a time.

However, sometimes you can’t use a big loop or an iterator - you may need
random access to the reads. Here the Bio.SeqIO.index() function
may prove very helpful, as it allows you to access any read in the FASTQ file
by its name (see Section 5.4.2).

If you work with 454 (Roche) sequence data, you will probably have access
to the raw data as a Standard Flowgram Format (SFF) file. This contains
the sequence reads (called bases) with quality scores and the original
flow information.

A common task is to convert from SFF to a pair of FASTA and QUAL files,
or to a single FASTQ file. These operations are trivial using the
Bio.SeqIO.convert() function (see Section 5.5.2):

Remember the convert function returns the number of records, in
this example just ten. This will give you the untrimmed reads, where
the leading and trailing poor quality sequence or adaptor will be in lower
case. If you want the trimmed reads (using the clipping information
recorded within the SFF file) use this:

If you run Linux, you could ask Roche for a copy of their “off instrument”
tools (often referred to as the Newbler tools). This offers an alternative way to
do SFF to FASTA or QUAL conversion at the command line (but currently FASTQ output
is not supported), e.g.

A very simplistic first step at identifying possible genes is to look for
open reading frames (ORFs). By this we mean look in all six frames for long
regions without stop codons – an ORF is just a region of nucleotides with
no in frame stop codons.

Of course, to find a gene you would also need to worry about locating a start
codon, possible promoters – and in Eukaryotes there are introns to worry about
too. However, this approach is still useful in viruses and Prokaryotes.

To show how you might approach this with Biopython, we’ll need a sequence to
search, and as an example we’ll again use the bacterial plasmid – although
this time we’ll start with a plain FASTA file with no pre-marked genes:
NC_005816.fna. This is a bacterial sequence, so we’ll want to use
NCBI codon table 11 (see Section 3.9 about translation).

Note that here we are counting the frames from the 5’ end (start) of
each strand. It is sometimes easier to always count from the 5’ end
(start) of the forward strand.

You could easily edit the above loop based code to build up a list of the
candidate proteins, or convert this to a list comprehension. Now, one thing
this code doesn’t do is keep track of where the proteins are.

You could tackle this in several ways. For example, the following code tracks
the locations in terms of the protein counting, and converts back to the
parent sequence by multiplying by three, then adjusting for the frame and
strand:

If you comment out the sort statement, then the protein sequences will be
shown in the same order as before, so you can check this is doing the same
thing. Here we have sorted them by location to make it easier to compare
to the actual annotation in the GenBank file (as visualised in
Section 16.1.9).

If however all you want to find are the locations of the open reading frames,
then it is a waste of time to translate every possible codon, including doing
the reverse complement to search the reverse strand too. All you need to do
is search for the possible stop codons (and their reverse complements). Using
regular expressions is an obvious approach here (see the Python module
re). These are an extremely powerful (but rather complex) way of
describing search strings, which are supported in lots of programming
languages and also command line tools like grep as well). You can
find whole books about this topic!

This section shows some more examples of sequence parsing, using the Bio.SeqIO
module described in Chapter 5, plus the Python library matplotlib’s pylab plotting interface (see the matplotlib website for a tutorial). Note that to follow these examples you will need matplotlib installed - but without it you can still try the data parsing bits.

There are lots of times when you might want to visualise the distribution of sequence
lengths in a dataset – for example the range of contig sizes in a genome assembly
project. In this example we’ll reuse our orchid FASTA file ls_orchid.fasta which has only 94 sequences.

First of all, we will use Bio.SeqIO to parse the FASTA file and compile a list
of all the sequence lengths. You could do this with a for loop, but I find a list
comprehension more pleasing:

Another easily calculated quantity of a nucleotide sequence is the GC%. You might
want to look at the GC% of all the genes in a bacterial genome for example, and
investigate any outliers which could have been recently acquired by horizontal gene
transfer. Again, for this example we’ll reuse our orchid FASTA file ls_orchid.fasta.

First of all, we will use Bio.SeqIO to parse the FASTA file and compile a list
of all the GC percentages. Again, you could do this with a for loop, but I prefer this:

A dot plot is a way of visually comparing two nucleotide sequences for similarity to
each other. A sliding window is used to compare short sub-sequences to each other,
often with a mis-match threshold. Here for simplicity we’ll only look for perfect
matches (shown in black
in the plot below).

To start off, we’ll need two sequences. For the sake of argument, we’ll just take
the first two from our orchid FASTA file ls_orchid.fasta:

We’re going to show two approaches. Firstly, a simple naive implementation
which compares all the window sized sub-sequences to each other to compiles a
similarity matrix. You could construct a matrix or array object, but here we
just use a list of lists of booleans created with a nested list
comprehension:

Note that we have not checked for reverse complement matches here.
Now we’ll use the matplotlib’s pylab.imshow() function to display this
data, first requesting the gray color scheme so this is done in black and
white:

As you might have expected, these two sequences are very similar with a
partial line of window sized matches along the diagonal. There are no off
diagonal matches which would be indicative of inversions or other interesting
events.

The above code works fine on small examples, but there are two problems
applying this to larger sequences, which we will address below.
First off all, this brute force approach to the all against all comparisons
is very slow. Instead, we’ll compile dictionaries mapping the window sized
sub-sequences to their locations, and then take the set intersection to find
those sub-sequences found in both sequences. This uses more memory, but is
much faster. Secondly, the pylab.imshow() function is limited
in the size of matrix it can display. As an alternative, we’ll use the
pylab.scatter() function.

We start by creating dictionaries mapping the window-sized sub-sequences to locations:

Personally I find this second plot much easier to read!
Again note that we have not checked for reverse complement matches here
– you could extend this example to do this, and perhaps plot the forward
matches in one color and the reverse matches in another.

In the following code the pylab.subplot(...) function is used in order to show
the forward and reverse qualities on two subplots, side by side. There is also a little
bit of code to only plot the first fifty reads.

You should note that we are using the Bio.SeqIO format name fastq
here because the NCBI has saved these reads using the standard Sanger FASTQ format
with PHRED scores. However, as you might guess from the read lengths, this data was
from an Illumina Genome Analyzer and was probably originally in one of the two
Solexa/Illumina FASTQ variant file formats instead.

This example uses the pylab.savefig(...) function instead of
pylab.show(...), but as mentioned before both are useful.
Here is the result:

Once you have an alignment, you are very likely going to want to find out information about it. Instead of trying to have all of the functions that can generate information about an alignment in the alignment object itself, we’ve tried to separate out the functionality into separate classes, which act on the alignment.

Getting ready to calculate summary information about an object is quick to do. Let’s say we’ve got an alignment object called alignment, for example read in using Bio.AlignIO.read(...) as described in Chapter 6. All we need to do to get an object that will calculate summary information is:

The SummaryInfo object, described in section 18.3.1, provides functionality to calculate a quick consensus of an alignment. Assuming we’ve got a SummaryInfo object called summary_align we can calculate a consensus by doing:

consensus = summary_align.dumb_consensus()

As the name suggests, this is a really simple consensus calculator, and will just add up all of the residues at each point in the consensus, and if the most common value is higher than some threshold value will add the common residue to the consensus. If it doesn’t reach the threshold, it adds an ambiguity character to the consensus. The returned consensus object is Seq object whose alphabet is inferred from the alphabets of the sequences making up the consensus. So doing a print consensus would give:

Position specific score matrices (PSSMs) summarize the alignment information in a different way than a consensus, and may be useful for different tasks. Basically, a PSSM is a count matrix. For each column in the alignment, the number of each alphabet letters is counted and totaled. The totals are displayed relative to some representative sequence along the left axis. This sequence may be the consesus sequence, but can also be any sequence in the alignment. For instance for the alignment,

GTATC
AT--C
CTGTC

the PSSM is:

G A T C
G 1 1 0 1
T 0 0 3 0
A 1 1 0 0
T 0 0 2 0
C 0 0 0 3

Let’s assume we’ve got an alignment object called c_align. To get a PSSM with the consensus sequence along the side we first get a summary object and calculate the consensus sequence:

To maintain strictness with the alphabets, you can only include characters along the top of the PSSM that are in the alphabet of the alignment object. Gaps are not included along the top axis of the PSSM.

The sequence passed to be displayed along the left side of the axis does not need to be the consensus. For instance, if you wanted to display the second sequence in the alignment along this axis, you would need to do:

You can access any element of the PSSM by subscripting like your_pssm[sequence_number][residue_count_name]. For instance, to get the counts for the ’A’ residue in the second element of the above PSSM you would do:

>>> print(my_pssm[1]["A"])
7.0

The structure of the PSSM class hopefully makes it easy both to access elements and to pretty print the matrix.

A potentially useful measure of evolutionary conservation is the information content of a sequence.

A useful introduction to information theory targeted towards molecular biologists can be found at http://www.lecb.ncifcrf.gov/~toms/paper/primer/. For our purposes, we will be looking at the information content of a consesus sequence, or a portion of a consensus sequence. We calculate information content at a particular column in a multiple sequence alignment using the following formula:

ICj =

Na

∑

i=1

Pijlog

⎛
⎜
⎜
⎝

Pij

Qi

⎞
⎟
⎟
⎠

where:

ICj – The information content for the j-th column in an alignment.

Na – The number of letters in the alphabet.

Pij – The frequency of a particular letter i in the j-th column (i. e. if G occurred 3 out of 6 times in an aligment column, this would be 0.5)

Qi – The expected frequency of a letter i. This is an
optional argument, usage of which is left at the user’s
discretion. By default, it is automatically assigned to 0.05 = 1/20 for a
protein alphabet, and 0.25 = 1/4 for a nucleic acid alphabet. This is for
geting the information content without any assumption of prior
distributions. When assuming priors, or when using a non-standard
alphabet, you should supply the values for Qi.

Well, now that we have an idea what information content is being calculated in Biopython, let’s look at how to get it for a particular region of the alignment.

First, we need to use our alignment to get an alignment summary object, which we’ll assume is called summary_align (see section 18.3.1) for instructions on how to get this. Once we’ve got this object, calculating the information content for a region is as easy as:

Wow, that was much easier then the formula above made it look! The variable info_content now contains a float value specifying the information content over the specified region (from 5 to 30 of the alignment). We specifically ignore the ambiguity residue ’N’ when calculating the information content, since this value is not included in our alphabet (so we shouldn’t be interested in looking at it!).

As mentioned above, we can also calculate relative information content by supplying the expected frequencies:

expect_freq = {
'A' : .3,
'G' : .2,
'T' : .3,
'C' : .2}

The expected should not be passed as a raw dictionary, but instead by passed as a SubsMat.FreqTable object (see section 20.2.2 for more information about FreqTables). The FreqTable object provides a standard for associating the dictionary with an Alphabet, similar to how the Biopython Seq class works.

To create a FreqTable object, from the frequency dictionary you just need to do:

Well, now you are ready to calculate information content. If you want to try applying this to some real life problems, it would probably be best to dig into the literature on information content to get an idea of how it is used. Hopefully your digging won’t reveal any mistakes made in coding this function!

Substitution matrices are an extremely important part of everyday bioinformatics work. They provide the scoring terms for classifying how likely two different residues are to substitute for each other. This is essential in doing sequence comparisons. The book “Biological Sequence Analysis” by Durbin et al. provides a really nice introduction to Substitution Matrices and their uses. Some famous substitution matrices are the PAM and BLOSUM series of matrices.

Biopython provides a ton of common substitution matrices, and also provides functionality for creating your own substitution matrices.

A very cool thing that you can do easily with the substitution matrix
classes is to create your own substitution matrix from an
alignment. In practice, this is normally done with protein
alignments. In this example, we’ll first get a Biopython alignment
object and then get a summary object to calculate info about the
alignment. The file containing protein.aln
(also available online
here)
contains the Clustalw alignment output.

Now that we’ve got our summary_align object, we want to use it
to find out the number of times different residues substitute for each
other. To make the example more readable, we’ll focus on only amino
acids with polar charged side chains. Luckily, this can be done easily
when generating a replacement dictionary, by passing in all of the
characters that should be ignored. Thus we’ll create a dictionary of
replacements for only charged polar amino acids using:

This information gives us our accepted number of replacements, or how
often we expect different things to substitute for each other. It
turns out, amazingly enough, that this is all of the information we
need to go ahead and create a substitution matrix. First, we use the
replacement dictionary information to create an Accepted Replacement
Matrix (ARM):

>>> from Bio import SubsMat
>>> my_arm = SubsMat.SeqMat(replace_info)

With this accepted replacement matrix, we can go right ahead and
create our log odds matrix (i. e. a standard type Substitution Matrix):

>>> my_lom = SubsMat.make_log_odds_matrix(my_arm)

The log odds matrix you create is customizable with the following
optional arguments:

exp_freq_table – You can pass a table of expected
frequencies for each alphabet. If supplied, this will be used
instead of the passed accepted replacement matrix when calculate
expected replacments.

logbase - The base of the logarithm taken to create the
log odd matrix. Defaults to base 10.

factor - The factor to multiply each matrix entry
by. This defaults to 10, which normally makes the matrix numbers
easy to work with.

round_digit - The digit to round to in the matrix. This
defaults to 0 (i. e. no digits).

Once you’ve got your log odds matrix, you can display it prettily
using the function print_mat. Doing this on our created matrix
gives:

BioSQL is a joint effort between the
OBF projects (BioPerl, BioJava etc) to support a
shared database schema for storing sequence data. In theory, you could load a
GenBank file into the database with BioPerl, then using Biopython extract this
from the database as a record object with features - and get more or less the same
thing as if you had loaded the GenBank file directly as a SeqRecord using
Bio.SeqIO (Chapter 5).

Biopython has a regression testing framework (the file
run_tests.py) based on
unittest,
the standard unit testing framework for Python. Providing comprehensive
tests for modules is one of the most important aspects of making sure that
the Biopython code is as bug-free as possible before going out.
It also tends to be one of the most undervalued aspects of contributing.
This chapter is designed to make running the Biopython tests and
writing good test code as easy as possible.
Ideally, every module that goes into Biopython
should have a test (and should also have documentation!).
All our developers, and anyone installing Biopython from source,
are strongly encouraged to run the unit tests.

When you download the Biopython source code, or check it out from
our source code repository, you should find a subdirectory call
Tests. This contains the key script run_tests.py,
lots of individual scripts named test_XXX.py, a subdirectory
called output and lots of other subdirectories which
contain input files for the test suite.

As part of building and installing Biopython you will typically
run the full test suite at the command line from the Biopython
source top level directory using the following:

python setup.py test

This is actually equivalent to going to the Tests
subdirectory and running:

python run_tests.py

You’ll often want to run just some of the tests, and this is done
like this:

python run_tests.py test_SeqIO.py test_AlignIO.py

When giving the list of tests, the .py extension is optional,
so you can also just type:

By default, run_tests.py runs all tests, including the docstring tests.

If an individual test is failing, you can also try running it
directly, which may give you more information.

Importantly, note that the individual unit tests come in two types:

Simple print-and-compare scripts. These unit tests are
essentially short example Python programs, which print out
various output text. For a test file named test_XXX.py
there will be a matching text file called test_XXX under
the output subdirectory which contains the expected
output. All that the test framework does to is run the script,
and check the output agrees.

Standard unittest- based tests. These will import unittest
and then define unittest.TestCase classes, each with one
or more sub-tests as methods starting with test_ which
check some specific aspect of the code.
These tests should not print any output directly.

Currently, about half of the Biopython tests are unittest-style tests, and half are print-and-compare tests.

Running a simple print-and-compare test directly will usually give lots
of output on screen, but does not check the output matches the expected
output. If the test is failing with an exception error, it should be
very easy to locate where exactly the script is failing.
For an example of a print-and-compare test, try:

python test_SeqIO.py

The unittest-based tests instead show you exactly which sub-section(s) of
the test are failing. For example,

Like most Python projects, you can also use
Tox to run the tests on multiple
Python versions, provided they are already installed in your system.

We do not provide the configuration tox.ini file in our code base because
of difficulties pinning down user-specific settings (e.g. executable names of the
Python versions). You may also only be interested in testing Biopython only against
a subset of the Python versions that we support.

If you are interested in using Tox, you may start with the example tox.ini
shown below:

Using the template above, executing tox will test your Biopython code against
Python2.6, Python2.7, PyPy, Python3.3, Python3.4, and Jython. It assumes that those
Pythons’ executables are named accordingly: python2.6 for Python2.6, and so on.

Let’s say you want to write some tests for a module called Biospam.
This can be a module you wrote, or an existing module that doesn’t have
any tests yet. In the examples below, we assume that
Biospam is a module that does simple math.

Each Biopython test can have three important files and directories involved with it:

test_Biospam.py – The actual test code for your module.

Biospam [optional]– A directory where any necessary input files
will be located. Any output files that will be generated should also
be written here (and preferably cleaned up after the tests are
done) to prevent clogging up the main Tests directory.

output/Biospam – [for print-and-compare tests only] This
file contains the expected output from running test_Biospam.py.
This file is not needed for unittest-style tests, since there
the validation is done in the test script test_Biospam.py itself.

It’s up to you to decide whether you want to write a print-and-compare test script or a unittest-style test script. The important thing is that you cannot mix these two styles in a single test script. Particularly, don’t use unittest features in a print-and-compare test.

Any script with a test_ prefix in the Tests directory will be found and run by run_tests.py. Below, we show an example test script test_Biospam.py both for a print-and-compare test and for a unittest-based test. If you put this script in the Biopython Tests directory, then run_tests.py will find it and execute the tests contained in it:

A print-and-compare style test should be much simpler for beginners
or novices to write - essentially it is just an example script using
your new module.

Here is what you should do to make a print-and-compare test for the
Biospam module.

Write a script called test_Biospam.py

This script should live in the Tests directory

The script should test all of the important functionality
of the module (the more you test the better your test is, of course!).

Try to avoid anything which might be platform specific,
such as printing floating point numbers without using an explicit
formatting string to avoid having too many decimal places
(different platforms can give very slightly different values).

If the script requires files to do the testing, these should go in
the directory Tests/Biospam (if you just need something generic, like
a FASTA sequence file, or a GenBank record, try and use an existing
sample input file instead).

Write out the test output and verify the output to be correct.

There are two ways to do this:

The long way:

Run the script and write its output to a file. On UNIX (including
Linux and Mac OS X) machines, you would do something like:
python test_Biospam.py > test_Biospam which would write the
output to the file test_Biospam.

Manually look at the file test_Biospam to make sure the output is correct. When you are sure it is all right and there are no bugs, you need to quickly edit the test_Biospam file so that the first line is: ‘test_Biospam’ (no quotes).

copy the test_Biospam file to the directory Tests/output

The quick way:

Run python run_tests.py -g test_Biospam.py. The
regression testing framework is nifty enough that it’ll put
the output in the right place in just the way it likes it.

Go to the output (which should be in Tests/output/test_Biospam) and double check the output to make sure it is all correct.

Now change to the Tests directory and run the regression tests
with python run_tests.py. This will run all of the tests, and
you should see your test run (and pass!).

That’s it! Now you’ve got a nice test for your module ready to check in,
or submit to Biopython. Congratulations!

As an example, the test_Biospam.py test script to test the
addition and multiplication functions in the Biospam
module could look as follows:

We generate the corresponding output with python run_tests.py -g test_Biospam.py, and check the output file output/test_Biospam:

test_Biospam
2 + 3 = 5
9 - 1 = 8
2 * 3 = 6
9 * (- 1) = -9

Often, the difficulty with larger print-and-compare tests is to keep track which line in the output corresponds to which command in the test script. For this purpose, it is important to print out some markers to help you match lines in the input script with the generated output.

We want all the modules in Biopython to have unit tests, and a simple
print-and-compare test is better than no test at all. However, although
there is a steeper learning curve, using the unittest framework
gives a more structured result, and if there is a test failure this can
clearly pinpoint which part of the test is going wrong. The sub-tests can
also be run individually which is helpful for testing or debugging.

The unittest-framework has been included with Python since version
2.1, and is documented in the Python Library Reference (which I know you
are keeping under your pillow, as recommended). There is also
online documentaion
for unittest.
If you are familiar with the unittest system (or something similar
like the nose test framework), you shouldn’t have any trouble. You may
find looking at the existing example within Biopython helpful too.

Here’s a minimal unittest-style test script for Biospam,
which you can copy and paste to get started:

In the division tests, we use assertAlmostEqual instead of assertEqual to avoid tests failing due to roundoff errors; see the unittest chapter in the Python documentation for details and for other functionality available in unittest (online reference).

These are the key points of unittest-based tests:

Test cases are stored in classes that derive from
unittest.TestCase and cover one basic aspect of your code

You can use methods setUp and tearDown for any repeated
code which should be run before and after each test method. For example,
the setUp method might be used to create an instance of the object
you are testing, or open a file handle. The tearDown should do any
“tidying up”, for example closing the file handle.

The tests are prefixed with test_ and each test should cover
one specific part of what you are trying to test. You can have as
many tests as you want in a class.

If your module contains docstring tests (see section 19.3),
you may want to include those in the tests to be run. You can do so as
follows by modifying the code under if __name__ == "__main__":
to look like this:

This is only relevant if you want to run the docstring tests when you
execute python test_Biospam.py; with
python run_tests.py, the docstring tests are run automatically
(assuming they are included in the list of docstring tests in
run_tests.py, see the section below).

Python modules, classes and functions support built in documentation using
docstrings. The doctest
framework (included with Python) allows the developer to embed working
examples in the docstrings, and have these examples automatically tested.

Currently only a small part of Biopython includes doctests. The
run_tests.py script takes care of running the doctests.
For this purpose, at the top of the run_tests.py script is a
manually compiled list of modules to test, which
allows us to skip modules with optional external dependencies which may
not be installed (e.g. the Reportlab and NumPy libraries). So, if you’ve
added some doctests to the docstrings in a Biopython module, in order to
have them included in the Biopython test suite, you must update
run_tests.py to include your module. Currently, the relevant part
of run_tests.py looks as follows:

Note that we regard doctests primarily as documentation, so you should
stick to typical usage. Generally complicated examples dealing with error
conditions and the like would be best left to a dedicated unit test.

Note that if you want to write doctests involving file parsing, defining
the file location complicates matters. Ideally use relative paths assuming
the code will be run from the Tests directory, see the
Bio.SeqIO doctests for an example of this.

Many of the older Biopython parsers were built around an event-oriented
design that includes Scanner and Consumer objects.

Scanners take input from a data source and analyze it line by line,
sending off an event whenever it recognizes some information in the
data. For example, if the data includes information about an organism
name, the scanner may generate an organism_name event whenever it
encounters a line containing the name.

Consumers are objects that receive the events generated by Scanners.
Following the previous example, the consumer receives the
organism_name event, and the processes it in whatever manner
necessary in the current application.

This is a very flexible framework, which is advantageous if you want to
be able to parse a file format into more than one representation. For
example, the Bio.GenBank module uses this to construct either
SeqRecord objects or file-format-specific record objects.

More recently, many of the parsers added for Bio.SeqIO and
Bio.AlignIO take a much simpler approach, but only generate a
single object representation (SeqRecord and
MultipleSeqAlignment objects respectively). In some cases the
Bio.SeqIO parsers actually wrap
another Biopython parser - for example, the Bio.SwissProt parser
produces SwissProt format specific record objects, which get converted
into SeqRecord objects.

This module provides a class and a few routines for generating substitution matrices, similar to BLOSUM or PAM matrices, but based on user-provided data. Additionally, you may select a matrix from MatrixInfo.py, a collection of established substitution matrices. The SeqMat class derives from a dictionary:

class SeqMat(dict)

The dictionary is of the form {(i1,j1):n1, (i1,j2):n2,...,(ik,jk):nk} where i, j are alphabet letters, and n is a value.

Attributes

self.alphabet: a class as defined in Bio.Alphabet

self.ab_list: a list of the alphabet’s letters, sorted. Needed mainly for internal purposes

Methods

__init__(self,data=None,alphabet=None, mat_name='', build_later=0):

data: can be either a dictionary, or another SeqMat instance.

alphabet: a Bio.Alphabet instance. If not provided, construct an alphabet from data.

mat_name: matrix name, such as "BLOSUM62" or "PAM250"

build_later: default false. If true, user may supply only alphabet and empty dictionary, if intending to build the matrix later. this skips the sanity check of alphabet size vs. matrix size.

entropy(self,obs_freq_mat)

obs_freq_mat: an observed frequency matrix. Returns the matrix’s entropy, based on the frequency in obs_freq_mat. The matrix instance should be LO or SUBS.

sum(self)

Calculates the sum of values for each letter in the matrix’s alphabet, and returns it as a dictionary of the form {i1: s1, i2: s2,...,in:sn}, where:

i: an alphabet letter;

s: sum of all values in a half-matrix for that letter;

n: number of letters in alphabet.

print_mat(self,f,format="%4d",bottomformat="%4s",alphabet=None)

prints the matrix to file handle f. format is the format field for the matrix values; bottomformat is the format field for the bottom row, containing matrix letters. Example output for a 3-letter alphabet matrix:

A 23
B 12 34
C 7 22 27
A B C

The alphabet optional argument is a string of all characters in the alphabet. If supplied, the order of letters along the axes is taken from the string, rather than by alphabetical order.

Usage

The following section is laid out in the order by which most people wish to generate a log-odds matrix. Of course, interim matrices can be generated and
investigated. Most people just want a log-odds matrix, that’s all.

Generating an Accepted Replacement Matrix

Initially, you should generate an accepted replacement matrix (ARM) from your data. The values in ARM are the counted number of replacements according to your data. The data could be a set of pairs or multiple alignments. So for instance if Alanine was replaced by Cysteine 10 times, and Cysteine by Alanine 12 times, the corresponding ARM entries would be:

('A','C'): 10, ('C','A'): 12

as order doesn’t matter, user can already provide only one entry:

('A','C'): 22

A SeqMat instance may be initialized with either a full (first method of counting: 10, 12) or half (the latter method, 22) matrices. A full protein
alphabet matrix would be of the size 20x20 = 400. A half matrix of that alphabet would be 20x20/2 + 20/2 = 210. That is because same-letter entries don’t
change. (The matrix diagonal). Given an alphabet size of N:

Full matrix size:N*N

Half matrix size: N(N+1)/2

The SeqMat constructor automatically generates a half-matrix, if a full matrix is passed. If a half matrix is passed, letters in the key should be provided in alphabetical order: (’A’,’C’) and not (’C’,A’).

At this point, if all you wish to do is generate a log-odds matrix, please go to the section titled Example of Use. The following text describes the nitty-gritty of internal functions, to be used by people who wish to investigate their nucleotide/amino-acid frequency data more thoroughly.

Generating the observed frequency matrix (OFM)

Use:

OFM = SubsMat._build_obs_freq_mat(ARM)

The OFM is generated from the ARM, only instead of replacement counts, it contains replacement frequencies.

Generating an expected frequency matrix (EFM)

Use:

EFM = SubsMat._build_exp_freq_mat(OFM,exp_freq_table)

exp_freq_table: should be a FreqTable instance. See section 20.2.2 for detailed information on FreqTable. Briefly, the expected frequency table has the frequencies of appearance for each member of the alphabet. It is
implemented as a dictionary with the alphabet letters as keys, and each letter’s frequency as a value. Values sum to 1.

The expected frequency table can (and generally should) be generated from the observed frequency matrix. So in most cases you will generate exp_freq_table using:

read_count(f): read a count file from stream f. Then convert to frequencies

read_freq(f): read a frequency data file from stream f. Of course, we then don’t have the counts, but it is usually the letter frquencies which are interesting.

Example of use:
The expected count of the residues in the database is sitting in a file, whitespace delimited, in the following format (example given for a 3-letter alphabet):

A 35
B 65
C 100

And will be read using the FreqTable.read_count(file_handle) function.

An equivalent frequency file:

A 0.175
B 0.325
C 0.5

Conversely, the residue frequencies or counts can be passed as a dictionary.
Example of a count dictionary (3-letter alphabet):

{'A': 35, 'B': 65, 'C': 100}

Which means that an expected data count would give a 0.5 frequency
for ’C’, a 0.325 probability of ’B’ and a 0.175 probability of ’A’
out of 200 total, sum of A, B and C)

A frequency dictionary for the same data would be:

{'A': 0.175, 'B': 0.325, 'C': 0.5}

Summing up to 1.

When passing a dictionary as an argument, you should indicate whether it is a count or a frequency dictionary. Therefore the FreqTable class constructor requires two arguments: the dictionary itself, and FreqTable.COUNT or FreqTable.FREQ indicating counts or frequencies, respectively.

Read expected counts. readCount will already generate the frequencies
Any one of the following may be done to geerate the frequency table (ftab):

We encourage all our uses to sign up to the main Biopython mailing list.
Once you’ve got the hang of an area of Biopython, we’d encourage you to
help answer questions from beginners. After all, you were a beginner once.

We’re happy to take feedback or contributions - either via a bug-report or on the Mailing List.
While reading this tutorial, perhaps you noticed some topics you were interested in which were missing, or not clearly explained. There is also Biopython’s built in documentation (the docstrings, these are also
online), where again, you may be able to help fill in any blanks.

We currently provide source code archives (suitable for any OS, if you have the right build tools installed), and Windows Installers which are just click and run. This covers all the major operating systems.

Most major Linux distributions have volunteers who take these source code releases, and compile them into packages for Linux users to easily install (taking care of dependencies etc). This is really great and we are of course very grateful. If you would like to contribute to this work, please find out more about how your Linux distribution handles this.

Below are some tips for certain platforms to maybe get people started with helping out:

Windows

– Windows products typically have a nice graphical installer that installs all of the essential components in the right place. We use Distutils to create a installer of this type fairly easily.

You must first make sure you have a C compiler on your Windows computer, and that you can compile and install things (this is the hard bit - see the Biopython installation instructions for info on how to do this).

Once you are setup with a C compiler, making the installer just requires doing:

python setup.py bdist_wininst

Now you’ve got a Windows installer. Congrats! At the moment we have no trouble shipping installers built on 32 bit windows. If anyone would like to look into supporting 64 bit Windows that would be great.

RPMs

– RPMs are pretty popular package systems on some Linux platforms. There is lots of documentation on RPMs available at http://www.rpm.org to help you get started with them. To create an RPM for your platform is really easy. You just need to be able to build the package from source (having a C compiler that works is thus essential) – see the Biopython installation instructions for more info on this.

To make the RPM, you just need to do:

python setup.py bdist_rpm

This will create an RPM for your specific platform and a source RPM in the directory dist. This RPM should be good and ready to go, so this is all you need to do! Nice and easy.

Macintosh

– Since Apple moved to Mac OS X, things have become much easier on the Mac. We generally
treat it as just another Unix variant, and installing Biopython from source is just as easy as on Linux.
The easiest way to get all the GCC compilers etc installed is to install Apple’s X-Code.
We might be able to provide click and run installers for Mac OS X, but to date there hasn’t been any demand.

Once you’ve got a package, please test it on your system to make sure it installs everything in a good way and seems to work properly. Once you feel good about it, send it off to one of the Biopython developers (write to our main mailing list at biopython@biopython.org if you’re not sure who to send it to) and you’ve done it. Thanks!

There are no barriers to joining Biopython code development other
than an interest in creating biology-related code in Python. The
best place to express an interest is on the Biopython mailing lists
– just let us know you are interested in coding and what kind of
stuff you want to work on. Normally, we try to have some discussion
on modules before coding them, since that helps generate good ideas
– then just feel free to jump right in and start coding!

The main Biopython release tries to be fairly uniform and interworkable,
to make it easier for users. You can read about some of (fairly
informal) coding style guidelines we try to use in Biopython in the
contributing documentation at
http://biopython.org/wiki/Contributing. We also try to add code to the distribution along with tests (see Chapter 19 for more info on the regression testing framework) and documentation, so that everything can stay as workable and well documented as possible (including docstrings). This is, of course, the most ideal situation, under many situations you’ll be able to find other people on the list who will be willing to help add documentation or more tests for your code once you make it available. So, to end this paragraph like the last, feel free to start working!

Please note that to make a code contribution you must have the legal right to contribute it and license it under the Biopython license. If you wrote it all yourself, and it is not based on any other code, this shouldn’t be a problem. However, there are issues if you want to contribute a derivative work - for example something based on GPL or LPGL licenced code would not be compatible with our license. If you have any queries on this, please discuss the issue on the biopython-dev mailing list.

Another point of concern for any additions to Biopython regards any build time or run time dependencies. Generally speaking, writing code to interact with a standalone tool (like BLAST, EMBOSS or ClustalW) doesn’t present a big problem. However, any dependency on another library - even a Python library (especially one needed in order to compile and install Biopython like NumPy) would need further discussion.

Additionally, if you have code that you don’t think fits in the
distribution, but that you want to make available, we maintain Script
Central (http://biopython.org/wiki/Scriptcentral)
which has pointers to freely available code in Python for bioinformatics.

Hopefully this documentation has got you excited enough about
Biopython to try it out (and most importantly, contribute!). Thanks
for reading all the way through!

If you haven’t spent a lot of time programming in Python, many
questions and problems that come up in using Biopython are often
related to Python itself. This section tries to present some ideas and
code that come up often (at least for us!) while using the Biopython
libraries. If you have any suggestions for useful pointers that could
go here, please contribute!

Handles are mentioned quite frequently throughout this documentation,
and are also fairly confusing (at least to me!). Basically, you can
think of a handle as being a “wrapper” around text information.

Handles provide (at least) two benefits over plain text information:

They provide a standard way to deal with information stored in
different ways. The text information can be in a file, or in a
string stored in memory, or the output from a command line program,
or at some remote website, but the handle provides a common way of
dealing with information in all of these formats.

They allow text information to be read incrementally, instead
of all at once. This is really important when you are dealing with
huge text files which would use up all of your memory if you had to
load them all.

Handles can deal with text information that is being read (e. g. reading
from a file) or written (e. g. writing information to a file). In the
case of a “read” handle, commonly used functions are read(),
which reads the entire text information from the handle, and
readline(), which reads information one line at a time. For
“write” handles, the function write() is regularly used.

The most common usage for handles is reading information from a file,
which is done using the built-in Python function open. Here, we open a
handle to the file m_cold.fasta
(also available online
here):

Handles are regularly used in Biopython for passing information to parsers.
For example, since Biopython 1.54 the main functions in Bio.SeqIO
and Bio.AlignIO have allowed you to use a filename instead of a
handle:

from Bio import SeqIO
for record in SeqIO.parse("m_cold.fasta", "fasta"):
print(record.id, len(record))