In [1]:
from sklearn.decomposition import KernelPCA
import networkx as nx
import numpy as np
from __future__ import absolute_import, division, print_function
from mayavi import mlab
import scipy.sparse as sps
import moviepy.editor as mpy


/anaconda/envs/py27/lib/python2.7/site-packages/matplotlib/font_manager.py:273: UserWarning: Matplotlib is building the font cache using fc-list. This may take a moment.
  warnings.warn('Matplotlib is building the font cache using fc-list. This may take a moment.')

In [3]:
DNA = 'ATGGCCCTTTGAAG'
print(1)
coordinates = {'A':np.array([1,0,0,0]),'T':np.array([0,1,0,0]),'C':np.array([0,0,1,0]),'G':np.array([0,0,0,1])}
pos4d = [coordinates[DNA[0]]]
for bp in DNA[1:]:
    pos4d.append(coordinates[bp] + pos4d[-1])
pos4d = {i:tuple(pos4d[i]) for i in range(len(DNA))}#np.array(pos4d)

connections = [(i,i+1) for i in range(len(DNA)-1)]
G = nx.Graph()
G.add_edges_from(connections)
pos_new = np.array([pos4d[i] for i in pos4d])
a = KernelPCA(n_components=3).fit_transform(pos_new)
mlab.points3d(0,0,0)
plt = mlab.points3d(a[:,0], a[:,1], a[:,2],mode='point')
xs,ys,zs = [],[],[]
xs.append(a[:,0])
ys.append(a[:,1])
zs.append(a[:,2])
for i in range(25):
    pos=nx.spring_layout(G,dim=4,pos=pos4d, iterations=i)
    pos_new = np.array([pos[i] for i in pos])
    a = KernelPCA(n_components=3).fit_transform(pos_new)
    xs.append(a[:,0])
    ys.append(a[:,1])
    zs.append(a[:,2])
@mlab.animate(delay=150)
def anim():
    f = mlab.gcf()
    while True:
        for (x, y, z) in zip(xs, ys, zs):
            #print('Updating scene...')
            #print(x,y,z)
            plt.mlab_source.x = x
            plt.mlab_source.y = y
            plt.mlab_source.z = z
            f.scene.render()
            yield
anim()
mlab.show()


