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(x=1)
func1(residues=100)
func1(residues=100, atoms=1000)
func1(atoms=1000,residues=100)
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):
    pass

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>()

ZeroDivisionError:

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:

a=10
b=2
try:
    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
try:
    f = a/b
except:
    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/Superimposer.py, that we copy-paste into its own file called superimposer.py. (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
 4: 
 5: if __name__=="__main__":
 6: 
 7:     p=PDBParser()
 8:     s1=p.get_structure("FIXED", sys.argv[1])
 9:  fixed=Selection.unfold_entities(s1, "A")
10: 
11:     s2=p.get_structure("MOVING", sys.argv[1])
12:  moving=Selection.unfold_entities(s2, "A")
13: 
14:  rot=numpy.identity(3).astype('f')
15:  tran=numpy.array((1.0, 2.0, 3.0), 'f')
16: 
17:  for atom in moving:
18:         atom.transform(rot, tran)
19: 
20:     sup=Superimposer()
21: 
22:  sup.set_atoms(fixed, moving)
23: 
24:     print sup.rotran
25:     print sup.rms
26: 
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
NeigborSearch?

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

Nei<TAB>?

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 ns.search (center, 5, "A") 
4: print ns.search (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:

Out[39]:
[<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 http://csb.stanford.edu/rachel/fragments/. 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 fragmentmapper.py:

 1: from Bio.PDB import PDBParser, FragmentMapper, Selection
 2: import sys
 3: 
 4: if __name__=="__main__":
 5: 
 6:     p=PDBParser()
 7:     s=p.get_structure("X", sys.argv[1])
 8: 
 9:     m=s[0]
10:  fm=FragmentMapper(m, 10, 5, "fragment_data")
11: 
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
dir(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 utils.py. 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 __init__.py. The presence of this file in a directory tells Python that it is a module.

mkdir course/
touch course/__init__.py

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, __init__.py is empty, but it can contain Python code. Let us enter the following into the file course/__init__.py:

def hello():
   print "Python is cool"

Now, in IPython, this function can be called:

import course
course.hello()

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 utils.py to the new course module:

cp utils.py course/

Now, utils.py 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
2: 
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 = gzip.open("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:

get_level()
return level in hierarchy (“A”, “R”, “C”, “M” or “S”)
get_list()
return list of children
get_id()
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:

get_chains()
return a chain iterator
get_residues()
return a residues iterator
get_atoms()
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 r.id, r.parent.id

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)
2: 
3:  chains = [c for c in s.get_chains()]
4: 
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 distancematrix.py, including the function plot() is shown in the Appendix.

Appendix

The source code of the program distancematrix.py. 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 pylab.show().

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])
    cbar.set_ticks([min,max])

    pylab.show()
# 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]

    warnings.simplefilter('ignore')
    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']
            x.append(ca.get_coord())

    coords = np.array(x)

    import scipy.spatial

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

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):
        data.append(rec.split())

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

len(data)
data[0]
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 pdb.py with the following content:

 1: class Atom:
 2:  def __init__(self):
 3:         self.name = ''
 4:         self.id = 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 pdb.py:

%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 pdb.py:

    def parse_from_pdb (self,s):
        L = s.split()
        self.id = int(L[1])
        self.name = 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:

atom.parse_from_pdb(L[2000])
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 pdb.py:

 1: class Atom:
 2:     def __init__(self):
 3:         self.name = ''
 4:         self.id = 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
11: 
12:     def parse_from_pdb (self,s):
13:         L = s.split()
14:         self.id = int(L[1])
15:         self.name = 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
25: 
26:     fnam = '1au1.pdb'
27:     f = open(fnam)
28:     L = f.readlines()
29: 
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.name,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: http://docs.python.org/library/stdtypes.html#string-formatting

%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()
            a.parse_from_pdb(line)
            atoms.append(a)

    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
last)

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

/u/mok/Dropbox/python-course-2011/pdb.py 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: <pdb.py>

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()
        self.id = int(L[1])
        self.name = 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
 5: 
 6:  fnam = sys.argv[1]
 7:  if not os.path.exists(fnam):
 8:         print "File", fnam, "not found, duh!"
 9:         raise SystemExit (ref:exit)
10: 
11:     f = open(fnam)
12:     L = f.readlines()
13: 
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)
20: 
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 pdb.py 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
                     +(atom1.y-atom2.y)**2
                     +(atom1.z-atom2.z)**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:
    bvalues.append(a.b)

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

import pylab
pylab.plot(bvalues)

Matplotlib can do a huge amount of different plots. A great way to get started is to go to the matplotlib gallery at http://matplotlib.sourceforge.net/gallery.html 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.

Appendix

Complete source code of the final version of pdb.py

class Atom:
    def __init__(self):
        self.name = ''
        self.id = 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()
        self.id = int(L[1])
        self.name = 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.name,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
                     +(atom1.y-atom2.y)**2
                     +(atom1.z-atom2.z)**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()
            a.parse_from_pdb(line)
            atoms.append(a)

    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