rdkit.Chem.Draw.IPythonConsole

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    return Draw._moltoSVG(mol,molSize,highlightAtoms,"",kekulize)
    116
    117
    118 -def _toReactionPNG(rxn):
    119    rc = copy.deepcopy(rxn)
    120    img = Draw.ReactionToImage(rc, subImgSize=(int(molSize[0] / 3), molSize[1]),
    121                               highlightByReactant=highlightByReactant)
    122    bio = BytesIO()
    123    img.save(bio, format='PNG')
    124    return bio.getvalue()
    125
    126 -def _toReactionSVG(rxn):
    127    if not ipython_useSVG:
    128      return None
    129    rc = copy.deepcopy(rxn)
    130    return Draw.ReactionToImage(rc, subImgSize=(int(molSize[0] / 3), molSize[1]),
    131                                useSVG=True,highlightByReactant=highlightByReactant)
    132
    133 -def _GetSubstructMatch(mol, query, **kwargs):
    134    res = mol.__GetSubstructMatch(query, **kwargs)
    135    if highlightSubstructs:
    136      mol.__sssAtoms = list(res)
    137    else:
    138      mol.__sssAtoms = []
    139    return res
    140
    141
    142 -def _GetSubstructMatches(mol, query, **kwargs):
    143    res = mol.__GetSubstructMatches(query, **kwargs)
    144    mol.__sssAtoms = []
    145    if highlightSubstructs:
    146      for entry in res:
    147        mol.__sssAtoms.extend(list(entry))
    148    return res
    149
    150
    151  # code for displaying PIL images directly,
    152 -def display_pil_image(img):
    153    """displayhook function for PIL Images, rendered as PNG"""
    154    bio = BytesIO()
    155    img.save(bio, format='PNG')
    156    return bio.getvalue()
    157
    158
    159  _MolsToGridImageSaved = None
    160
    161
    162 -def ShowMols(mols, maxMols=50, **kwargs):
    163    global _MolsToGridImageSaved
    164    if 'useSVG' not in kwargs:
    165      kwargs['useSVG'] = ipython_useSVG
    166    if _MolsToGridImageSaved is not None:
    167      fn = _MolsToGridImageSaved
    168    else:
    169      fn = Draw.MolsToGridImage
    170    if len(mols)>maxMols:
    171      warnings.warn("Truncating the list of molecules to be displayed to %d. Change the maxMols value to display more."%(maxMols))
    172      mols = mols[:maxMols]
    173      for prop in ('legends','highlightAtoms','highlightBonds'):
    174        if prop in kwargs:
    175          kwargs[prop] = kwargs[prop][:maxMols]
    176
    177    res = fn(mols, **kwargs)
    178    if kwargs['useSVG']:
    179      return SVG(res)
    180    else:
    181      return res
    182
    183
    184 -def InstallIPythonRenderer():
    185    global _MolsToGridImageSaved
    186    rdchem.Mol._repr_png_ = _toPNG
    187    rdchem.Mol._repr_svg_ = _toSVG
    188    if _canUse3D:
    189      rdchem.Mol._repr_html_ = _toJSON
    190    rdChemReactions.ChemicalReaction._repr_png_ = _toReactionPNG
    191    rdChemReactions.ChemicalReaction._repr_svg_ = _toReactionSVG
    192    if not hasattr(rdchem.Mol, '__GetSubstructMatch'):
    193      rdchem.Mol.__GetSubstructMatch = rdchem.Mol.GetSubstructMatch
    194    rdchem.Mol.GetSubstructMatch = _GetSubstructMatch
    195    if not hasattr(rdchem.Mol, '__GetSubstructMatches'):
    196      rdchem.Mol.__GetSubstructMatches = rdchem.Mol.GetSubstructMatches
    197    rdchem.Mol.GetSubstructMatches = _GetSubstructMatches
    198    Image.Image._repr_png_ = display_pil_image
    199    _MolsToGridImageSaved = Draw.MolsToGridImage
    200    Draw.MolsToGridImage = ShowMols
    201    rdchem.Mol.__DebugMol = rdchem.Mol.Debug
    202    rdchem.Mol.Debug = lambda self, useStdout=False: self.__DebugMol(useStdout=useStdout)
    203
    204
    205  InstallIPythonRenderer()
    206
    207
    208 -def UninstallIPythonRenderer():
    209    global _MolsToGridImageSaved
    210    del rdchem.Mol._repr_svg_
    211    del rdchem.Mol._repr_png_
    212    if _canUse3D:
    213      del rdchem.Mol._repr_html_
    214    del rdChemReactions.ChemicalReaction._repr_png_
    215    if hasattr(rdchem.Mol, '__GetSubstructMatch'):
    216      rdchem.Mol.GetSubstructMatch = rdchem.Mol.__GetSubstructMatch
    217      del rdchem.Mol.__GetSubstructMatch
    218    if hasattr(rdchem.Mol, '__GetSubstructMatches'):
    219      rdchem.Mol.GetSubstructMatches = rdchem.Mol.__GetSubstructMatches
    220      del rdchem.Mol.__GetSubstructMatches
    221    del Image.Image._repr_png_
    222    if _MolsToGridImageSaved is not None:
    223      Draw.MolsToGridImage = _MolsToGridImageSaved
    224    if hasattr(rdchem.Mol, '__DebugMol'):
    225      rdchem.Mol.Debug = rdchem.Mol.__DebugMol
    226      del rdchem.Mol.__DebugMol
    227