🆕 Depicting Molecule in Jupyter Notebook
Problem
You would like to depict molecules in Jupyter Notebook.
Difficulty level
🌶️
Download
Download code
Molecule Depiction in Jupiter Notebook¶
In [ ]:
from IPython.display import SVG, Image, display
from openeye import oechem, oedepict
mol = oechem.OEGraphMol()
oechem.OESmilesToMol(mol, "Cn1cnc2c1c(=O)n(c(=O)n2C)C caffeine")
oedepict.OEPrepareDepiction(mol)
image_width, image_height = 300.0, 300.0
PNG Depiction¶
In [2]:
image = oedepict.OEImage(image_width, image_height)
oedepict.OERenderMolecule(image, mol)
oedepict.OEDrawCurvedBorder(image, oedepict.OELightGreyPen, 20)
display(Image(oedepict.OEWriteImageToBytes("png", image)))
In [3]:
display(SVG(oedepict.OEWriteImageToBytes("svg", image)))
SVG Depiction (Resized)¶
The SVG image can be displayed at its original size by using the ResizeSVG class.
In [ ]:
class ResizeSVG:
"""Utility class to add with/height to SVG image."""
def __init__(self, svg: bytes) -> None:
"""Initialize."""
svg_str: str = svg.decode("utf-8")
import re # noqa: PLC0415
match = re.search(r'viewBox="(\d+\.?\d*)\s+(\d+\.?\d*)\s+(\d+\.?\d*)\s+(\d+\.?\d*)"', svg_str)
if match and len(match.groups()) == 4:
width, height = match.group(3), match.group(4)
self.svg_content = svg_str.replace( match.group(), f'width="{width}" height="{height}"')
else:
# SVG can not be resized
self.svg_content = svg_str
def _repr_html_(self) -> str:
return self.svg_content
display(ResizeSVG(oedepict.OEWriteImageToBytes("svg", image)))