Plotting RDKit mols

This snippet isn't very advanced, and I've seen several flavours of it around. Nevertheless I need it all the time, and always forget it - here's a copy so I know where to find it, and you might find it helpful, too. It overlays 3D RDKit molecules using py3Dmol with optional colouring or conformer information.

      
 import py3Dmol
 def viewProt(mol, view=None, color='orange',confid=0):
     if view is None:
         view = py3Dmol.view()
     view.addModel(Chem.MolToMolBlock(mol,confId=confid), "sdf")

     model = view.getModel()
     model.setStyle({}, {"stick": {"colorscheme": f"{color}Carbon"}})
     view.zoomTo()
     return view

Here's how to draw a pocket and ligand:

      
 view = viewProt(pocket)
 view = viewProt(ligand, view=view, color='green')
 view #output the view at the end of a jupyter notebook cell to render

Draw hydrogen bonds:

        
 view = viewProt(pocket)
 #get hbonds from somewhere (future blog post!),
 #e.g. np.array([[hbd_idx, hba_idx, angle], [...]])
 hbonds_arr = ...
 xyz = pocket.GetConformer(0).GetPositions()
 for hbd, hba in zip(hbonds_arr[:,0], hbonds_arr[:,1]):
     view.addCylinder({'color':'darkblue',
                 'start':{'x':xyz[hbd][0],'y':xyz[hbd][1],'z':xyz[hbd][2]},
                 'end':{'x':xyz[hba][0],'y':xyz[hba][1],'z':xyz[hba][2]},
                 'radius':0.1, 'dashed':True});
 view 

Highlight some atoms:


 for idx in atoms_of_interest_indices:
     view.addSphere({'radius':1, "center":{"x":xyz[idx][0], "y":xyz[idx][1], "z":xyz[idx][2]},
         "wireframe":True, "color":"pink"})
 view

Overlay conformers of a molecule:


  core = Chem.MolFromMolFile(....)
  ms = []
  for i in range(10):
      m = Chem.MolFromSmiles('...')
      mH = Chem.AddHs(m)
      AllChem.ConstrainedEmbed(mH, core)
      ms.append(mH)
  view = viewProt(ms[0])
  for i in range(1,10):
      view = viewProt(ms[i], confid=i)
  view