# MD trajectories#

In this section, we will see how to use py3Dmol to visualize MD trajectories, either as an animation, as well as using a slider to observe each individual step. We first need to import the required modules:

import py3Dmol as p3d
import ipywidgets


Assuming that we have the MD trajectory saved in a PDB file, we need to write a routine which reads all the steps from the PDB file and returns them as text, as required by the Py3Dmol viewer.

def read_pdb_file(file_name):
"""Reads the MD trajectory from a PDB file."""
pdb_file = open(file_name, "r")
pdb_file.close()
return data


We can now create an animation of the dynamics.

pdb_file_name = '../../data/md/bithiophene.pdb'
viewer = p3d.view(width=600, height=300)

viewer.animate({"loop": "forward"})
# visualize with the stick option - can also consider spheres and more
viewer.setStyle({"stick": {}})
viewer.show()


You appear to be running in JupyterLab (or JavaScript failed to load for some other reason). You need to install the 3dmol extension:
jupyter labextension install jupyterlab_3dmol

If instead we would like to observe each step (in this case, each step is 1 ps) individually, we need a routine which reads one configuration at a time from the PDB file.

def read_pdb_index(file_name, index=0):
"""Reads one configuration defined by its index from a PDB file."""
pdb_file = open(file_name, "r")
current_index = 0
data = ""
for line in pdb_file:
if index == current_index:
data += line
if 'ENDMDL' in line:
if index == current_index:
break
current_index += 1
pdb_file.close()
return data


Additionally, we need a routine which creates a py3Dmol viewer for each configuration.

def return_viewer(file_name, step=0):

Now we can create a widget with a slider that allows us to visualize one configuration at a time. To do so, we make use of the ipywidgets module which allows to interactively change the parameters of a Python routine. In our case, we use ipywidgets to allow the user to set the trajectory file name and step index required by the return_viewer routine which generates the py3Dmol viewer. The step is set using a slider widget which allows the user to select any value between the defined limits. Below we show a static picture of how the widget looks in a Jupyter notebook.
total_steps = 100 # number of configurations in the trajectory file