Chem.PyMol

Package Chem :: Module PyMol |
[hide private]
[frames] | no frames]

# Source Code for Module Chem.PyMol

      1  # $Id: PyMol.py 753 2008-07-10 03:39:35Z glandrum $
      2  #
      3  # Copyright (C) 2004-2008 Greg Landrum and Rational Discovery LLC
      4  #
      5  #   @@ All Rights Reserved  @@
      6  #
      7  """ uses pymol to interact with molecules
      8
      9  """
     10  import Chem
     11  import xmlrpclib,os
     12
     13
     14  _server=None
     15 -class MolViewer(object):
     16 -  def __init__(self,host=None,port=9123,force=0,**kwargs):
     17      global _server
     18      if not force and _server is not None:
     19        self.server=_server
     20      else:
     21        if not host:
     22          host=os.environ.get('PYMOL_RPCHOST','localhost')
     23        _server=None
     24        serv = xmlrpclib.Server('http://%s:%d'%(host,port))
     25        serv.ping()
     26        _server = serv
     27        self.server=serv
     28      self.InitializePyMol()
     29
     30 -  def InitializePyMol(self):
     31      """ does some initializations to set up PyMol according to our
     32      tastes
     33
     34      """
     35      self.server.do('set valence,1')
     36      self.server.do('set stick_rad,0.15')
     37      self.server.do('set mouse_selection_mode,0')
     38      self.server.do('set line_width,2')
     39      self.server.do('set selection_width,10')
     40      self.server.do('set auto_zoom,0')
     41
     42
     43 -  def DeleteAll(self):
     44      " blows out everything in the viewer "
     45      self.server.deleteAll()
     46
     47 -  def DeleteAllExcept(self,excludes):
     48      " deletes everything except the items in the provided list of arguments "
     49      allNames = self.server.getNames('*',False)
     50      for nm in allNames:
     51        if nm not in excludes:
     52          self.server.deleteObject(nm)
     53
     54 -  def LoadFile(self,filename,name,showOnly=False):
     55      """ calls pymol's "load" command on the given filename; the loaded object
     56      is assigned the name "name"
     57      """
     58      if showOnly:
     59        self.DeleteAll()
     60      id = self.server.loadFile(filename,name)
     61      return id
     62
     63 -  def ShowMol(self,mol,name='molecule',showOnly=True,highlightFeatures=[],
     64                molB="",confId=-1,zoom=True):
     65      """ special case for displaying a molecule or mol block """
     66
     67      if not molB:
     68        molB = Chem.MolToMolBlock(mol,confId=confId)
     69      server = self.server
     70      if not zoom:
     71        self.server.do('view rdinterface,store')
     72      if showOnly:
     73        self.DeleteAll()
     74      id = server.loadMolBlock(molB,name)
     75      if highlightFeatures:
     76        nm = name+'-features'
     77        conf = mol.GetConformer(confId)
     78        for feat in highlightFeatures:
     79          pt = [0.0,0.0,0.0]
     80          for idx in feat:
     81            loc = conf.GetAtomPosition(idx)
     82            pt[0] += loc[0]/len(feat)
     83            pt[1] += loc[1]/len(feat)
     84            pt[2] += loc[2]/len(feat)
     85          server.sphere(pt,0.2,(1,1,1),nm)
     86      if zoom:
     87        server.zoom('visible')
     88      else:
     89        self.server.do('view rdinterface,recall')
     90      return id
     91
     92 -  def GetSelectedAtoms(self,whichSelection=None):
     93      " returns the selected atoms "
     94      if not whichSelection:
     95        sels = self.server.getNames('selections')
     96        if sels:
     97          whichSelection = sels[-1]
     98        else:
     99          whichSelection=None
    100      if whichSelection:
    101        items = self.server.index(whichSelection)
    102      else:
    103        items = []
    104      return items
    105
    106
    107 -  def SelectAtoms(self,itemId,atomIndices,selName='selection'):
    108      " selects a set of atoms "
    109      ids = '(id '
    110      ids += ','.join(['%d'%(x+1) for x in atomIndices])
    111      ids += ')'
    112      cmd = 'select %s,%s and %s'%(selName,ids,itemId)
    113      self.server.do(cmd)
    114
    115 -  def HighlightAtoms(self,indices,where,extraHighlight=False):
    116      " highlights a set of atoms "
    117      if extraHighlight:
    118        idxText = ','.join(['%s and (id %d)'%(where,x) for x in indices])
    119        self.server.do('edit %s'%idxText)
    120      else:
    121        idxText = ' or '.join(['id %d'%x for x in indices])
    122        self.server.do('select selection, %s and (%s)'%(where,idxText))
    123
    124 -  def SetDisplayStyle(self,obj,style=''):
    125      " change the display style of the specified object "
    126      self.server.do('hide everything,%s'%(obj,))
    127      if style:
    128        self.server.do('show %s,%s'%(style,obj))
    129
    130 -  def SelectProteinNeighborhood(self,aroundObj,inObj,distance=5.0,
    131                                  name='neighborhood',showSurface=False):
    132      """ selects the area of a protein around a specified object/selection name;
    133      optionally adds a surface to that """
    134      self.server.do('select %(name)s,byres (%(aroundObj)s around %(distance)f) and %(inObj)s'%locals())
    135
    136
    137      if showSurface:
    138        self.server.do('show surface,%s'%name)
    139        self.server.do('disable %s'%name)
    140
    141 -  def AddPharmacophore(self,locs,colors,label,sphereRad=0.5):
    142      " adds a set of spheres "
    143      self.server.do('view rdinterface,store')
    144      self.server.resetCGO(label)
    145      for i,loc in enumerate(locs):
    146        self.server.sphere(loc,sphereRad,colors[i],label,1)
    147      self.server.do('enable %s'%label)
    148      self.server.do('view rdinterface,recall')
    149
    150
    151 -  def SetDisplayUpdate(self,val):
    152      if not val:
    153        self.server.do('set defer_update,1')
    154      else:
    155        self.server.do('set defer_update,0')
    156
    157 -  def GetAtomCoords(self,sels):
    158      " returns the coordinates of the selected atoms "
    159      res = {}
    160      for label,idx in sels:
    161        coords = self.server.getAtomCoords('(%s and id %d)'%(label,idx))
    162        res[(label,idx)] = coords
    163      return res
    164
    165 -  def HideAll(self):
    166      self.server.do('disable all')
    167 -  def HideObject(self,objName):
    168      self.server.do('disable %s'%objName)
    169 -  def DisplayObject(self,objName):
    170      self.server.do('enable %s'%objName)
    171
    172 -  def Redraw(self):
    173      self.server.do('refresh')
    174 -  def Zoom(self,objName):
    175      self.server.zoom(objName)
    176
    177 -  def DisplayHBonds(self,objName,molName,proteinName,
    178                      molSelText='(%(molName)s)',
    179                      proteinSelText='(%(proteinName)s and not het)'):
    180      " toggles display of h bonds between the protein and a specified molecule "
    181      cmd = "delete %(objName)s;\n"
    182      cmd += "dist %(objName)s," + molSelText+","+proteinSelText+",mode=2;\n"
    183      cmd += "enable %(objName)s;"
    184      cmd = cmd%locals()
    185
    186      self.server.do(cmd)
    187
    188 -  def DisplayCollisions(self,objName,molName,proteinName,distCutoff=3.0,
    189                          color='red',
    190                          molSelText='(%(molName)s)',
    191                          proteinSelText='(%(proteinName)s and not het)'):
    192      " toggles display of collisions between the protein and a specified molecule "
    193      cmd = "delete %(objName)s;\n"
    194      cmd += "dist %(objName)s," + molSelText+","+proteinSelText+",%(distCutoff)f,mode=0;\n"
    195      cmd += """enable %(objName)s
    196      color %(color)s, %(objName)s"""
    197      cmd = cmd%locals()
    198      self.server.do(cmd)
    199