Search code examples
pythonchemistryrdkit

Create a scaled molecule rdkit


I am using RDKit in python to draw a molecule, and I want to get a high-definition image

This is my current code

mol = Chem.MolFromSmiles("CCO")
mol = Chem.AddHs(mol)
img = Draw.MolToImage(mol)

I want it to be ~ 2000x1000 pixels

I tried: img = Draw.MolToImage(mol, size = (2000,1000)) but although the canvas increases in size, the line width and font size remains constant.

Scaling with img.resize() is not ok because I want to get a non-pixelated output.

The closes to an answer is this. However when I try creating its parent class I get an error:

>> a = Draw.rdMolDraw2D.MolDraw2D()
RuntimeError: This class cannot be instantiated from Python

tldr; I am trying to find out a way to scale the image while it is rendering.

I am also ok using an alternative to RDKit, all I need is a way to display chemical structures from SMILES in a high-def (2000x1000) image.

Side question: Is there a way to show carbon atoms too? Can't find any docs for both these questions.


Solution

  • I ended up first rendering as a svg and then scaling + converting to a png, here is the implementation:

    from rdkit import Chem
    from rdkit.Chem import Draw
    import cairosvg  #You can use some toher library to convert svg to png
    
    mol = Chem.MolFromSmiles("CCO")
    mol = Chem.AddHs(mol)
    
    drawer = Draw.MolDraw2DSVG(300, 150) #You can adjust this, however to keep it looking good, both width,height should be between 150-400 inclusive.
    drawer.DrawMolecule(mol)
    drawer.FinishDrawing()
    
    svg_data = drawer.GetDrawingText()
    cairosvg.svg2png(bytestring=svg_data.encode('utf-8'), write_to="molecule.png", scale=10) #Adjust scale for higher-def image