Home > database >  How to save rdkit DrawMorganBit output as image?
How to save rdkit DrawMorganBit output as image?

Time:07-18

code:

import numpy as np
from rdkit import Chem
from rdkit.Chem import Draw, AllChem, PandasTools, DataStructs

mol = Chem.MolFromSmiles('O=C1N([C@@H](C)C2CC2)CC3=CC(C4=C(C)N=C(NC(C)=O)S4)=CC(S(=O)(C)=O)=C31')
bi = {}
fp = AllChem.GetMorganFingerprintAsBitVect(mol, radius=3, bitInfo=bi)

fp_arr = np.zeros(1,)
DataStructs.ConvertToNumpyArray(fp, fp_arr)
fp_arr = np.nonzero(fp_arr)[0]

for ar in fp_arr:
    img = Draw.DrawMorganBit(mol, ar, bi, useSVG=True)
    img.save("submol.png")

I want to create an image using DrawMorganBit to know how Molecule's fingerprint bit was generated. (Using PyCharm instead of Jupyter Notebook) However, two problems have arisen: the kekulize problem and the image storage problem. I dont know what's causing the kekulize problem and how to save DrawMorganBit image

rdkit version 2022.3.4

Error

kekulize problem:

rdkit.Chem.rdchem.KekulizeException: Can't kekulize mol.  Unkekulized atoms: 5 6 8 9 14

save problem:

AttributeError: 'str' object has no attribute 'save'

CodePudding user response:

The solution for the problem with kekulizing can be found here: https://github.com/rdkit/rdkit/issues/5129

Your problem with saving the image is that you are trying to save an SVG as a png.

With this code you should get an image with all MorganBits.

from rdkit import Chem
from rdkit.Chem import rdMolDescriptors, Draw
drawOptions = Draw.rdMolDraw2D.MolDrawOptions()
drawOptions.prepareMolsBeforeDrawing = False
from rdkit.Chem.Draw import IPythonConsole

mol = Chem.MolFromSmiles('O=C1N([C@@H](C)C2CC2)CC3=CC(C4=C(C)N=C(NC(C)=O)S4)=CC(S(=O)(C)=O)=C31')

bi = {}
fp = rdMolDescriptors.GetMorganFingerprintAsBitVect(mol, radius=2, bitInfo=bi)

tpls = [(mol, x, bi) for x in fp.GetOnBits()]

p = Draw.DrawMorganBits(tpls, molsPerRow=5, legends=[str(x) for x in fp.GetOnBits()], drawOptions=drawOptions)
p.save('submol.png')
  • Related