Draw molecules as SVG in horizontal layout #Drawing #RDKit #memo

As you know, Greg posted cool code about new drawing code options of rdkit 202003. You can read details of them in following URL

It’s really cool! New version of rdkit can render molecule with many options in high quarity.

In the post, molecules are rendered as SVG image one molecule per one cell.

I would like to draw molecules in one cells like Draw.MolsToGridImage.

So I traced the blog post and try to render molecules in one cell. I found good solution to do it, the strategy is that get svg text of molecules and embed them in to the div tag and then draw it as HTML.

OK let’s try it. Following code is almost same but example molecules are different. Defined HorizontalDisplay class for displaying multiple molecules at later.

import os
from rdkit import Chem
from rdkit.Chem import rdBase
from rdkit.Chem import RDConfig
from rdkit.Chem import AllChem
from rdkit.Chem import Draw
from rdkit.Chem.Draw import rdMolDraw2D
from rdkit.Chem.Draw import IPythonConsole
from rdkit.Chem import rdDepictor
import rdkit
from IPython.display import SVG

from rdkit.Chem import ChemicalFeatures
fdef = os.path.join(RDConfig.RDContribDir, 'M_Kossner/BaseFeatures_DIP2_NoMicrospecies.fdef')
ffact = ChemicalFeatures.BuildFeatureFactory(fdef)

# the code is bollowed from following url.
# https://bit.ly/3aTUBCU
class HorizontalDisplay:
    def __init__(self, *args):
        self.args = args

    def _repr_html_(self):
        template = '<div style="float:left;padding:10px;">{0}</div>'
        return "\n".join(template.format(arg)
                         for arg in self.args)

Then draw molecules one by one and get SVGdrawing text of each drawing setting. First two codes are draw molecule with / without atom indices. And 3rd, 4th codes are draw molecules with atom features.

d2d = rdMolDraw2D.MolDraw2DSVG(250, 200)
text1 = d2d.GetDrawingText()

d2d = rdMolDraw2D.MolDraw2DSVG(250, 200)
d2d.drawOptions().addAtomIndices = True
text2 = d2d.GetDrawingText()

from collections import defaultdict
feats = ffact.GetFeaturesForMol(mol1)
colors = {'SingleAtomDonor':(1,0.5,0.5),

atomHighlighs = defaultdict(list)
highlightRads = {}
for feat in feats:
    if feat.GetType() in colors:
        clr = colors[feat.GetType()]
        for aid in feat.GetAtomIds():
            highlightRads[aid] = 0.4

d2d = rdMolDraw2D.MolDraw2DSVG(250, 200)
d2d.DrawMoleculeWithHighlights(mol1, '', dict(atomHighlighs), {}, highlightRads, {})
d2d.drawOptions().addAtomIndices = True
text3 = d2d.GetDrawingText()

d2d = rdMolDraw2D.MolDraw2DSVG(250, 200)
dos = d2d.drawOptions()
dos.atomHighlightsAreCricle = True
dos.fillHighlights = False
d2d.DrawMoleculeWithHighlights(mol1, '', dict(atomHighlighs), {}, highlightRads, {})
d2d.drawOptions().addAtomIndices = True
text4 = d2d.GetDrawingText()

Now I had 4 svg texts. Finally call HorizontalDisplay.

HorizontalDisplay(text1, text2, text3, text4)

Now I could get multiple molecules in one cell ;).

It can’t control the number of the molecules in one row, so it seems there is room for improvement. Any comments and suggestions will be greatly appreciated.

I uploaded the code my github repo and gist. And hope reader will have a nice weekend. (gist couldn’t draw molecules per row)

Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.




Published by iwatobipen

I'm medicinal chemist in mid size of pharmaceutical company. I love chemoinfo, cording, organic synthesis, my family.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.

%d bloggers like this: