mok0's world

Python for crystallographers 5

Posted in Biopython, Programming, Python, Tutorial by mok0 on February 1, 2012

5 Python for crystallographers 5

This is the fifth and last in a series of tutorials on Python I gave at the Department of Molecular Biology, Aarhus University. It is aimed at crystallographers and structural biologists. This text is a commented transcript of the session log file produced by IPython The transcript does not include the output from Python. You will have to try it yourself.

5.1 Variable function arguments

Variable arguments can be used in a function when the number of arguments that the function needs to process cannot be predicted. The archetypical example is the C printf function, which accepts a format string as the first parameter, and any number of variables following that. In Python, variable function arguments are specified in the function definition by prefixing the name of the formal parameter with an asterisk:

def func(*args):
    print type (args)
    for i in args:
        print i,

From the point of view of the function, the passed parameters are contained in a tuple:

In [6]: func(1,2,'a')
<type 'tuple'>
1 2 a

In [7]: func(1,2,3,4,5,6)
<type 'tuple'>
1 2 3 4 5 6

The function must of course know what to do with the varying number of arguments, and that is the job of the programmer.

5.2 Keyworded function arguments

This section introduces keyworded function arguments.

Keyworded arguments are somewhat similar to variable argument lists from the previous section, however, the function identifies the arguments by the parameter name, and arguments kan be skipped or they can be placed out of order. This is often a convenience to the programmer, and keyworded arguments are typically used to set various options in the function. Keyworded function arguments are specified in the function definition by prefixing the name of the formal parameter with a double asterisk:

def func1 (**kwargs):
    print type(kwargs)
    for k in kwargs:
        print k, kwargs[k],

From the point of view of the function, the passed parameters are contained in a dictionary. Let’s try to call this function using various keyworded arguments (recall that IPython’s %cpaste magic can be used to insert code snippets from the clipboard):

func1(residues=100, atoms=1000)
In [11]: func1(x=1)
<type 'dict'>
x 1

In [12]: func1(residues=100)
<type 'dict'>
residues 100

In [13]: func1(residues=100, atoms=1000)
<type 'dict'>
residues 100 atoms 1000

In [14]: func1(atoms=1000,residues=100)
<type 'dict'>
residues 100 atoms 1000

Quite typically, keyworded arguments are used to set optional parameters, but the function might still want one or more fixed and required parameters. A template example of such a use is given below:

def func2 (a, b, **kwargs):

and an example of a function call might look like this:

func2(filenam, 0.2, atoms=1000,residues=100)

5.3 Exceptions

Python is extremely smart about errors that arise during excecution of programs. When programs written in compiled languages such as C encounter an error, for example if a number is divided by zero, the operating system simply terminates the process. The programmer then needs to track down where the error happened, fix it, and recompile the program.

When running Python interactively, for example via IPython, the process survives, but it throws an exception, meaning that it stops what is was doing when the error happened. But since the process survives, you can examine the content of the variables, for example by printing them, and this can give vital clues about what went wrong. Of course, you can also use the Python debugger which streamlines this process, enables you to set breakpoints in the program and so on. Curiously to crystallographers, the Python debugger is called PDB. However, this subject is outside the scope of this presentation. IPython has a smart interface to the Python debugger, which you are encouraged to check out.

Here, we attempt to divide by zero:

In [15]: 1/0
ZeroDivisionError                         Traceback (most recent call last)

/Users/mok/dropbox/python-course-2011/<ipython console> in <module>()

ZeroDivisionError: integer division or modulo by zero

Python does not like that, and raises an exception named ZeroDivisionError. The programmer can also raise exceptions, both predefined, or home-made exceptions. Here, we try to raise at ZeroDivisionError:

In [16]: raise ZeroDivisionError
ZeroDivisionError                         Traceback (most recent call last)

/Users/mok/dropbox/python-course-2011/<ipython console> in <module>()


It is seen that an exception is thrown, but Python really doesn’t know the reason (there is no associated message.)

The very smart thing about exceptions is that you can catch them, and let the program deal with the unexpected situation. This is done in a
try/except block, for example:

    f = a/b
except ZeroDivisionError:
    print "oops!"

After the try/except block, everything is normal, and the value of f is 5. Let us try again, this time setting b to zero:

b = 0
    f = a/b
    print "oops!"

The output written this time is “oops!”, and the value of f is unchanged (i.e. 5 if you follow the input above.)

5.3.1 The useful SystemExit exception

A quite common construction in a Python main program is to exit in the very beginning, if the user fails to provide the proper command line arguments, or, as in the following example, the specified file does not exist. When the SystemExit exception is raised, the Python process terminates:

    fnam = sys.argv[1]
    if not os.path.exists(fnam):
        print "file not found, duh!"
        raise SystemExit

5.4 Superposition

In this section, we will take a look at the Superimposer() class that comes with Biopython.

The following code is the main program from the Biopython source file Bio/PDB/, that we copy-paste into its own file called (The Python standard programming guidelines encourages use of lower-case letters for file names.)

 1: import sys
 2: from Bio.PDB import PDBParser, Selection, Superimposer
 3: import numpy
 5: if __name__=="__main__":
 7:     p=PDBParser()
 8:     s1=p.get_structure("FIXED", sys.argv[1])
 9:  fixed=Selection.unfold_entities(s1, "A")
