python

python

python

python

python

python

python

python

My most loved programming language. Easy to read easy to write with loads of powerful features.

closeup.py

basic version

A small script in python that determines atoms in the proximity of given x y z co-ordinates in a pdb file. This is the python version of the close-up in MCCE ;)

001 #!/usr/bin/python
002
003 '''
004 This small python script lists atoms of a given pdb file that are 
005 in the proximity of given coordinates.
006
007 Usage:
008 closeup.py <pdbfile> <x y z> <max distance>
009
010 '''
011
012 import sys, math 
013
014 __copyright__ = """
015 -----------------------------------------------------------------
016 (c) Copyright by Christian Fufezan, 2007  (christian@fufezan.net)
017
018     Permission to use, copy, modify, and distribute this 
019     software and its documentation for any purpose and 
020     without fee or royalty is hereby granted, provided 
021     that the above copyright notice appear in all copies 
022     and that both that copyright notice and this permission 
023     notice appear in supporting documentation or portions 
024     thereof, including modifications, that you make.
025
026 """
027 __version__   = '1.0'
028 __author__    = 'Christian Fufezan'
029 __date__      = '7th March 2007'
030 __url__       = 'http://www.fufezan.net/contact.php'
031
032 class ATOM:
033    def __init__(self,x,y,z):
034       self.x = x
035       self.y = y
036       self.z = z
037
038    def distanceTo(self, zeOther):
039       SumOfSquares = ((self.x-zeOther.x)**2) + ((self.y-zeOther.y)**2) 
   + ((self.z-zeOther.z)**2)
040       formated = '%(d).3f' % {'d' :math.sqrt(SumOfSquares)   }
041       return float(formated)
042       
043       
044 def bp():
045    sys.exit(0)
046
047 if (__name__ == "__main__"):
048    if (len(sys.argv)) != 6:
049       print __doc__
050       print " script location:",str(sys.argv[0])
051       print " Version",__version__,"\n"
052       bp()
053    else:
054       pdbfile = sys.argv[1]
055       x = float(sys.argv[2])
056       y = float(sys.argv[3])
057       z = float(sys.argv[4])
058       d = float(sys.argv[5])
059       centre = ATOM(x,y,z)
060       complete_pdb=open(pdbfile).xreadlines()
061       neighbours = []
062       
063       for line in complete_pdb:
064          if (line[:6] == 'HETATM') or (line[:6] == 'ATOM  '):
065             tmpAtom=ATOM(float(line[31:38]),float(line[39:46]),float(line[4
   7:54]))
066             distance = tmpAtom.distanceTo(centre)
067             if distance < d:
068                tmpAtom.idx = int(line[6:11])
069                tmpAtom.atype = str(line[11:16]).strip()
070                tmpAtom.aa = str(line[17:20]).strip()
071                tmpAtom.chain = str(line[21:22])
072                tmpAtom.resid = int(line[22:26])
073                tmpAtom.distance = distance
074                neighbours.append(tmpAtom)
075       
076       for atom in neighbours:
077          print '%(distance).2f %(idx)5s %(atype)3s %(aa)s %(chain)s%(resi
   d)4s %(x).3f %(y).3f %(z).3f' % {
078          'distance'   : atom.distance,
079          'idx'      : atom.idx,
080          'atype'      : atom.atype,
081          'aa'      : atom.aa,
082          'chain'      : atom.chain,
083          'resid'      : atom.resid,
084          'x'         : atom.x,
085          'y'         : atom.y,
086          'z'         : atom.z
087          }

type:python   [ download ]

The Actual Code starts at line 47. Line 48 checks if sufficient arguments are passed over to the script (namely 6) and if not, the documentation, usage, version number, and so on, are printed. Otherwise (line 53) the variables are defined according to the input. Line 59 defines the centre as an ATOM object. This object is defined in line 32. The object has to be initiated by its x y z coordinates. In this script the ATOM object has only one other attribute, namely distanceTo.
The loop at line 63 checks each line in the pdb file to check which ones start with HETATM or ATOM. If we have a line that holds coordinates for an atom we define this atom as an ATOM object with its x y z. Line 66 defines distance as the distance to and from the current tmpAtom to the centre. If distance is smaller than d (max distance defined) by the input (d) then the tmpAtom is fully assigned with its idx, chain, atomtype, residue and so on, and appended to the neighbouring list.
Finally the output is produced by looping over ATOM objects in the neighbours list (line 76).
Very easy ;) showing the power of object oriented programming.

map2pdb

xyz Version

This converts a xyz output file (e.g. from Jaguar) to a pdb file and adds values (e.g. charges) to the beta field. Additionally a second value file (e.g. another charge file) can be specified and the difference between the two files wil be mapped into the user field of the pdb file.

001 #!/usr/bin/python
002 #
003 #
004 '''
005 map value to beta field in corrosponding pdb
006
007   - Usage: map2pdb <xyz-inputfile> <NBO charges> <optional NBO file
   >
008   - input data format e.g.: C  1   -0.08588
009
010  The optional NBO File can be used to calculate the difference 
011  in charge. It will be mapped into the User field.
012 '''
013
014 import sys
015
016 __author__ = 'Christian Fufezan'
017 __url__ = 'http://www.fufezan.net/contact.php'
018 __version__ = 1.2
019
020 class ENTRY(object):
021    global xyz
022    def __init__(self,x,y,z,i,name):
023       self.x = round(float(x),3)
024       self.y = round(float(y),3)
025       self.z = round(float(z),3)
026       self.atype = str(name)+str(i)
027       self.type = str(name)
028       self.idx = int(i)
029       self.beta = 7.777
030       self.user = 7.777
031    
032    def addBeta(self,atomname,atomidx,charge):
033       try:
034          if self.idx == atomidx:
035             self.beta = float(charge)
036          else:
037             print '<missmatch Beta> arry has',self.idx,' - expected',atomid
   x 
038       except:
039          print 'Woot'
040       return
041    
042    def addUser(self,atomname,atomidx,charge):
043       try:
044          if self.idx == atomidx:
045             self.user = 10*(self.beta - float(charge))
046             #print self.idx,self.beta,charge,self.user
047          else:
048             print '<missmatch User> arry has',self.idx,' - expected',atomid
   x
049       except:
050          print 'Woot'
051       return
052          
053    def iscomplete(self):
054       if diffcrg != '':
055          if self.beta == 7.777 or self.user == 7.777:
056             return 0
057          else:
058             return 1
059       else:
060          if self.beta == 7.777:
061             return 0
062          else:
063             return 1
064          
065 def readin_xyz(file):
066    coordinates=open(file).xreadlines()
067    i = 0
068    xyz = []
069    for line in coordinates:
070       if not line.startswith('#') and line.strip() != '':
071          chopped = line.split()
072          if len(chopped) == 4:
073             tmp = ENTRY(chopped[1],chopped[2],chopped[3],i+1,chopped[0])
074             i += 1
075             xyz.append(tmp)
076    return xyz
077
078 def bp():
079    sys.exit(1)
080
081
082 if (__name__ == '__main__'):
083    if (len(sys.argv) != 3 and len(sys.argv) != 4):
084       print __doc__
085       print __version__
086       bp()
087    else:
088       inputxyz = str(sys.argv[1])
089       inputcrg = str(sys.argv[2])
090       if ( len(sys.argv) == 4):
091          diffcrg = str(sys.argv[3])
092       else:
093          diffcrg = ''
094       Output = {}
095       xyz = []
096       charges = []
097       '''Reading xyz hem file ...'''
098       xyz = readin_xyz(inputxyz)
099       '''print 'Adding charges ... '''
100       crg = open(inputcrg).xreadlines()
101       for line in crg:
102          if not line.startswith('#') and line.strip() != '':
103             chopped = line.split()
104             if len(chopped) == 3:
105                xyz[int(chopped[1])-1].addBeta(chopped[0],int(chopped[1]),chop
   ped[2])
106       if diffcrg != '':
107          diffcrg = open(str(sys.argv[3])).xreadlines()
108          for line in diffcrg:
109             if not line.startswith('#') and line.strip() != '':
110                chopped = line.split()
111                if len(chopped) == 3:
112                   xyz[int(chopped[1])-1].addUser(chopped[0],int(chopped[1]),cho
   pped[2])
113          
114       print 'HEADER    Hem-Project CCNY 2007'
115       print 'REMARK    generate by map2pdb. xyz file + charge '
116       print 'REMARK    !! verify atom <-> charge correlation !!'
117       
118       for i in range(len(xyz)):
119          if not xyz[i].iscomplete():
120             print "<Error> Could not match charges for all atomes ..."
121             bp()
122          else:
123             #print 'ATOM     60  CG1 ILE A   8       8.487  10.934  16.126 
    1.00 20.08           C'  
124             print 'ATOM    %(j)3d %(atype)4s UKN A %(j)3d      %(x)6s  %(y)
   6s  %(z)6s %(user)5s %(crg)5s           %(e)s' % {
125             'j'     : xyz[i].idx,
126             'atype' : xyz[i].atype,
127             'x'     : str('%(tmp).3f' % {'tmp' : float(xyz[i].x)}),
128             'y'     : str('%(tmp).3f' % {'tmp' : float(xyz[i].y)}),
129             'z'     : str('%(tmp).3f' % {'tmp' : float(xyz[i].z)}),
130             'crg'   : str('%(tmp).2f' % {'tmp' : float(xyz[i].beta)}),
131             'user'   : str('%(tmp).2f' % {'tmp' : float(xyz[i].user)}),
132             'e'     : xyz[i].type
133             }
134       print 'END'
135       bp()

type:python   [ download ]

Description of what happens will follow .. sorry ...

gSyslog

Do you own an US Robotics router ? Did you ever want to use the System log feature? That feature enables the router to send its log files via port 514 to a computer on the local network. There are some tools to display this log on Windows machines, but nothing similar on the Mac platform (afaik).
This is why I wrote this little Python script. There are better ways to do it and if you want to go into Network programming, I highly recommend Twisted.
For a comfortable display I use the growl system notification extension. You must have the growl-python extension installed! See the Growl manual for that :)

001 #!/usr/bin/python
002 '''
003 A python scripts that listens on port 514 for 
004 UDP connections e.g. from US Robotics 
005 and displays the log via growl
006
007 Requires Python 2.3 or higher and Growl
008
009 Copyright 2007 Christian Fufezan <Christian@fufezan.net>
010 '''
011
012 from Growl import *
013 from socket import *
014 from time import localtime,asctime
015 host = ''
016 port = 514
017 buf = 8192
018 address = (host,port)
019
020 class GROWLNOTIFIER(GrowlNotifier):
021    def __init__(self):
022       self.applicationName = 'gSyslog'
023       self.applicationIcon = Image.imageWithIconForApplication('/Applic
   ations/Utilities/Console.app')
024       self.notifications = ['gSyslog msg','Connection allowed', 'Connec
   tion denied']
025       self.register()
026       self.notify(self.notifications[0],'_gSyslog_init_','Starting list
   ing\n'+str(asctime(localtime())),sticky=1)
027
028 if __name__ == '__main__':
029    UDPSocket = socket(AF_INET,SOCK_DGRAM)
030    UDPSocket.setsockopt(SOL_SOCKET, SO_REUSEADDR, 1)
031    UDPSocket.bind(address)
032    print 'talking to Growl'
033    gSyslog = GROWLNOTIFIER()
034    print 'starting Listening ...'
035    try:
036       while 1:
037          data,addr = UDPSocket.recvfrom(buf)
038          no_idx = data[4:]
039          gSyslog.notify(gSyslog.notifications[0],'_gSyslog_'+str(asctime(
   localtime())),no_idx+'\n')
040          print no_idx
041    except KeyboardInterrupt:
042       # Close socket
043       print '\nExiting ...'
044       UDPSocket.close()

type:python   [ download ]

What happens ? Is about to follow ...