Reputation: 1460
I am using jupyter lab to draw chemical structures. But the output image resolution is too low. How can I improve it?
from rdkit import Chem
from rdkit.Chem import Draw
smiles = 'C1=CC(=C(C=C1C2=C(C(=O)C3=C(C=C(C=C3O2)O)O)O)O)O'
m = Chem.MolFromSmiles(smiles)
Draw.MolToImage(m)
Thanks a lot
Upvotes: 4
Views: 11308
Reputation: 495
For those looking for a solution with higher resolution molecule output AND export. The cairosvg
library (also command-line program) has export options for file types including .svg, .pdf, .png, .eps (https://cairosvg.org/).
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem.Draw import rdMolDraw2D
import cairosvg
import io
def molecule_to_pdf(mol, file_name, width=300, height=300):
"""Save substance structure as PDF"""
# Define full path name
full_path = f"./figs/2Dstruct/{file_name}.pdf"
# Render high resolution molecule
drawer = rdMolDraw2D.MolDraw2DSVG(width, height)
drawer.DrawMolecule(mol)
drawer.FinishDrawing()
# Export to pdf
cairosvg.svg2pdf(bytestring=drawer.GetDrawingText().encode(), write_to=full_path)
# Example
m = Chem.MolFromSmiles('Cn1cnc2n(C)c(=O)n(C)c(=O)c12')
molecule_to_pdf(m, "myfav")
Upvotes: 5
Reputation: 1460
I have found a solution, more information can be found here
from rdkit import Chem
from rdkit.Chem.Draw import IPythonConsole
from rdkit.Chem import rdDepictor
from rdkit.Chem.Draw import rdMolDraw2D
from IPython.display import SVG
smiles = 'C1=CC(=C(C=C1C2=C(C(=O)C3=C(C=C(C=C3O2)O)O)O)O)O'
m = Chem.MolFromSmiles(smiles)
def moltosvg(mol, molSize = (300,300), kekulize = True):
mc = Chem.Mol(mol.ToBinary())
if kekulize:
try:
Chem.Kekulize(mc)
except:
mc = Chem.Mol(mol.ToBinary())
if not mc.GetNumConformers():
rdDepictor.Compute2DCoords(mc)
drawer = rdMolDraw2D.MolDraw2DSVG(molSize[0],molSize[1])
drawer.DrawMolecule(mc)
drawer.FinishDrawing()
svg = drawer.GetDrawingText()
return svg.replace('svg:','')
SVG(moltosvg(m))
Upvotes: 3