11:     s2=p.get_structure("MOVING", sys.argv[1])
12:  moving=Selection.unfold_entities(s2, "A")
14:  rot=numpy.identity(3).astype('f')
15:  tran=numpy.array((1.0, 2.0, 3.0), 'f')
17:  for atom in moving:
18:         atom.transform(rot, tran)
20:     sup=Superimposer()
22:  sup.set_atoms(fixed, moving)
24:     print sup.rotran
25:     print sup.rms
27:  sup.apply(moving)

The above example is only mildly interesting, because it simply superimposes a molecule on a copy of itself, which has been translated by a small amount. The result of the calculation should therefore be the identity matrix, and a small translation in the opposite direction. We will none-the-less go through the program and examine what it’s doing.

The first few lines ought to be familiar by now. The PDB file from the command line is opened twice, and its atoms are placed in two Structure() instances s1 and s2.

In lines 9 and 12 we are using the convenient Selection() class, that can be used to access the various levels of the SMCRA hierachy. We use the method called unfold_entities(), which can unfold a list of entities to a list of entities of another level. For example:

  • list of atoms -> list of residues
  • list of residues -> list of atoms
  • list of residues -> list of chains

In this case, we unfold a Structure() instance to a list of atoms, specified by the “A” in parameter 2. Those lists of atoms are stored in variables moving and fixed.

In line 14 we define the identity matrix, and in line 15 we define a translation vector (1.0, 2.0, 3.0). That rotation/translation operator is applied to the moving list of atoms in line 17, and after this operation all atoms in that list have been shifted by the translation vector given above.

Now we instance the Superimposer() class in the variable sup, and feed two lists of atoms to it (line 22). The rotation/translation operator and root mean squared deviation is printed, and finally, in line 27, the translation in sup is applied to the moving list, which should result in the atoms being shifted back to their original positions.

It is left as an exercise for the reader to generalize this program so it can take two different PDB files and/or two different chains.

5.5 Neighbor search

Now lets take a look at the NeighborSearch class from Biopython. This is a useful class that can search entities (that can be Atom, Residue, etc. objects) within a certain distance.

To remind yourself how smart IPython is (assuming you are running it) let us first check the documentation for NeighborSearch.

from Bio.PDB import NeigborSearch

Recall that IPython has extensive support of Tab-completion. When typing the above, it is actually sufficient to type:


and IPython will automatically expand “Nei” to “NeighborSearch”.

Now, load a Structure object from a PDB file, and as in the previous example, unfold that structure into a list of atoms.

from Bio.PDB import Selection
s = p.get_structure("test", "1zen.pdb")
atoms = Selection.unfold_entities(s, "A")

Now, choose a random atom in that structure. Below, we choose atom number 30, which happens to be the OH atom of residue 3, which is a Tyr. The get_coord() method returns a Numpy array containing that atom’s coordinates.

1: center = atoms[30].get_coord()
2: ns = NeighborSearch(atoms) 
3: print (center, 5, "A") 
4: print (center, 5, "R")

In line 2, we prime an instance ns of the NeighborSearch class with the list of atoms extracted from PDB structure 1zen. Then, in line 3, we print out the list of atoms within 5.0 Å of the center (atom OH of Tyr 3). In the following line, we print the list of residues found by the search within that radius:

[<Residue TYR het=  resseq=3 icode= >,
 <Residue LYS het=  resseq=105 icode= >,
 <Residue GLU het=  resseq=53 icode= >,
 <Residue LYS het=  resseq=52 icode= >]

NeighborSearch is a very useful class solving an often encountered problem, that you can use in your programs.

5.6 Fragment search

For the next example, we will take a look at Biopython’s Fragmentmapper class, and we shall use it to write a small program that performs a calculation more or less like the Lego_ca command in O: step through the polypeptide chain one residue at the time, and find the best fitting fragment from a library of fragments.

The FragmentMapper class requires that you download and install the fragment database first. It consists of a number of text files, that should be placed in a directory somewhere. You can download the fragment library from In the following, it is assumed that these files are placed in a directory called fragment_data in the current working directory, but it could be anywhere on your file system. Here is the program

 1: from Bio.PDB import PDBParser, FragmentMapper, Selection
 2: import sys
 4: if __name__=="__main__":
 6:     p=PDBParser()
 7:     s=p.get_structure("X", sys.argv[1])
 9:     m=s[0]
10:  fm=FragmentMapper(m, 10, 5, "fragment_data")
12:  for r in Selection.unfold_entities(m, "R"):
13:         print r,
14:         if fm.has_key(r):
15:             print fm[r]
16:         else:
17:             print

Most of the elements of this program should be familiar. The program accepts the file name of a PDB entry on the command line. In line 10, the FragmentMapper class is instanced. It receives a Model object, the size of the library (10 in this case), and the length of the fragments (we use 5 here, same as the Lego_* system from O). The last parameter is the directory where the fragment library files are stored.

In the loop starting at line 12 the model m is unfolded residue by residue, and each is looked up in the fragment mapper object, which functions like a Python dictionary. If there is a match, the fragment object is printed. The output of the program looks something like this:

