1. Running pymol as a module in jupyter notebook is the best way to make your first movie. (c)

1.1 Importing pymol as a python module. Running pymol in viewer window.

In [1]:
# Importing pymol module

import __main__
__main__.pymol_argv = [ 'pymol', '-x' ]

import pymol
pymol.finish_launching()
from pymol import cmd,stored

1.2 Fetching a structure and creating 1000 blank frames.

In [3]:
# Fetching of 1cll

num_frames = 1000

cmd.reinitialize()
cmd.fetch('1cll', 'structure')
cmd.remove('hetatm')
cmd.bg_color('white')
cmd.color('silver')
cmd.zoom('1cll')

cmd.mset('1 x{0}'.format(int(num_frames)))
cmd.mview('store')
In [4]:
# List of CA atoms of amino acids in structure

stored.r = [] 
cmd.iterate('strucutre and n. CA', 'stored.r.append(resi)')
Out[4]:
148

1.3 Creating a coloring scheme for residues.

In [5]:
# Gradient coloring of amino acids

import numpy as np

length = len(stored.r)
colors = np.linspace(1,0.5, length)
for k,i in enumerate(stored.r):
    cmd.set_color('col{}'.format(int(k)), [colors[k],0.9,1])
    cmd.set('cartoon_color','col{}'.format(int(k)) ,'resi {}'.format(str(i)))
cmd.show_as('cartoon','all')

1.4 The result of coloring.

In [5]:
# What do we see?

import IPython

cmd.set('ray_trace_mode', 1)
cmd.png('pymol_rainbow.png', '1920', '1080', ray=1)
In [6]:
IPython.display.Image('pymol_rainbow.png', retina=True)
Out[6]:

1.5 Creating a movie.

In [6]:
# Looping through residues

for i in range(length):
    cmd.frame((10*i)+1)
    cmd.zoom( 'n. CA and i. {0}+{1}'.format(int(i), int(i+7)))
    cmd.mview('store')

1.6 Saving 1000 frames and making a movie with a suitable codec.

In [7]:
# Saving 1000 frames

import os

cmd.set('ray_trace_mode', 1)

for i in range(num_frames):
    cmd.frame(i)
    cmd.png(os.path.join(os.getcwd(), 'pics', '{0}.png'.format(str(i))), '1920', '1080', ray=1)
In [8]:
%%bash
where_am_i=`echo $PWD`
ffmpeg -i "$where_am_i"/pics/%d.png -vcodec libx264 -crf 15 -hide_banner -loglevel panic "$where_am_i"/movie.mp4

1.7 Enjoying the movie!

In [10]:
from base64 import b64encode
from IPython.display import HTML

video = open('movie.mp4', 'rb').read()
encoded = b64encode(video)
HTML(data='''<video width=700px controls>
<source src="data:video/mp4; base64,{0}" type="video/mp4" />
</video>'''.format(encoded.decode('ascii')))
Out[10]: