Download Notebook View in GitHub Open in Google Colab
Visualizations in the OpenFF Toolkit
Toolkit Molecule
objects provide some facilities for visualization in the Jupyter Notebook. This can be very useful for inspecting molecules and topologies!
We have implemented three backends:
rdkit
openeye
nglview (requires conformers)
There are two ways to invoke the visualization:
implicitly, by evaluating the object in a cell
explicitly, by calling
Molecule.visualize()
Troubleshooting if NGLView doesn't work
This notebook below demonstrates usage ofnglview
with openforcefield
. This can be tricky to get working. You may need to run an additional command after creating the Conda environment.
To configure for use with Jupyter Notebooks:
jupyter-nbextension enable nglview --py --sys-prefix
To use with Jupyter Lab, configure with:
jupyter labextension install nglview-js-widgets jupyter-labextension install @jupyter-widgets/jupyterlab-manager
For NGLView ≥ 3.0.0, the above should not be necessary; however, it is not yet compatible with Jupyter Lab ≥ 4.0.0.
from openff.toolkit import Molecule
Implicit visualization
Implicit visualization will try to use nglview
if there are conformers and fall back to rdkit
and openeye
(in that order) if they are not available.
m = Molecule.from_smiles("CCCCOCC")
m
The regular display()
call works on Molecule
objects too.
display(m) # noqa
Explicit visualization
Explicit visualization works as one would expect:
m.visualize()
This method can take a backend
parameter, which defaults to rdkit
:
m.visualize(backend="rdkit")
openeye
can also be used, if available:
try:
from openeye import oechem
assert oechem.OEChemIsLicensed()
m.visualize(backend="openeye")
except (ImportError, AssertionError):
print('Visualizing with `backend="openeye"` requires the OpenEye Toolkits')
Visualizing with `backend="openeye"` requires the OpenEye Toolkits
nglview
, if installed, can only be used if conformers have been generated:
try:
m.visualize(backend="nglview") # this will fail because we have no conformers yet
except ValueError as excinfo:
# Catch the exception and print its message
print(str(excinfo))
Visualizing with NGLview requires that the molecule has conformers.
But, once you generate them, it works! You can zoom in/out, rotate and translate the molecule. You can even inspect the different conformers (if available) using the trajectory player:
m.generate_conformers()
m.visualize(backend="nglview")
For example, a benzene ring will not have multiple conformers, so you won’t see the trajectory player.
n = Molecule.from_smiles("c1ccccc1")
n.generate_conformers()
n
Notice that, once conformers are available, the implicit representation will use nglview
to provide a 3D visualization.