<Residue SER het=  resseq=1 icode= >
<Residue LYS het=  resseq=2 icode= >
<Residue ILE het=  resseq=3 icode= > <Fragment length=5 id=9>
<Residue PHE het=  resseq=4 icode= > <Fragment length=5 id=9>
<Residue ASP het=  resseq=5 icode= > <Fragment length=5 id=7>
<Residue PHE het=  resseq=6 icode= > <Fragment length=5 id=3>

The first two residues don’t have any matches, the first five-residue fragment match is at residue 3, because the position of the match is the central residue of the five. In other words, fragment id 9 is the best match of residues 1-5, and also the best match of residues 2-6, whereas the best match of residues 3-7 is fragment id 7.

5.7 Shell utilities

Finally, we will introduce a very useful module that is distributed with Python. It is the shutil module, containing various utility functions e.g. for copying files and directory trees.

import shutil

Some of the functions available in shutil are:

copy(src, dst)
copy data and mode bits fra src to dst. Same as
“cp src dst” from the command line.
copy2(src, dst)
copy data and all stat info (same as “cp -p src dst”).
move(src, dst)
Recursively move a file or directory to another location.

The shutil module is thus convenient for performing shell-like operations from within Python.

Date: 2012-02-01 12:08:44 CET

HTML generated by org-mode 6.21b in emacs 23


Python for crystallographers 4

Posted in Biopython, Programming, Python, Tutorial by mok0 on January 30, 2012

4 Python for crystallographers 4

This is the fourth in a series of tutorials on Python I gave at the Department of Molecular Biology, Aarhus University. It is aimed at crystallographers and structural biologists. This text is a commented transcript of the session log file produced by IPython The transcript does not include the output from Python. You will have to try it yourself.

4.1 Python modules

We have seen that simple Python modules are often just files containing Python code, typically functions and classes. In presentation 2, we saw the following construct:

from utils import parse_list

that simply imports the function parse_list() from the file This allows the programmer to organize the code in elements that are more easily maintained. However, many large projects are exported as packages. A package is normally a collection of modules, but can also be a single module.

To define a module called course, we can create a directory called course, and in that directory, we place a file called The presence of this file in a directory tells Python that it is a module.

mkdir course/
touch course/

Now, inside Python, we can:

import course

but of course, the module is empty. There are several ways to put code into a module. Most often, is empty, but it can contain Python code. Let us enter the following into the file course/

def hello():
   print "Python is cool"

Now, in IPython, this function can be called:

import course

You can see that the function hello() is now in the modules’ namespace. The directory course can also contain other Python files, which then become part of the module. Let us copy our file from earlier to the new course module:

cp course/

Now, is a part of the course module, and needs to be addressed as a part of that. In Python, we can import the function
parse_list() like this:

from course.utils import parse_list

This imports the function parse_list() directly into the current namespace. However, we can also write:

import course

but then we need to use the fully qualified namespace to access the function which should be called course.utils.parse_list(). It is a matter of taste, and a matter of code clarity, how to use the import statement in your program. As a rule-of-thumb, if you need to use the function many places in your code, it is convinient to import its name into the current namespace. If you only need to call a function (or class) once, it is more clear to leave it fully qualified, because the code then will show its origin.

4.2 The Bio.PDB module

We will now look at the PDB module from Biopython. This module is quite sophisticated, and is supposedely be very well tested. Basically, the PDB module regards a macromolecular structure from a PDB entry as a hierachy called “SMCRA”, which stands for

  • Structure
  • Model
  • Chain
  • Residue
  • Atom

In a typical X-ray structure, the model level is not used, but in a typical NMR structure entry, it is typical to have 20 models or more in one file. Each Model contains one or more chains, each Chain contains one or more residues, and each Residue contains one or more atoms.

The PDB module is designed so it is possible to access this information in several ways. How, exactly, this is done in your program depends on the requirements of the specific application.

4.2.1 Parsing a PDB file

To parse a PDB file we need to instantiate a parser. The parser object has a few methods to access the content of the PDB file, but one method is always used, namely get_structure() which – as the name implies – returns a Structure object.

1: from Bio import PDB
3: p = PDB.PDBParser()
4: s = p.get_structure("3ns0", "3ns0.pdb")

In line 3 the parser object is instantiated in the object
p. Next, in line 4 we retrieve the Structure object. The method get_structure() needs an identifier string (can be any meaningful string, here we use the PDB ident) and the file name of a PDB entry.

In fact, the second argument to get_structure() can also be a file handle, or generally, an object that has a readlines() method. This is useful if for example you would like to read a gzipped PDB entry:

import gzip
fd ="1psr.pdb.gz")
s1 = p.get_structure("1psr", fd)

The gzip module transparently opens both gzipped and text files.

4.2.2 The Structure object

The Structure object is the top-level object, and contains methods to access the child objects. Many of these methods are in fact common to the lower-level objects also, because they are inherited from a common base class called Entity(). The methods include:

return level in hierarchy (“A”, “R”, “C”, “M” or “S”)
return list of children
return the ID of the object

The objects in the SMCRA hierachy also inherit attributes from the base class, including child_dict, which is a dictionary containing the child objects with the child IDs as keys.

However, the Structure object also contains convienient methods that more directly access the content of the structure:

return a chain iterator
return a residues iterator
return an atom iterator

Recall that iterators are objects that cannot be accessed directly,
but must be used in a loop contruct.

Finally, the Entity() base class defines the special method __getitem()= which enables the use of the “[]” operator on the object. In our example, s[0] thus contains the child (a Model object) with ID 0. Another usefule attribute is parent, which contains a reference to the parent object.

4.2.3 The Model object

The Model object is used in PDB entries containing NMR models. An NMR entry typically contains 20 models or more. PDB entries of structures determined by X-Ray crystallography normally only has one model.

4.2.4 The Chain object

Each Model object contains a list of one or more Chain objects. One Chain object is generated from each unique chain identifier in the PDB file (column 5), and the Chain object controls access to the residues that are a part of that chain.

4.2.5 The Residue object

The pattern should be obvious by now. The Residue object defines one residue in the structure.

To retrieve residues in a structure, we first store the model in object m, then loop over chains c, and for each chain, we can loop over residues r:

m = s[0]
for c in m:
   for r in c:
      print r

However, there really is no need to loop over models, then chains, then residues unless you actually need to examine the structure in this way. We can use a convienience method in the Structure object to retrieve all residues from a structure directly:

1: R = s.get_residues()
2: for r in R:
3:  print,

Line 1 gives us an iterator that can be used to visit all residues belonging to structure s. In line 3 we print the ids of all residues. This is the number given in column 6 of a PDB file. Many molecular graphics programs prefix the residue number with the chain ID (for example “A129”) but here, we retrieve the ID of the parent object (the parent of Residue objects is the Chain).

4.2.6 The Atom object

The Atom() class is the most fundamental class in the SMCRA hierachy, and also the class with the most methods. In particular, we have the get_coord() method, which returns the coordinates of the atom in a Numpy array. We can retrieve atoms from a structure using the get_atoms() method:

4: A = s.get_atoms() # get an atom iterator 5: L = []
6: for a in A:
7:  L.append(a.get_coord())
8: print L

In line 7, we stash away the coordinates of a structure in a list L. The Atom object also exposes methods to retrieve the B-factor, the occupancy, serial number, etc.

4.3 List comprehension

In this and earlier presentations, you have seen that we routinely extract objects and organize them into a list. For example in the example above we first created an empty list L, and in the following loop, we extract the objects we are interested in and append them to the list. This construction is used to often in Python, that a special idiom in the language has been created to deal with it. It is called list comprehension. Let us revisit the case of retrieving atoms from a structure:

A = s.get_atoms() # get an atom iterator L = [a for a in A]

This construction might look a bit weird when you first see it, but it quickly becomes a part of your Python vocabulary. Let us break the syntax down a bit. The initial a is the object that gets appended to the list, or in other words, the list will consist of a‘s. The following “for” statement determines what a‘s will be selected, namely those generated by the iterator A.

We can condense it even further:

L = [a for a in s.get_atoms()]

This gives us a list of atoms in L. However, in the example in the previous section (7) we retrieved a list of coordinates not atoms. Using a list comprehension, we can write:

L = [a.get_coord() for a in s.get_atoms()]

A list comprehension can also introduce an if-filter, for example:

T = [r for r in s.get_residues() if r.resname=='TYR']

creates a list T containing tyrosine residues.

4.4 Distance matrix plot

We will now use Biopython and Numpy to write a program to make a C-alpha distance matrix plot. The core logic of this program looks like this:

1:     s = parser.get_structure(id, fnam)
3:  chains = [c for c in s.get_chains()]
5:     x = []
6:     for r in chains[0]:
7:  if 'CA' in r.child_dict:
8:             ca = r.child_dict['CA']
9:  x.append(ca.get_coord())

First, we generate a list of chains (line 3), and then, in the loop, we step through the residues of the first chain only. It is left as an exercise to make the program more general so that it can deal with all chains, or deal with a specific chain specified by the user on the command line. In line 7, we check to see if the key ‘CA’ is in the residues’ child dictionary. For a residue, this dictionary contains the atoms of the residue, indexed by their names. If the atom has the name ‘CA’, the atom object is retrieved, and its coordinate appended to the list x.

The next step is to convert the list of coordinates (each of which is a Numpy array) to a large Numpy array of dimensions (N,3) where N is the number of atoms:

coords = np.array(x)

The final step is to compute the distance matrix. Fortunately, this is possible by using a module from scipy. The function cdist is able to compute a distance matrix between two different sets of coordinates, in our case, we need to compute a distance matrix between the coordinates to themselves. This is why the first two arguments passed to cdist are both coords. The last argument specifies that we want to compute the eucledian distance (normal geometry).

import scipy.spatial

data = scipy.spatial.distance.cdist(coords, coords, 'euclidean')

Now, with the distance matrix stored in the Numpy array data, all we need to do is plot it:

plot (data)

The code in the plot() function was copied from the Gallery on the matplotlib web site, after first finding a plot that looks like the one we want.

The entire source of the program, including the function plot() is shown in the Appendix.


