Package rdkit :: Package Chem :: Package Draw :: Module IPythonConsole
[hide private]
[frames] | no frames]

Source Code for Module rdkit.Chem.Draw.IPythonConsole

  1  # 
  2  #  Copyright (C) 2011-2017 Greg Landrum 
  3  # 
  4  #   @@ All Rights Reserved @@ 
  5  #  This file is part of the RDKit. 
  6  #  The contents are covered by the terms of the BSD license 
  7  #  which is included in the file license.txt, found at the root 
  8  #  of the RDKit source tree. 
  9  # 
 10  import sys 
 11  import IPython 
 12   
 13  if IPython.release.version < '0.11': 
 14    raise ImportError('this module requires at least v0.11 of IPython') 
 15  try: 
 16    import py3Dmol 
 17    _canUse3D = True 
 18  except ImportError: 
 19    _canUse3D = False 
 20   
 21  from rdkit import Chem 
 22  from rdkit.Chem import rdchem, rdChemReactions 
 23  from rdkit.Chem import Draw 
 24  from rdkit.Chem.Draw import rdMolDraw2D 
 25  from rdkit.six import BytesIO, StringIO 
 26  import copy 
 27  import os 
 28  import json 
 29  import uuid 
 30  import warnings 
 31  import numpy 
 32  try: 
 33    import Image 
 34  except ImportError: 
 35    from PIL import Image 
 36   
 37  from IPython.display import SVG 
 38   
 39  molSize = (450, 150) 
 40  highlightSubstructs = True 
 41  kekulizeStructures = True 
 42  highlightByReactant = False 
 43  ipython_useSVG = False 
 44  ipython_3d = False 
 45  molSize_3d = (400, 400) 
 46  drawing_type_3d = 'stick' # default drawing type for 3d structures 
 47  bgcolor_3d = '0xeeeeee' 
 48  # expose RDLogs to Python StdErr so they are shown 
 49  #  in the IPythonConsole not the server logs. 
 50  Chem.WrapLogs() 
 51   
 52   
53 -def addMolToView(mol,view,confId=-1,drawAs=None):
54 if mol.GetNumAtoms()>=999 or drawAs == 'cartoon': 55 # py3DMol is happier with TER and MASTER records present 56 pdb = Chem.MolToPDBBlock(mol,flavor=0x20|0x10) 57 view.addModel(pdb,'pdb') 58 else: 59 # py3Dmol does not currently support v3k mol files, so 60 # we can only provide those with "smaller" molecules 61 mb = Chem.MolToMolBlock(mol,confId=confId) 62 view.addModel(mb,'sdf') 63 if drawAs is None: 64 drawAs = drawing_type_3d 65 view.setStyle({drawAs:{}})
66
67 -def drawMol3D(m,view=None,confId=-1,drawAs=None,bgColor=None,size=None):
68 if bgColor is None: 69 bgColor = bgcolor_3d 70 if size is None: 71 size=molSize_3d 72 if view is None: 73 view = py3Dmol.view(width=size[0],height=size[1]) 74 view.removeAllModels() 75 try: 76 iter(m) 77 except TypeError: 78 addMolToView(m,view,confId,drawAs) 79 else: 80 ms = m 81 for m in ms: 82 addMolToView(m,view,confId,drawAs) 83 84 view.setBackgroundColor(bgColor) 85 view.zoomTo() 86 return view.show()
87
88 -def _toJSON(mol):
89 """For IPython notebook, renders 3D webGL objects.""" 90 if not ipython_3d or not mol.GetNumConformers(): 91 return None 92 conf = mol.GetConformer() 93 if not conf.Is3D(): 94 return None 95 return drawMol3D(mol).data
96 97
98 -def _toPNG(mol):
99 if hasattr(mol, '__sssAtoms'): 100 highlightAtoms = mol.__sssAtoms 101 else: 102 highlightAtoms = [] 103 kekulize=kekulizeStructures 104 return Draw._moltoimg(mol,molSize,highlightAtoms,"",returnPNG=True, 105 kekulize=kekulize)
106 107
108 -def _toSVG(mol):
109 if not ipython_useSVG: 110 return None 111 if hasattr(mol, '__sssAtoms'): 112 highlightAtoms = mol.__sssAtoms 113 else: 114 highlightAtoms = [] 115 kekulize=kekulizeStructures 116 return Draw._moltoSVG(mol,molSize,highlightAtoms,"",kekulize)
117 118
119 -def _toReactionPNG(rxn):
120 rc = copy.deepcopy(rxn) 121 img = Draw.ReactionToImage(rc, subImgSize=(int(molSize[0] / 3), molSize[1]), 122 highlightByReactant=highlightByReactant) 123 bio = BytesIO() 124 img.save(bio, format='PNG') 125 return bio.getvalue()
126
127 -def _toReactionSVG(rxn):
128 if not ipython_useSVG: 129 return None 130 rc = copy.deepcopy(rxn) 131 return Draw.ReactionToImage(rc, subImgSize=(int(molSize[0] / 3), molSize[1]), 132 useSVG=True,highlightByReactant=highlightByReactant)
133
134 -def _GetSubstructMatch(mol, query, **kwargs):
135 res = mol.__GetSubstructMatch(query, **kwargs) 136 if highlightSubstructs: 137 mol.__sssAtoms = list(res) 138 else: 139 mol.__sssAtoms = [] 140 return res
141 142
143 -def _GetSubstructMatches(mol, query, **kwargs):
144 res = mol.__GetSubstructMatches(query, **kwargs) 145 mol.__sssAtoms = [] 146 if highlightSubstructs: 147 for entry in res: 148 mol.__sssAtoms.extend(list(entry)) 149 return res
150 151 152 # code for displaying PIL images directly,
153 -def display_pil_image(img):
154 """displayhook function for PIL Images, rendered as PNG""" 155 bio = BytesIO() 156 img.save(bio, format='PNG') 157 return bio.getvalue()
158 159 160 _MolsToGridImageSaved = None 161 162
163 -def ShowMols(mols, maxMols=50, **kwargs):
164 global _MolsToGridImageSaved 165 if 'useSVG' not in kwargs: 166 kwargs['useSVG'] = ipython_useSVG 167 if _MolsToGridImageSaved is not None: 168 fn = _MolsToGridImageSaved 169 else: 170 fn = Draw.MolsToGridImage 171 if len(mols)>maxMols: 172 warnings.warn("Truncating the list of molecules to be displayed to %d. Change the maxMols value to display more."%(maxMols)) 173 mols = mols[:maxMols] 174 for prop in ('legends','highlightAtoms','highlightBonds'): 175 if prop in kwargs: 176 kwargs[prop] = kwargs[prop][:maxMols] 177 178 res = fn(mols, **kwargs) 179 if kwargs['useSVG']: 180 return SVG(res) 181 else: 182 return res
183 184
185 -def InstallIPythonRenderer():
186 global _MolsToGridImageSaved 187 rdchem.Mol._repr_png_ = _toPNG 188 rdchem.Mol._repr_svg_ = _toSVG 189 if _canUse3D: 190 rdchem.Mol._repr_html_ = _toJSON 191 rdChemReactions.ChemicalReaction._repr_png_ = _toReactionPNG 192 rdChemReactions.ChemicalReaction._repr_svg_ = _toReactionSVG 193 if not hasattr(rdchem.Mol, '__GetSubstructMatch'): 194 rdchem.Mol.__GetSubstructMatch = rdchem.Mol.GetSubstructMatch 195 rdchem.Mol.GetSubstructMatch = _GetSubstructMatch 196 if not hasattr(rdchem.Mol, '__GetSubstructMatches'): 197 rdchem.Mol.__GetSubstructMatches = rdchem.Mol.GetSubstructMatches 198 rdchem.Mol.GetSubstructMatches = _GetSubstructMatches 199 Image.Image._repr_png_ = display_pil_image 200 _MolsToGridImageSaved = Draw.MolsToGridImage 201 Draw.MolsToGridImage = ShowMols 202 rdchem.Mol.__DebugMol = rdchem.Mol.Debug 203 rdchem.Mol.Debug = lambda self, useStdout=False: self.__DebugMol(useStdout=useStdout)
204 205 206 InstallIPythonRenderer() 207 208
209 -def UninstallIPythonRenderer():
210 global _MolsToGridImageSaved 211 del rdchem.Mol._repr_svg_ 212 del rdchem.Mol._repr_png_ 213 if _canUse3D: 214 del rdchem.Mol._repr_html_ 215 del rdChemReactions.ChemicalReaction._repr_png_ 216 if hasattr(rdchem.Mol, '__GetSubstructMatch'): 217 rdchem.Mol.GetSubstructMatch = rdchem.Mol.__GetSubstructMatch 218 del rdchem.Mol.__GetSubstructMatch 219 if hasattr(rdchem.Mol, '__GetSubstructMatches'): 220 rdchem.Mol.GetSubstructMatches = rdchem.Mol.__GetSubstructMatches 221 del rdchem.Mol.__GetSubstructMatches 222 del Image.Image._repr_png_ 223 if _MolsToGridImageSaved is not None: 224 Draw.MolsToGridImage = _MolsToGridImageSaved 225 if hasattr(rdchem.Mol, '__DebugMol'): 226 rdchem.Mol.Debug = rdchem.Mol.__DebugMol 227 del rdchem.Mol.__DebugMol
228