🆕 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 [ ]:
# (C) 2026 Cadence Design Systems, Inc. (Cadence)
# All rights reserved.
# TERMS FOR USE OF SAMPLE CODE The software below ("Sample Code") is
# provided to current licensees or subscribers of OpenEye products or
# SaaS offerings (each a "Customer").
# Customer is hereby permitted to use, copy, and modify the Sample Code,
# subject to these terms. Cadence claims no rights to Customer's
# modifications. Modification of Sample Code is at Customer's sole and
# exclusive risk. Sample Code may require Customer to have a then
# current license or subscription to the applicable OpenEye offering.
# THE SAMPLE CODE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED. CADENCE DISCLAIMS ALL WARRANTIES, INCLUDING, BUT
# NOT LIMITED TO, WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
# PARTICULAR PURPOSE AND NONINFRINGEMENT. In no event shall Cadence be
# liable for any damages or liability in connection with the Sample Code
# or its use.
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)))