The source code of the program In the plot() function, the commented-out code is needed to create a plot to a PNG file instead of to the computer screen. To generate a plot, the lines:

# import matplotlib # matplotlib.use( 'Agg' ) 

should be activated, and the function pylab.savefig() should be used instead of

import sys
import os
from Bio.PDB.PDBParser import PDBParser
import numpy as np
import warnings

def plot(data):    

# import matplotlib # matplotlib.use( 'Agg' ) 
    import pylab

    fig = pylab.figure()
    ax = fig.add_subplot(111)

    cax = ax.imshow(data, interpolation='nearest')
    ax.set_title('Ca-Ca distance plot')

    # Add colorbar, make sure to specify tick locations to match desired ticklabels 
    min = np.min(data)
    max = np.max(data)
    cbar = fig.colorbar(cax, ticks=[min, max])
# pylab.savefig( 'distmat.png', format='png' ) 

if __name__ == '__main__':
    import re

    fnam = sys.argv[1]
    if not os.path.exists(fnam):
        print "file not found, duh!"
        raise SystemExit

    id = fnam.split('.')[0]

    parser = PDBParser()

    s = parser.get_structure(id, fnam)

    chains = [c for c in s.get_chains()]

    x = []
    for r in chains[0]:
        if 'CA' in r.child_dict:
            ca = r.child_dict['CA']

    coords = np.array(x)

    import scipy.spatial

    data = scipy.spatial.distance.cdist(coords, coords, 'euclidean')
    print data.shape

Date: 2012-01-30 13:59:32 CET

HTML generated by org-mode 6.21b in emacs 23

Python for crystallographers 3

Posted in Biopython, Programming, Python, Tutorial by mok0 on January 29, 2012

3 Python for crystallographers 3

This is the third in a series of tutorials on Python I gave at the Department of Molecular Biology, Aarhus University. It is aimed at crystallographers and structural biologists. This text is a commented transcript of the session log file produced by IPython The transcript does not include the output from Python. You will have to try it yourself.

3.1 Reading a PDB file

The first project is to read a PDB format file. The following snippet of code opens a file and swallows it. The list L will contain a list of lines:

fnam = '1au1.pdb'
f = open(fnam)
L = f.readlines()
print L[10]

But L includes a lot of header lines from the PDB file that we really don’t need. To help filter out the ATOM records, we make use of Pythons regular expression module, called re. Then we step through all lines in the list L, extract the lines that start with ‘ATOM’, and append those to another list: data.

import re

data = []
for rec in L:
    if re.match('ATOM', rec):

We check the length of the list data, and print out a few of the first atoms:

for i in 1,2,3,4:
    print data[i]

Remember, that Python arrays start at 0, so data[0] contains the first atom, but that atom has serial ID number 1.

3.2 Class based approach

Now we will create a more advanced and flexible data structure for atoms. We create a file with the following content:

 1: class Atom:
 2:  def __init__(self):
 3: = ''
 4: = 0
 5:         self.element_number = 6
 6:         self.x = 0.0
 7:         self.y = 0.0
 8:         self.z = 0.0
 9:         self.b = 1.0
10:         self.occ = 1.0

In line 2 we define the class constructor. In this design, the constructor does not need any parameters. So now we can define an “empty” atom. In IPython, we use the %run magic command to “source” the file

%run pdb
atom = Atom()
print a.x, a.y, a.z, a.occ, a.b

This will print out the default values defined in the constructor.

Now, let us add a method to the Atom class that will parse an ATOM record from a PDB file, and fill the relevant attributes with the relevant data. Here is the method, it should be addede to the class Atom in the file

    def parse_from_pdb (self,s):
        L = s.split() = int(L[1]) = L[2]
        self.x = float(L[6])
        self.y = float(L[7])
        self.z = float(L[8])
        self.occ = float(L[9])
        self.b = float(L[10])

Now, in IPython, we run again:

%run pdb
atom = Atom()

We still have a record from the PDB file from before, when we loaded the PDB file into a list of strings called L. Let us try to parse one of these lines:

print atom.x, atom.y, atom.z

This loaded the data from line 2000 in the file into the object atom.

3.3 version 2

Now we would like to make a more complete standalone program, so we add a main program to the file

 1: class Atom:
 2:     def __init__(self):
 3: = ''
 4: = 0
 5:         self.element_number = 6
 6:         self.x = 0.0
 7:         self.y = 0.0
 8:         self.z = 0.0
 9:         self.b = 1.0
10:         self.occ = 1.0
12:     def parse_from_pdb (self,s):
13:         L = s.split()
14: = int(L[1])
15: = L[2]
16:         self.x = float(L[6])
17:         self.y = float(L[7])
18:         self.z = float(L[8])
19:         self.occ = float(L[9])
20:         self.b = float(L[10])
21:     #. 22: 
23: if __name__ == '__main__':
24:     import re
26:     fnam = '1au1.pdb'
27:     f = open(fnam)
28:     L = f.readlines()
30:  atoms = []
31:  for line in L:
32:  if re.match('ATOM|HETATM', line):
33:             a = Atom()
34:             a.parse_from_pdb(line)
35:             atoms.append(a)

We open the file as before, and swallow the whole thing using readlines(). This gives a list of lines. In line 30, we create an empty list that will be used to store the atom objects. In line 31 we step through all the strings in list L. Something new happens in line 32. Here we use match() of the regular expression module re to “grep” out lines that start with either ‘ATOM’ or ‘HETATM’. Only if one of these two keywords are found, we will execute the code inside that if statement. If we have an ‘ATOM’ or a ‘HETATM’ record, we instance an empty Atom object, and use the parse_from_pdb() method to populate the fields of the object. Finally, we append the newly created object to the list atoms. Now, run this from IPython, and look at some of the elements in list atoms:

%run pdb
print atoms[1]
print atoms[10]

This printout is pretty uninformative. We should add a __repr()__ method to the Atom class. It looks like this:

    def __repr__(self):
        s = "Atom: {0}, x,y,z={1},{2},{3}, occ={4}, B={5}"
        s = s.format(,self.x,self.y,self.z,self.occ,self.b)
        return s

Here, the format() method of the str class is used to format the string. In this case, the tokens marked with curly brackets will be formatted with the corresponding argument. There is a whole mini-language that allows very sophisticated string formatting, it can be studied here:

%run pdb
print atoms[1]

which prints output that looks like this:

Atom: CA, x,y,z=24.887,27.143,6.222, occ=1.0, B=41.36

Now, we can enhance our main program to write out more information:

if __name__ == '__main__':
    import re

    fnam = '1au1.pdb'
    f = open(fnam)
    L = f.readlines()

    atoms = []
    for line in L:
        if re.match('ATOM|HETATM', line):
            a = Atom()

    for a in atoms:
        print a

However, when we run this, we get a run-time error!

In [7]: %run pdb 1au1.pdb
ValueError                                Traceback (most recent call

/u/mok/Dropbox/python-course-2011/ in <module>()
     59         if re.match('ATOM|HETATM', line):
     60             a = Atom()
---> 61             a.parse_from_pdb(line)
     62             atoms.append(a)

/u/mok/Dropbox/python-course-2011/ in parse_from_pdb(self, s)
     18         self.y = float(L[7])
     19         self.z = float(L[8])
---> 20         self.occ = float(L[9])
     21         self.b = float(L[10])
     22     #.

ValueError: invalid literal for float(): 1.00100.00
WARNING: Failure executing file: <>

The second-last line gives us a hint to what is going on. Python can not convert the string ‘1.00100.00’ to a floating point number. This is a well known limitation of the PDB format. When a B factor becomes 100.0 or larger, there is no longer a space between the occupancy field and the B-factor field. Therefore, the logic we used in the parse_from_pdb() method is too simplistic. We can’t simply split the line into space-separated fields using the split() method. We need to be more careful. So, parse_from_pdb() needs to be changed to this:

    def parse_from_pdb (self,s):
        L = s.split() = int(L[1]) = L[2]
        self.x = float(L[6])
        self.y = float(L[7])
        self.z = float(L[8])
        self.occ = float(s[55:60])
        self.b = float(s[60:66])

Now, instead of using the split fields to extract occ and b, we extract them directly from positions 55 to 59 and 60 to 65 in the input string. (This will work for this file, but the logic is likely to fail if tested on every PDB file we can find, because there are other issues with PDB files that may cause the number of fields to be different.)

3.4 A more complete program

Now, let us make the program more versatile, so that we can specify the PDB file from the command line. We change the main program to look like this:

 1: if __name__ == '__main__':
 2:     import re
 3:     import sys
 4:     import os
 6:  fnam = sys.argv[1]
 7:  if not os.path.exists(fnam):
 8:         print "File", fnam, "not found, duh!"
 9:         raise SystemExit (ref:exit)
11:     f = open(fnam)
12:     L = f.readlines()
14:     atoms = []
15:     for line in L:
16:         if re.match('ATOM|HETATM', line):
17:             a = Atom()
18:             a.parse_from_pdb(line)
19:             atoms.append(a)
21:     for a in atoms:
22:         print a

In line 6 we use the sys module to access the (first) command line argument. This is assumed to be a file name, but in line 7 we double check to make sure the file exists, by using exists() from the (extremely useful) os.path module. If the file is not found, we print out an error message, and stop the program by raising an exception in line nil. Now the program is more general, and can be used to read in any PDB file.

3.5 Distance between atoms

We want to be able to compute the distance between two atoms. We add a function to to do this. The function assumes to be passed two objects that have attributes x, y and z, it then does the math computes the distance between these points.

def distance(atom1, atom2):
    import math
    dist = math.sqrt((atom1.x-atom2.x)**2
    return dist

We need to import the math module so we can look up the square root. We could also have written the function as a method of the Atom class, in which case the call would be:

d = atom1.distance(atom2)
print d

This is a matter of design. We choose to write a function, that is called like this:

d = distance(atom1, atom2)
print d

We can then compute the distance of all atoms to (a random) atom number 300 The full source code of the program is listed in the appendix. We run the program from within IPython like this:

%run pdb 1au1.pdb

3.6 Difference between = and ==

The answer is simple: = is used for assignement, and == is used for comparisons. For example:

In [9]: a=1

In [10]: a
Out[10]: 1

In [11]: a == 2
Out[11]: False

In [12]: a == 1
Out[12]: True

3.7 Plotting with matplotlib

Finally, let us take a look at the incredibly useful plotting library, matplotlib, that is a part of SciPy. First, we create a list of B values from our list of atom objects:

bvalues =[]
for a in atoms:

Now we can make plot of B-values vs. atom number:

import pylab

Matplotlib can do a huge amount of different plots. A great way to get started is to go to the matplotlib gallery at and choose a plot that looks like what you need. Then you can cut and paste the source code of the plot into IPython. Use the %cpaste magic to do this.


Complete source code of the final version of

class Atom:
    def __init__(self): = '' = 0
        self.element_number = 6
        self.x = 0.0
        self.y = 0.0
        self.z = 0.0
        self.b = 1.0
        self.occ = 1.0

    def parse_from_pdb (self,s):
        L = s.split() = int(L[1]) = L[2]
        self.x = float(L[6])
        self.y = float(L[7])
        self.z = float(L[8])
        self.occ = float(s[55:60])
        self.b = float(s[60:66])

    def __repr__(self):
        s = "Atom: {0}, x,y,z={1},{2},{3}, occ={4}, B={5}"
        s = s.format(,self.x,self.y,self.z,self.occ,self.b)
        return s

def distance(atom1, atom2):
    import math
    dist = math.sqrt((atom1.x-atom2.x)**2
    return dist

if __name__ == '__main__':
    import re
    import sys
    import os

    fnam = sys.argv[1]
    if not os.path.exists(fnam):
        print "file not found, duh!"
        raise SystemExit

    f = open(fnam)
    L = f.readlines()

    atoms = []
    for line in L:
        if re.match('ATOM|HETATM', line):
            a = Atom()

    XXX = atoms[299]

    for a in atoms:
        print distance(a,XXX)

Date: 2012-01-29 16:22:46 CET

HTML generated by org-mode 6.21b in emacs 23

Python for crystallographers 2

Posted in Biopython, Programming, Python, Tutorial by mok0 on January 28, 2012

2 Python for Crystallographers 2

This is the second in a series of tutorials on Python I gave at the Department of Molecular Biology, Aarhus University in 2011. It is aimed at crystallographers and structural biologists. This text is a commented transcript of the session log file produced by IPython The transcript does not include the output from Python. You will have to try it yourself.

2.1 Classes

Classes are a fundamental feature in all Object Oriented programming languages. C++, Java, Objective-C, Smalltalk, etc. all implement classes. Programmers use classes in different ways. Some classes represent concrete objects, for example atoms, residues, or sequences, but in other cases, classes are used to encapsulate various algorithms, or they produce iterators or are factories of objects. As you use various Python modules, you will meet different class designs.

Let us define a very simple class:

class A:
    a = 1

A Python class is not usually used on its own. You can compare a class to a cookie-cutter, it defines the shape and size of the cookie, but to actually get something concrete out of it, you need to press it into the dough to make a cookie. With classes, you need to instance it to make it useful, and you can create as many instances as you want (unless the class has specific logic to prevent that.)

inst = A()

Class A only contains one variable, a. Variables of this kind are called class variables, because they are shared by all instances of the class. This is useful for e.g. constants and other data items, but in general, instances need their own data too.

Here we define a class that has an instance variable b:

class A:
    a = 1
    def __init__(self, name): = name

The special method __init__()= is called whenever Python constructs an instance of a class. The variable self refers to the instance object itself, so refers to a variable in the namespace of the instance. The __init__() method can also be called a constructor. When we define a constructor that takes an argument, the instance must be defined by passing one to the constructor. This fails:

inst = A()

but this works:

inst = A("abc")

We can make another instance of class A:

inst2 = A("def")
print inst2.a

You see that the name instance variable is different in the objects inst and inst2, but the class variable a is the same. If we change a:

A.a = 2
print inst2.a
print inst.a

You will see that the class variable a has now been set to 2 in both instances.

2.1.1 Class inheritance

Now we look at class inheriance. Here is a class that describes a person:

class Person:
    def __init__(self, name, addr, email, phone): = name
        self.address = addr = email = phone

    def set_email(self, email): = email
        print "email sat til", email

The instance variables name, address, email, and phone is defined in the constructor, so it is used like this:

pers1 = Person("morten", "århus", "", 86188180)

We can access the attributes via the instance of the person:


In the class definition, we have defined a method to set the email address. A method of this type is called a “setter”:


In this case, the setter does nothing else than change the value of the email variable, so we could have done just this: = ''

however, using getters and setters is normally considered good programming style.

If we want to have a class describing a student, we can make use of the functionality already existing in the Person class. This is called the DRY principle: Don’t Repeat Yourself. A student however, has special attributes that is not used for other persons:

class Student(Person):

    def set_studiekortnummer(self, s):
        self.studie_nr = s

We have added a method to set the studynumber, but the name, address etc. is inherited from the base class.

rune = Student("rune", "ukendt", "rune@gmail", 89421111)

We now have an instance of the Student class called rune. Let us set the student number:

print rune
print rune.studie_nr

2.2 Biopython

We will now look at the Biopython package, but first, let us write a small program to fetch a sequence from Uniprot that is purely native Python.

2.2.1 fetch sequence from Uniprot

Here is the content of the program called

#! /usr/bin/env python 
from utils import parse_list
import urllib
import sys

uniprot = ""
remote = urllib.FancyURLopener()

if __name__ == "__main__":

    fd = open (sys.argv[1])

    for ent in parse_list(fd):
        print "getting ", ent
        f =".txt")
        seq =
        g = open(ent+".txt", "w")
    #. #. 

Let us examine the code. Near the top, you see that we import the function parse_list from the module utils. This is our own Python module, stored in a file, and it looks like this:

def parse_list(f):
    "Parse our little sequence id list files"
    line = 'begin'
    L = []
    for line in f:
        if '#' in line:
            line,comment = line.split('#',1)
        #.         if len(line) > 0:
    return L

This function reads a file, skips comments marked with ‘#’, and returns a list of sequence IDs.

Next, we open a file with the file name sys.argv[1]. This is an attribute from the imported sys module, that contains the parameters given on the command line. So, it our program is invoked like this:

$ python ifns.txt

the value of sys.args[1] will be ‘ifns.txt’. Our program then proceeds by reading entries one by one from the file-like object remote, which is an instance of the object urllib.FancyURLopener() from the urllib module, opened with the URL of the relevant sequence entry. Every sequence entry is then stored in a local file.

2.2.2 Fetch sequence using Bio.Entrez

Now we will fetch some sequences using NCBI’s Entrez database. Biopython provides a convienient interface to Entrez’ API. Here is the program

#! /usr/bin/env python 
from Bio import Entrez
from utils import parse_list
import sys

# See 
file_ext = {'gp':'gb',

if __name__ == '__main__':

    fd = open (sys.argv[1]) = ""

    for ent in parse_list(fd):
        for rettype in file_ext:
            handle = Entrez.efetch(db="protein", id=ent,
            fnam = ent + '.' + file_ext[rettype]
            g = open(fnam, 'w')
            print "wrote", fnam
        #.     #. #. 

This program is a bit more complicated than the Uniprot fetching program, but follows the same general logic. First, we set a class variable, this is requested by the Entrez service and we do that as a matter of courtesy. As before, we pass through all sequence IDs in the input file, but this time, we add an additional loop inside, that loops through a list of different data return types given in the dictionary file_ext, which at the same time maps a file extension to each return type. After running this program, we are left with a series of files for each sequence ID, for example, for ID P01563 we have:

  -rw-r--r--   1 mok  mok        345 May 30 10:11 P01563.fa
  -rw-r--r--   1 mok  mok       2676 May 30 10:11 P01563.ft
  -rw-r--r--   1 mok  mok      80468 May 30 10:11 P01563.full
  -rw-r--r--   1 mok  mok      17099 May 30 10:11
  -rw-r--r--   1 mok  mok      56359 May 30 10:11 P01563.gpc
  -rw-r--r--   1 mok  mok      11662 May 30 10:03 P01563.txt

Now, lets go back to the IPython interface and play a bit more with Biopython. First, we will use the SeqIO module:

from Bio import SeqIO
dir (SeqIO) # look at what SeqIO contains 
seq ="", "genbank")

Now, we have a Biopython sequence object (a “SeqRecord”) named seq containing all the information that was parsed from the input Genbank format file:


We can look at the sequence description, and we see that the sequence is stored in a special object which also contains the alphabet.


The object seq can be indexed using the square bracket notation (like normal Python lists), and it can be iterated in a loop:

print seq[0]
for a in seq:
    print a

The SeqRecord object attribute features contains a list of feature objects, all collected from the Genbank format sequence file:

print seq.features

You can investigate this yourself more, look at the various types of features and what data they contain.

2.3 The special method __repr__

We will briefly look at the special method called __repr()__. This is a method that can be defined in any class, and it defines how the class behaves when passed to the print function, and should simply return a string representation of the object. Let us define this method in our Person class from before:

class Person:
    def __init__(self, a, addr, email, tlf): = a
        self.adresse = addr = email
        self.telefon = tlf

    def set_email(self, email): = email
        print "email set to", email

    def __repr__(self):
        return "Name: " +

Now, if we print the person pers1 from before, Python will print:

Name: morten

instead of a strange technical object description. As the base class is now enhanced, the new capability will automatically be available to the Student class too:

rune = Student("rune", "ukendt", "rune@gmail", 89421111)
print rune

2.4 Function returning tuples

A function can return a tuple:

def f():
    return "a", "b"

print f()
i,j = f()

print i
print j

The above example shows how each element in the tuple returned by function f() can be assigned to different variables i and j.

2.5 Listdir

Python is very suited for all kinds of systems work. The os module contains lots of useful functions for interacting with the operating system. For example, the function listdir() will return a list of files in the directory passed as an argument:

import os

this_dir = os.listdir('.')
tmp_dir = os.listdir('/tmp')
for f in os.listdir('/tmp'):
    print f

Date: 2012-01-26 18:53:42 CET

HTML generated by org-mode 6.21b in emacs 23