Search code examples
visual-studio-codejupyter-notebookrdkit

Why is this rdkit script not working in visual studio code?


I've been using VS code via jupyter notebook. So, I have to produce grid image of 15 molecules and save it to my computer, but the script I've been using is not showing any errors, but still doesn't produce any images nor save them to designated file to my computer even though the cell gas been executed successfully.

I'm fresh and new to the world of computational chemistry and would appreciate any help!

My script is below.

from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem.Draw import MolsToGridImage
from rdkit.Chem import SDMolSupplier

suppl = Chem.SDMolSupplier('chemspidersdf/database.sdf')
ms = [x for x in suppl if x is not None]
for m in ms: tmp=AllChem.Compute2DCoords(m)
img=Draw.MolsToGridImage(ms[:15],molsPerRow=5,subImgSize=(200,200),legends=[x.GetProp("_Name") for x in ms[:15]])
img.save('gridpng/test_molgrid.o.png') 

Solution

  • Because you are using Jupyter the output of MolsToGridImage is likely not what you expect. In Jupyter the function returns an IPython.core.display.Image. You can save this to a png like so:

    img = Draw.MolsToGridImage(mymols)
    
    with open('molgrid.png', 'wb') as png:
        png.write(img.data)
    

    When run in a standard interpreter the function returns a PIL.PngImagePlugin.PngImageFile.

    You could also return to the original behaviour (outside of jupyter) by uninstalling the IPython renderer although this would remove the nice behaviour of being able to see your molecule images displayed in the notebook.

    from rdkit.Chem.Draw import IPythonConsole
    
    IPythonConsole.UninstallIPythonRenderer()
    img = Draw.MolsToGridImage(mymols)
    img.save('molgrid.png')