1
---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
/anaconda/envs/py27/lib/python2.7/site-packages/pyface/ui/qt4/timer/timer.pyc in Notify(self)
     49         """
     50         try:
---> 51             self.callable(*self.args, **self.kw_args)
     52         except StopIteration:
     53             self.stop()

/anaconda/envs/py27/lib/python2.7/site-packages/mayavi/tools/animator.pyc in _step(self)
    222         def _step(self):
    223             try:
--> 224                 self._next()
    225                 if self._support_movie:
    226                     self._update_movie_maker()

<ipython-input-3-c00f52760df4> in anim()
     35             plt.mlab_source.y = y
     36             plt.mlab_source.z = z
---> 37             f.scene.render()
     38             yield
     39 anim()

AttributeError: 'NoneType' object has no attribute 'render'

In [14]:
G = nx.from_scipy_sparse_matrix(sps.load_npz('spectralGraph.npz'))
pos_new = np.load('graphInitialPositions.npy')
mlab.points3d(0,0,0,mode='point')
plt = mlab.points3d(pos_new[:,0], pos_new[:,1], pos_new[:,2],mode='point')
xs,ys,zs = [],[],[]
xs.append(pos_new[:,0])
ys.append(pos_new[:,1])
zs.append(pos_new[:,2])
pos = {j:tuple(pos_new[j]) for j in range(len(pos_new))}
#np.array(pos4d)
for i in range(90):
    print(i)
    pos=nx.spring_layout(G,dim=3,pos=pos, iterations=1)
    pos_new = np.array([pos[i] for i in pos])
    xs.append(pos_new[:,0])
    ys.append(pos_new[:,1])
    zs.append(pos_new[:,2])
@mlab.animate(delay=100)
def anim():
    f = mlab.gcf()
    while True:
        for (x, y, z) in zip(xs, ys, zs):
            #print('Updating scene...')
            #print(x,y,z)
            #plt.mlab_source.x = x
            #plt.mlab_source.y = y
            #plt.mlab_source.z = z
            #plt.mlab_source.reset_zoom = True
            plt.mlab_source.reset(x=x,y=y,z=z)
            f.scene.reset_zoom()
            f.scene.render()
            yield
anim()
mlab.show()


0
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29

In [ ]:
mlab.points3d(0,0,0,mode='point')
plt = mlab.points3d(xs[0], ys[0], zs[0],mode='point')
@mlab.animate(delay=300)
def anim():
    f = mlab.gcf()
    while True:
        for (x, y, z) in zip(xs, ys, zs):
            #print('Updating scene...')
            #print(x,y,z)
            #plt.mlab_source.x = x
            #plt.mlab_source.y = y
            #plt.mlab_source.z = z
            #plt.mlab_source.reset_zoom = True
            #mlab.clf()
            #mlab.points3d(x, y, z,mode='point')
            plt.mlab_source.reset(x=x,y=y,z=z,)
            f.scene.reset_zoom()
            f.scene.render()
            yield
anim()
mlab.show()

In [3]:
duration= 2 # duration of the animation in seconds (it will loop)

# MAKE A FIGURE WITH MAYAVI

fig_myv = mlab.figure(size=(220,220), bgcolor=(1,1,1))
G = nx.from_scipy_sparse_matrix(sps.load_npz('spectralGraph.npz'))
pos_new = np.load('graphInitialPositions.npy')
mlab.points3d(0,0,0,mode='point')
#plt = mlab.points3d(pos_new[:,0], pos_new[:,1], pos_new[:,2],mode='point',color='blue')
xs,ys,zs = [],[],[]
xs.append(pos_new[:,0])
ys.append(pos_new[:,1])
zs.append(pos_new[:,2])
pos = {j:tuple(pos_new[j]) for j in range(len(pos_new))}
#np.array(pos4d)
for i in range(90):
    print(i)
    pos=nx.spring_layout(G,dim=3,pos=pos, iterations=1)
    pos_new = np.array([pos[i] for i in pos])
    xs.append(pos_new[:,0])
    ys.append(pos_new[:,1])
    zs.append(pos_new[:,2])

# ANIMATE THE FIGURE WITH MOVIEPY, WRITE AN ANIMATED GIF

def make_frame(t):
    mlab.clf() # clear the figure (to reset the colors)
    mlab.points3d(xs[t],ys[t],zs[t],color='blue', figure=fig_myv)
    return mlab.screenshot(antialiased=True)

animation = mpy.VideoClip(make_frame, duration=duration)
animation.write_gif("new_fig.gif", fps=30)


0
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
---------------------------------------------------------------------------
TraitError                                Traceback (most recent call last)
<ipython-input-3-42a87c9af16c> in <module>()
     29     return mlab.screenshot(antialiased=True)
     30 
---> 31 animation = mpy.VideoClip(make_frame, duration=duration)
     32 animation.write_gif("new_fig.gif", fps=20)

/anaconda/envs/py27/lib/python2.7/site-packages/moviepy/video/VideoClip.pyc in __init__(self, make_frame, ismask, duration)
     98         if make_frame is not None:
     99             self.make_frame = make_frame
--> 100             self.size =self.get_frame(0).shape[:2][::-1]
    101         self.ismask = ismask
    102         if duration is not None:

/anaconda/envs/py27/lib/python2.7/site-packages/moviepy/Clip.pyc in get_frame(self, t)
     75         """
     76         # Coming soon: smart error handling for debugging at this point
---> 77         return self.make_frame(t)
     78 
     79     def fl(self, fun, apply_to=[] , keep_duration=True):

<ipython-input-3-42a87c9af16c> in make_frame(t)
     26 def make_frame(t):
     27     mlab.clf() # clear the figure (to reset the colors)
---> 28     mlab.points3d(xs[t],ys[t],zs[t],color='blue', figure=fig_myv)
     29     return mlab.screenshot(antialiased=True)
     30 

/anaconda/envs/py27/lib/python2.7/site-packages/mayavi/tools/helper_functions.pyc in the_function(*args, **kwargs)
     35 
     36     def the_function(*args, **kwargs):
---> 37         return pipeline(*args, **kwargs)
     38 
     39     if hasattr(pipeline, 'doc'):

/anaconda/envs/py27/lib/python2.7/site-packages/mayavi/tools/helper_functions.pyc in __call__(self, *args, **kwargs)
     80             scene.disable_render = True
     81         # Then call the real logic
---> 82         output = self.__call_internal__(*args, **kwargs)
     83         # And re-enable the rendering, if needed.
     84         if scene is not None:

/anaconda/envs/py27/lib/python2.7/site-packages/mayavi/tools/helper_functions.pyc in __call_internal__(self, *args, **kwargs)
    175         if scale_factor == 'auto':
    176             kwargs['scale_factor'] = 1
--> 177         g = Pipeline.__call_internal__(self, *args, **kwargs)
    178         if scale_factor == 'auto':
    179             g.glyph.glyph.scale_factor = \

/anaconda/envs/py27/lib/python2.7/site-packages/mayavi/tools/helper_functions.pyc in __call_internal__(self, *args, **kwargs)
     93         # Copy the pipeline so as not to modify it for the next call
     94         self.pipeline = self._pipeline[:]
---> 95         return self.build_pipeline()
     96 
     97     def store_kwargs(self, kwargs):

/anaconda/envs/py27/lib/python2.7/site-packages/mayavi/tools/helper_functions.pyc in build_pipeline(self)
    121                 if key in keywords:
    122                     this_kwargs[key] = value
--> 123             object = pipe(object, **this_kwargs)._target
    124         return object
    125 

/anaconda/envs/py27/lib/python2.7/site-packages/mayavi/tools/modules.pyc in __init__(self, *args, **kwargs)
    154 
    155     def __init__(self, *args, **kwargs):
--> 156         super(DataModuleFactory, self).__init__(*args, **kwargs)
    157         # We are adding data to the scene, reset the zoom:
    158         scene = self._scene.scene

/anaconda/envs/py27/lib/python2.7/site-packages/mayavi/tools/pipe_base.pyc in __init__(self, parent, **kwargs)
    161         # Now calling the traits setter, so that traits handlers are
    162         # called
--> 163         self.set(**traits)
    164         if scene is not None:
    165             scene.disable_render = not self._do_redraw

/anaconda/envs/py27/lib/python2.7/site-packages/mayavi/tools/pipe_base.pyc in set(self, trait_change_notify, **traits)
    169         unless trait_change_notify==False"""
    170         HasPrivateTraits.set(self, trait_change_notify=trait_change_notify,
--> 171                                     **traits)
    172         if trait_change_notify == False:
    173             return

/anaconda/envs/py27/lib/python2.7/site-packages/traits/util/deprecated.pyc in wrapper(*args, **kw)
     30 
     31             warnings.warn(message, DeprecationWarning, stacklevel=2)
---> 32             return fn(*args, **kw)
     33 
     34         return wrapper

/anaconda/envs/py27/lib/python2.7/site-packages/traits/has_traits.pyc in set(self, trait_change_notify, **traits)
   1550     def set ( self, trait_change_notify = True, **traits ):
   1551         return self.trait_set(
-> 1552             trait_change_notify=trait_change_notify, **traits)
   1553 
   1554     set.__doc__ = trait_set.__doc__

/anaconda/envs/py27/lib/python2.7/site-packages/traits/has_traits.pyc in trait_set(self, trait_change_notify, **traits)
   1542         else:
   1543             for name, value in traits.items():
-> 1544                 setattr( self, name, value )
   1545 
   1546         return self

/anaconda/envs/py27/lib/python2.7/site-packages/traits/trait_handlers.pyc in error(self, object, name, value)
    170         """
    171         raise TraitError( object, name, self.full_info( object, name, value ),
--> 172                           value )
    173 
    174     def full_info ( self, object, name, value ):

TraitError: The 'color' trait of a GlyphFactory instance must be a tuple of the form: (0.0 <= a floating point number <= 1.0, 0.0 <= a floating point number <= 1.0, 0.0 <= a floating point number <= 1.0) or None, but a value of 'blue' <type 'str'> was specified.

In [ ]:
duration= 2.8 # duration of the animation in seconds (it will loop)

# MAKE A FIGURE WITH MAYAVI

fig_myv = mlab.figure(size=(220,220), bgcolor=(1,1,1))

def make_frame(t):
    t = int(t)
    mlab.clf() # clear the figure (to reset the colors)
    mlab.points3d(xs[t],ys[t],zs[t],mode='point',color=(0.5,0.4,0.2), figure=fig_myv)
    return mlab.screenshot(antialiased=True)

animation = mpy.VideoClip(make_frame, duration=duration)
animation.write_gif("new_fig.gif", fps=30)

In [ ]: