File: DSViewer.py

package info (click to toggle)
rdkit 202009.4-1
  • links: PTS, VCS
  • area: main
  • in suites: bullseye
  • size: 129,624 kB
  • sloc: cpp: 288,030; python: 75,571; java: 6,999; ansic: 5,481; sql: 1,968; yacc: 1,842; lex: 1,254; makefile: 572; javascript: 461; xml: 229; fortran: 183; sh: 134; cs: 93
file content (370 lines) | stat: -rw-r--r-- 12,125 bytes parent folder | download | duplicates (2)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
# $Id$
#
# Copyright (C) 2005-2006 Rational Discovery LLC
#
#   @@ All Rights Reserved @@
#  This file is part of the RDKit.
#  The contents are covered by the terms of the BSD license
#  which is included in the file license.txt, found at the root
#  of the RDKit source tree.
#
""" uses DSViewer to interact with molecules

"""
from rdkit import Chem
from win32com.client import Dispatch
import tempfile, os

_nextDisplayId = 1


class Displayable(object):

  def __init__(self, doc, id=-1):
    global _nextDisplayId
    if id < 0:
      id = _nextDisplayId
      _nextDisplayId += 1

    self.doc = doc
    self.id = id
    self.visible = True
    self.children = []

  def Select(self, atoms=[], state=True, recurse=False):
    if state:
      selText = 'true'
    else:
      selText = 'false'
    if not atoms or atoms == '*':
      atomStr = '; atom "*"'
    else:
      # DSViewer has atom ids from 1, we do it from 0:
      atoms = ['id=%d' % (x) for x in atoms]
      atomStr = '; atom %s' % ','.join(atoms)

    cmd = 'SetProperty object RD_Visual=%d %s: select=%s' % (self.id, atomStr, selText)
    r = int(str(self.doc.DoCommand(cmd)))
    if not r and not atoms:
      # this handles an annoying case where if you try to select
      # a molecule by ID in DSViewer, you get nothing selected:
      atomStr = ''
      cmd = 'SetProperty object RD_Visual=%d %s: select=%s' % (self.id, atomStr, selText)
      r = int(str(self.doc.DoCommand(cmd)))
    #print 'sel cmd:',cmd
    #print 'result:', r

    # stupid DSViewer will select the bonds between pairs of highlighted atoms,
    # stop that nonsense right now:
    if r:
      cmd = 'SetProperty object RD_Visual=%d; bond index="*": select=off' % (self.id)
      self.doc.DoCommand(cmd)

    if recurse:
      for child in self.children:
        child.Select(atoms=atoms, state=state, recurse=True)
    return r

  def Hide(self, recurse=True):
    self.Select(state=True, recurse=True)
    self.doc.DoCommand('hide')
    self.Select(state=False, recurse=True)

  def Show(self, recurse=True):
    self.Select(state=True, recurse=True)
    self.doc.DoCommand('Show')
    self.Select(state=False, recurse=True)

  def ShowOnly(self, recurse=True):
    self.doc.DoCommand('HideAll')
    self.Select(state=True, recurse=True)
    self.doc.DoCommand('Show')
    self.Select(state=False, recurse=True)

  def __del__(self):
    self.doc.DoCommand('UnselectAll')
    count = self.Select(state=True, recurse=True)
    if count:
      self.doc.DoCommand('Delete')


class MolViewer(object):

  def __init__(self, force=0, title='Untitled', **kwargs):
    self.app = Dispatch('WebLabViewerPro.Application')
    self.app.Visible = 1
    if force or self.app.ActiveDocument is None:
      self.doc = self.app.New(title)
    else:
      self.doc = self.app.ActiveDocument

    self.displayables = {}

  def DeleteAll(self):
    self.doc.DoCommand('SelectAll')
    self.doc.DoCommand('Delete')
    self.displayables = {}

  def DeleteAllExcept(self, excludes):
    excludes = [x.lower() for x in excludes]
    allNames = self.displayables.keys()
    for nm in allNames:
      if nm not in excludes:
        del self.displayables[nm]

  def ShowMol(self, mol, name='molecule', showOnly=True, highlightFeatures=[], molB="", confId=-1,
              zoom=True):
    if showOnly:
      self.DeleteAll()
      obj = None
    else:
      obj = self.displayables.get(name.lower(), None)
      #if obj:
      #  obj.Select(state=True)
      #  self.doc.DoCommand('Delete')
      #  obj.Select(state=False)

    if not molB:
      molB = Chem.MolToMolBlock(mol, confId=confId)

    tmp = name + "\n" + molB[molB.index('\n') + 1:]
    molB = tmp

    if not obj:
      obj = Displayable(self.doc)
    if not hasattr(obj, '_molBlock') or obj._molBlock != molB:
      obj._molBlock = molB
      with tempfile.NamedTemporaryFile('w+', suffix='.mol') as tmpf:
        tmpf.write(molB)
      self.doc.DoCommand('PasteFrom %s' % tmp.name)
      self.doc.DoCommand('SetProperty molecule id=0 : RD_Visual=%d' % (obj.id))
      self.doc.DoCommand('SetProperty molecule id=0 : id=%d' % (obj.id))
      self.doc.DoCommand('SetProperty molecule id=0 : select=off')
    else:
      obj.Select(state=True)
      self.doc.DoCommand('Show')

    self.displayables[name.lower()] = obj

    if zoom:
      self.doc.DoCommand('Center')
      self.doc.DoCommand('FitView')

    return

  def LoadFile(self, filename, name, showOnly=False):
    if showOnly:
      self.DeleteAll()
    self.doc.DoCommand('PasteFrom %s' % filename)
    obj = Displayable(self.doc)
    self.doc.DoCommand('SetProperty molecule id=0 : id=%d' % (obj.id))
    self.doc.DoCommand('SetProperty molecule id=0 : select=off')
    count = self.doc.DoCommand('SetProperty AminoAcidChain id=0 : RD_Visual=%d' % (obj.id))
    if not count or int(count) <= 0:
      count = self.doc.DoCommand('SetProperty molecule id=0 : RD_Visual=%d' % (obj.id))
    self.displayables[name.lower()] = obj
    return obj

  def GetSelectedAtoms(self, whichSelection=''):
    #print 'WHICH',repr(whichSelection), whichSelection.lower() in self.displayables
    if not whichSelection:
      d = str(self.doc.DoCommand('GetPropertyValue atom select=true: id=?'))
      d2 = str(self.doc.DoCommand('GetPropertyValue atom select=true: molecule=?'))
      if d2:
        molIds = []
        tmpD = {}
        for id in d2.split(','):
          id = int(id.split('/')[1]) + 1
          if id in tmpD:
            molIds.append(tmpD[id])
          else:
            for k, v in self.displayables.iteritems():
              if id == v.id:
                tmpD[id] = k
                molIds.append(k)
      else:
        molIds = [''] * (d.count(',') + 1)
    elif whichSelection.lower() in self.displayables:
      whichSelection = whichSelection.lower()
      whichSelection = self.displayables[whichSelection].id
      d = str(
        self.doc.DoCommand('GetPropertyValue molecule RD_Visual=%d; atom select=true: id=?' %
                           whichSelection))
      molIds = [whichSelection] * (d.count(',') + 1)
    else:
      d = None
      molIds = None

    if d:
      splitD = d.split(',')
      #print 'splitD:',splitD
      #print 'molIds:',molIds
      try:
        res = []
        for i in range(len(splitD)):
          # DSViewer has atom ids from 1, we do it from 0:
          idx = int(splitD[i])
          res.append((molIds[i], idx))
      except Exception:
        import traceback
        traceback.print_exc()
        res = []
    else:
      res = []
    return res

  def HighlightAtoms(self, indices, where, extraHighlight=False):
    self.doc.DoCommand('UnSelectAll')
    self.SelectAtoms(where, indices)

  def SelectAtoms(self, itemId, atomIndices, selName='selection'):
    self.doc.DoCommand('UnSelectAll')
    self.doc.DoCommand('SetProperty atom id="*": select=off')
    o = self.displayables.get(itemId.lower(), None)
    #print 'O:',itemId,atomIndices
    if o:
      o.Select(atoms=atomIndices)

  def SetDisplayUpdate(self, val):
    if not val:
      self.doc.DoCommand('UpdateView off')
    else:
      self.doc.DoCommand('UpdateView on')

  def GetAtomCoords(self, sels):
    res = {}
    for label, idx in sels:
      whichSelection = label.lower()
      whichSelection = self.displayables[label].id
      # DSViewer has atom ids from 1, we do it from 0:
      idx += 1
      cmd = 'GetPropertyValue molecule RD_Visual=%d; atom id=%d: xyz=?' % (whichSelection, idx)
      coords = self.doc.DoCommand(cmd)
      coords = [float(x) for x in coords.split(' ')]
      res[(label, idx)] = coords
      #print 'grab:',label,idx,coords
    return res

  def AddPharmacophore(self, locs, colors, label, sphereRad=0.5):
    label = label.lower()
    self.SetDisplayUpdate(False)
    parent = Displayable(self.doc)
    for i, loc in enumerate(locs):
      color = colors[i]
      color = ' '.join([str(int(255 * x)) for x in color])
      obj = Displayable(self.doc)
      nm = 'sphere-%d' % obj.id
      self.doc.DoCommand('Sphere %s' % nm)
      self.doc.DoCommand('SetProperty Object name=%s : xyz=%f %f %f' % (nm, loc[0], loc[1], loc[2]))
      self.doc.DoCommand('SetProperty Object name=%s : radius=%f' % (nm, sphereRad))
      self.doc.DoCommand('SetProperty Object name=%s : color=%s' % (nm, color))
      self.doc.DoCommand('SetProperty Object name=%s : RD_Visual=%d' % (nm, parent.id))
      self.doc.DoCommand('SetProperty Object name=%s : id=%d' % (nm, parent.id))
      #parent.children.append(obj)
    self.displayables[label] = parent
    self.SetDisplayUpdate(True)

  def SetDisplayStyle(self, obj, style=''):
    self.doc.DoCommand('UnSelectAll')
    obj = obj.lower()
    o = self.displayables.get(obj, None)
    if o:
      o.Select(state=True)
      if style == 'sticks':
        self.doc.DoCommand('DisplayStyle Atom Stick')
      elif style == 'lines':
        self.doc.DoCommand('DisplayStyle Atom Line')
      elif style == '':
        self.doc.DoCommand('DisplayStyle Atom Off')
      o.Select(state=False)

  def HideAll(self):
    self.doc.DoCommand('HideAll')

  def HideObject(self, objName):
    self.doc.DoCommand('UnSelectAll')
    objName = objName.lower()
    o = self.displayables.get(objName, None)
    if o:
      o.Hide()

  def DisplayObject(self, objName):
    self.doc.DoCommand('UnSelectAll')
    objName = objName.lower()
    o = self.displayables.get(objName, None)
    if o:
      o.Show()

  def Zoom(self, objName):
    self.doc.DoCommand('UnSelectAll')
    objName = objName.lower()
    o = self.displayables.get(objName, None)
    if o:
      r = o.Select(state=True)
      self.doc.DoCommand('Center')
      self.doc.DoCommand('FitView')
      o.Select(state=False)

  def SelectProteinNeighborhood(self, aroundObj, inObj, distance=5.0, name='neighborhood',
                                showSurface=False):
    """ FIX: the surface display stuff here is all screwed up due to
    differences between the way PyMol and DSViewer handle surfaces.
    In PyMol they are essentially a display mode for the protein, so
    they don't need to be managed separately.
    In DSViewer, on the other hand, the surface is attached to the
    protein, but it needs to be hidden or shown on its own.  I haven't
    figured out how to do that yet.
    """
    self.doc.DoCommand('UnSelectAll')
    o = self.displayables.get(aroundObj.lower(), None)
    p = self.displayables.get(inObj.lower(), None)
    if o and p:
      self.SetDisplayUpdate(False)
      p.Show()
      self.doc.DoCommand('UnSelectAll')
      tmp = self.doc.DoCommand('SetProperty object RD_Visual=%d;object id="*":select=on' % o.id)
      tmp = self.doc.DoCommand('SelectByRadius inside %f atom' % distance)
      # that selects all atoms in the radius, now we need to make sure 
      #  only atoms in _inObj_ are selected:
      for obj in self.displayables.values():
        if obj.id != p.id:
          self.doc.DoCommand('SetProperty object RD_Visual=%d;object id="*":select=off' % obj.id)

      # ----
      # now get all the residue names for the selected atoms:
      rs = self.doc.DoCommand('GetPropertyValue atom select=true: parent=?')
      if rs:
        rs = rs.split(',')
        residues = {}
        for r in rs:
          residues[r] = 1

        # and select each atom in those residues:
        parents = ','.join(['parent="%s"' % x for x in residues.keys()])
        cmd = 'SetProperty atom %s: select=on' % parents
        tmp = self.doc.DoCommand(cmd)
      if showSurface:
        # create the surface:
        self.doc.DoCommand('Surface')
        obj = Displayable(self.doc)
        self.displayables[name] = obj
        self.doc.DoCommand('SetProperty surface id="*":RD_Visual=%d' % obj.id)

        self.doc.DoCommand('UnSelectAll')

      self.SetDisplayUpdate(True)

  def Redraw(self):
    self.SetDisplayUpdate(True)


if __name__ == '__main__':
  from rdkit import Chem
  from rdkit.Chem import rdDistGeom, rdForceFieldHelpers

  m = Chem.MolFromSmiles('c1cccc2c1cccc2')
  rdDistGeom.EmbedMolecule(m)
  rdForceFieldHelpers.UFFOptimizeMolecule(m)

  s = MolViewer()
  s.ShowMol(m)