Commit 8bf19c02 authored by Tiago Peixoto's avatar Tiago Peixoto
Browse files

Include cookbook documentation on animations

parent 7a015e02
Animations with graph-tool
==========================
The drawing capabilities of ``graph-tool`` (see :mod:`~graph_tool.draw`
module) can be harnessed to perform animations in a straightforward
manner. Here we show some examples which uses `GTK+
<http://www.gtk.org/>`_ to display animations in an
:class:`~graph_tool.draw.interactive_window`, as well as offscreen to a
file. The idea is to easily generate visualisations which can be used in
presentations, and embedded in websites.
SIRS epidemics
--------------
Here we implement a simple `SIRS epidemics
<http://en.wikipedia.org/wiki/Epidemic_model>`_ on a network, and we
construct an animation showing the time evolution. Nodes which are
susceptible (S) are shown in white, whereas infected (I) nodes are shown
in black. Recovered (R) nodes are removed from the layout, since they
cannot propagate the outbreak.
The script which performs the animation is called
:download:`animation_sirs.py <animation_sirs.py>` and is shown below.
.. literalinclude:: animation_sirs.py
:linenos:
If called without arguments, the script will show the animation inside an
:class:`~graph_tool.draw.interactive_window`. If the parameter
``offscreen`` is passed, individual frames will be saved in the
``frames`` directory:
.. code-block:: bash
$ ./animation_sirs.py offscreen
.. doctest::
:hide:
>>> import subprocess
>>> subprocess.call(["demos/animation_sirs.py", "offscreen"])
0
These frames can be combined and encoded into the appropriate
format. Here we use the `mencoder
<http://www.mplayerhq.hu/DOCS/HTML/en/mencoder.html>`_ tool from
`mplayer <http://www.mplayerhq.hu>`_ to combine all the frames into a
single file with YUY format, and then we encode this with the `WebM
format <http://www.webmproject.org>`_, using `vpxenc
<http://www.webmproject.org/docs/encoder-parameters/>`_, so that it can
be embedded in a website.
.. code-block:: bash
$ mencoder mf://frames/sirs*.png -mf w=500:h=400:type=png -ovc raw -of rawvideo -vf format=i420 -nosound -o sirs.yuy
$ vpxenc sirs.yuy -o sirs.webm -w 500 -h 400 --fps=25/1 --target-bitrate=1000 --good --threads=4
.. doctest::
:hide:
>>> import subprocess
>>> subprocess.call("mencoder mf://frames/sirs*.png -mf w=500:h=400:type=png -ovc raw -of rawvideo -vf format=i420 -nosound -o demos/sirs.yuy".split())
0
>>> subprocess.call("vpxenc demos/sirs.yuy -o demos/sirs.webm -w 500 -h 400 --fps=25/1 --target-bitrate=1000 --good --threads=4".split())
0
The resulting animation can be downloaded :download:`here <sirs.webm>`,
or played below if your browser supports WebM.
.. raw:: html
<div style="text-align:center">
<video id="sirs" src="../_downloads/sirs.webm" controls></video>
</div>
This type of animation can be extended or customized in many ways, by
dynamically modifying the various drawing parameters and vertex/edge
properties. For instance, one might want to represent the susceptible
state as either |susceptible| or |susceptible-fear|, depending on
whether a neighbor is infected, and the infected state as |zombie|.
Properly modifying the script above would lead to the following
:download:`movie <zombie.webm>`:
.. doctest::
:hide:
>>> import subprocess
>>> subprocess.call(["demos/animation_zombies.py", "offscreen"])
0
>>> import subprocess
>>> subprocess.call("mencoder mf://frames/zombies*.png -mf w=500:h=400:type=png -ovc raw -of rawvideo -vf format=i420 -nosound -o demos/zombie.yuy".split())
0
>>> subprocess.call("vpxenc demos/zombie.yuy -o demos/zombie.webm -w 500 -h 400 --fps=10/1 --target-bitrate=1000 --good --threads=4".split())
0
.. raw:: html
<div style="text-align:center">
<video id="sirs" src="../_downloads/zombie.webm" controls></video>
</div>
The modified script can be downloaded :download:`here <animation_zombies.py>`.
.. |susceptible| image:: face-grin.png
:height: 48
:width: 48
.. |susceptible-fear| image:: face-surprise.png
:height: 48
:width: 48
.. |zombie| image:: zombie.png
:height: 48
:width: 48
Dynamic layout
--------------
The graph layout can also be updated during an animation. As an
illustration, here we consider a very simplistic model for spatial
segregation, where the edges of the graph are repeatedly and randomly
rewired, as long as the new edge has a shorter euclidean distance.
The script which performs the animation is called
:download:`animation_dancing.py <animation_dancing.py>` and is shown below.
.. literalinclude:: animation_dancing.py
:linenos:
This example works like the SIRS example above, and if we pass the
``offscreen`` parameter, the frames will be dumped to disk, otherwise
the animation is displayed inside an :class:`~graph_tool.draw.interactive_window`.
.. code-block:: bash
$ ./animation_dancing.py offscreen
.. doctest::
:hide:
>>> import subprocess
>>> subprocess.call(["demos/animation_dancing.py", "offscreen"])
0
Also like the previous example, we can encode the animation with the `WebM
format <http://www.webmproject.org>`_:
.. code-block:: bash
$ mencoder mf://frames/dancing*.png -mf w=500:h=400:type=png -ovc raw -of rawvideo -vf format=i420 -nosound -o dancing.yuy
$ vpxenc sirs.yuy -o dancing.webm -w 500 -h 400 --fps=100/1 --target-bitrate=5000 --good --threads=4
.. doctest::
:hide:
>>> import subprocess
>>> subprocess.call("mencoder mf://frames/dancing*.png -mf w=500:h=400:type=png -ovc raw -of rawvideo -vf format=i420 -nosound -o demos/dancing.yuy".split())
0
>>> subprocess.call("vpxenc demos/dancing.yuy -o demos/dancing.webm -w 500 -h 400 --fps=100/1 --target-bitrate=5000 --good --threads=4".split())
0
The resulting animation can be downloaded :download:`here
<dancing.webm>`, or played below if your browser supports WebM.
.. raw:: html
<div style="text-align:center">
<video id="sirs" src="../_downloads/dancing.webm" controls></video>
</div>
\ No newline at end of file
#! /usr/bin/env python
# -*- coding: utf-8 -*-
# This simple example on how to do animations using graph-tool, where the layout
# changes dynamically. We start with some network, and randomly rewire its
# edges, and update the layout dynamically, where edges are rewired only if
# their euclidian distance is reduced. It is thus a very simplistic model for
# spatial segregation.
from graph_tool.all import *
from numpy.random import *
from numpy.linalg import norm
import sys, os, os.path
seed(42)
seed_rng(42)
# We need some Gtk and gobject functions
from gi.repository import Gtk, Gdk, GdkPixbuf
import gi._gobject as gobject
# We will generate a small random network
g = random_graph(150, lambda: 1 + poisson(5), directed=False)
# Parameters for the layout update
step = 0.005 # move step
K = 0.5 # preferred edge length
pos = sfdp_layout(g, K=K) # initial layout positions
offscreen = True # If true, the frames will be dumped to disk as images.
max_count = 5000
if offscreen and not os.path.exists("./frames"):
os.mkdir("./frames")
# This creates a GTK+ window with the initial graph layout
if not offscreen:
win = GraphWindow(g, pos, geometry=(500, 400))
else:
win = Gtk.OffscreenWindow()
win.set_default_size(500, 400)
win.graph = GraphWidget(g, pos)
win.add(win.graph)
# list of edges
edges = list(g.edges())
count = 0
# This function will be called repeatedly by the GTK+ main loop, and we use it
# to update the vertex layout and perform the rewiring.
def update_state():
global count
# Perform one iteration of the layout step, starting from the previous positions
sfdp_layout(g, pos=pos, K=K, init_step=step, max_iter=1)
for i in range(100):
# get a chosen edge, and swap one of its end points for a random vertex,
# if it is closer
i = randint(0, len(edges))
e = list(edges[i])
shuffle(e)
s1, t1 = e
t2 = g.vertex(randint(0, g.num_vertices()))
if (norm(pos[s1].a - pos[t2].a) <= norm(pos[s1].a - pos[t1].a) and
s1 != t2 and # no self-loops
t1.out_degree() > 1 and # no isolated vertices
t2 not in s1.out_neighbours()): # no parallel edges
g.remove_edge(edges[i])
edges[i] = g.add_edge(s1, t2)
# The movement of the vertices may cause them to leave the display area. The
# following function rescales the layout to fit the window to avoid this.
if count % 1000 == 0:
win.graph.fit_to_window(ink=True)
count += 1
# The following will force the re-drawing of the graph, and issue a
# re-drawing of the GTK window.
win.graph.regenerate_surface(lazy=False)
win.graph.queue_draw()
# if doing an offscreen animation, dump frame to disk
if offscreen:
pixbuf = win.get_pixbuf()
pixbuf.savev(r'./frames/dancing%06d.png' % count, 'png', [], [])
if count > max_count:
sys.exit(0)
# We need to return True so that the main loop will call this function more
# than once.
return True
# Bind the function above as an 'idle' callback.
cid = gobject.idle_add(update_state)
# We will give the user the ability to stop the program by closing the window.
win.connect("delete_event", Gtk.main_quit)
# Actually show the window, and start the main loop.
win.show_all()
Gtk.main()
#! /usr/bin/env python
# -*- coding: utf-8 -*-
# This simple example on how to do animations using graph-tool. Here we do a
# simple simulation of an S->I->R->S epidemic model, where each vertex can be in
# one of the following states: Susceptible (S), infected (I), recovered (R). A
# vertex in the S state becomes infected either spontaneously with a probability
# 'x' or because a neighbour is infected. An infected node becomes recovered
# with probability 'r', and a recovered vertex becomes again susceptible with
# probability 's'.
# DISCLAIMER: The following code is definitely not the most efficient approach
# if you want to simulate this dynamics for very large networks, and/or for very
# long times. The main purpose is simply to highlight the animation capabilities
# of graph-tool.
from graph_tool.all import *
from numpy.random import *
import sys, os, os.path
seed(42)
seed_rng(42)
# We need some Gtk and gobject functions
from gi.repository import Gtk, Gdk, GdkPixbuf
import gi._gobject as gobject
# We will use the network of network scientists, and filter out the largest
# component
g = collection.data["netscience"]
g = GraphView(g, vfilt=label_largest_component(g), directed=False)
g = Graph(g, prune=True)
pos = g.vp["pos"] # layout positions
# We will filter out vertices which are in the "Recovered" state, by masking
# them using a property map.
removed = g.new_vertex_property("bool")
# SIRS dynamics parameters:
x = 0.001 # spontaneous outbreak probability
r = 0.1 # I->R probability
s = 0.01 # R->S probability
# (Note that the S->I transition happens simultaneously for every vertex with a
# probability equal to the fraction of non-recovered neighbours which are
# infected.)
# The states would usually be represented with simple integers, but here we will
# use directly the color of the vertices in (R,G,B,A) format.
S = [1, 1, 1, 1] # White color
I = [0, 0, 0, 1] # Black color
R = [0.5, 0.5, 0.5, 1.] # Grey color (will not actually be drawn)
# Initialize all vertices to the S state
state = g.new_vertex_property("vector<double>")
for v in g.vertices():
state[v] = S
# Newly infected nodes will be highlighted in red
newly_infected = g.new_vertex_property("bool")
# If True, the frames will be dumped to disk as images.
offscreen = sys.argv[1] == "offscreen" if len(sys.argv) > 1 else False
max_count = 500
if offscreen and not os.path.exists("./frames"):
os.mkdir("./frames")
# This creates a GTK+ window with the initial graph layout
if not offscreen:
win = GraphWindow(g, pos, geometry=(500, 400),
edge_color=[0.6, 0.6, 0.6, 1],
vertex_fill_color=state,
vertex_halo=newly_infected,
vertex_halo_color=[0.8, 0, 0, 0.6])
else:
count = 0
win = Gtk.OffscreenWindow()
win.set_default_size(500, 400)
win.graph = GraphWidget(g, pos,
edge_color=[0.6, 0.6, 0.6, 1],
vertex_fill_color=state,
vertex_halo=newly_infected,
vertex_halo_color=[0.8, 0, 0, 0.6])
win.add(win.graph)
# This function will be called repeatedly by the GTK+ main loop, and we use it
# to update the state according to the SIRS dynamics.
def update_state():
newly_infected.a = False
removed.a = False
# visit the nodes in random order
vs = list(g.vertices())
shuffle(vs)
for v in vs:
if state[v] == I:
if random() < r:
state[v] = R
elif state[v] == S:
if random() < x:
state[v] = I
else:
ns = list(v.out_neighbours())
if len(ns) > 0:
w = ns[randint(0, len(ns))] # choose a random neighbour
if state[w] == I:
state[v] = I
newly_infected[v] = True
elif random() < s:
state[v] = S
if state[v] == R:
removed[v] = True
# Filter out the recovered vertices
g.set_vertex_filter(removed, inverted=True)
# The following will force the re-drawing of the graph, and issue a
# re-drawing of the GTK window.
win.graph.regenerate_surface(lazy=False)
win.graph.queue_draw()
# if doing an offscreen animation, dump frame to disk
if offscreen:
global count
pixbuf = win.get_pixbuf()
pixbuf.savev(r'./frames/sirs%06d.png' % count, 'png', [], [])
if count > max_count:
sys.exit(0)
count += 1
# We need to return True so that the main loop will call this function more
# than once.
return True
# Bind the function above as an 'idle' callback.
cid = gobject.idle_add(update_state)
# We will give the user the ability to stop the program by closing the window.
win.connect("delete_event", Gtk.main_quit)
# Actually show the window, and start the main loop.
win.show_all()
Gtk.main()
#! /usr/bin/env python
# -*- coding: utf-8 -*-
# This simple example on how to do animations using graph-tool. Here we do a
# simple simulation of an S->I->R->S epidemic model, where each vertex can be in
# one of the following states: Susceptible (S), infected (I), recovered (R). A
# vertex in the S state becomes infected either spontaneously with a probability
# 'x' or because a neighbour is infected. An infected node becomes recovered
# with probability 'r', and a recovered vertex becomes again susceptible with
# probability 's'.
# DISCLAIMER: The following code is definitely not the most efficient approach
# if you want to simulate this dynamics for very large networks, and/or for very
# long times. The main purpose is simply to highlight the animation capabilities
# of graph-tool.
from graph_tool.all import *
from numpy.random import *
import sys, os, os.path
import cairo
seed(42)
seed_rng(42)
# We need some Gtk and gobject functions
from gi.repository import Gtk, Gdk, GdkPixbuf
import gi._gobject as gobject
# We will use the karate-club network
g = collection.data["karate"]
pos = g.vp["pos"] # layout positions
# We will filter out vertices which are in the "Recovered" state, by masking
# them using a property map.
removed = g.new_vertex_property("bool")
# SIRS dynamics parameters:
x = 0.001 # spontaneous outbreak probability
r = 0.1 # I->R probability
s = 0.01 # R->S probability
# (Note that the S->I transition happens simultaneously for every vertex with a
# probability equal to the fraction of non-recovered neighbours which are
# infected.)
S = 0
I = 1
R = 2
# Initialize all vertices to the S state
state = g.new_vertex_property("int")
state.a = S
# Images used to draw the nodes. They need to be loaded as cairo surfaces.
Simg = cairo.ImageSurface.create_from_png(open("face-grin.png", "rb"))
Simg_fear = cairo.ImageSurface.create_from_png(open("face-surprise.png", "rb"))
Iimg = cairo.ImageSurface.create_from_png(open("zombie.png", "rb"))
vertex_sfcs = g.new_vertex_property("object")
for v in g.vertices():
vertex_sfcs[v] = Simg
# Newly infected nodes will be highlighted in red
newly_infected = g.new_vertex_property("bool")
# If True, the frames will be dumped to disk as images.
offscreen = sys.argv[1] == "offscreen" if len(sys.argv) > 1 else False
max_count = 500
if offscreen and not os.path.exists("./frames"):
os.mkdir("./frames")
# This creates a GTK+ window with the initial graph layout
if not offscreen:
win = GraphWindow(g, pos, geometry=(500, 400),
vertex_size=42,
vertex_anchor=0,
edge_color=[0.6, 0.6, 0.6, 1],
vertex_surface=vertex_sfcs,
vertex_halo=newly_infected,
vertex_halo_color=[0.8, 0, 0, 0.6])
else:
count = 0
win = Gtk.OffscreenWindow()
win.set_default_size(500, 400)
win.graph = GraphWidget(g, pos,
vertex_size=42,
vertex_anchor=0,
edge_color=[0.6, 0.6, 0.6, 1],
vertex_surface=vertex_sfcs,
vertex_halo=newly_infected,
vertex_halo_color=[0.8, 0, 0, 0.6])
win.add(win.graph)
# This function will be called repeatedly by the GTK+ main loop, and we use it
# to update the state according to the SIRS dynamics.
def update_state():
newly_infected.a = False
removed.a = False
# visit the nodes in random order
vs = list(g.vertices())
shuffle(vs)
for v in vs:
if state[v] == I:
if random() < r:
state[v] = R
elif state[v] == S:
if random() < x:
state[v] = I
else:
ns = list(v.out_neighbours())
if len(ns) > 0:
w = ns[randint(0, len(ns))] # choose a random neighbour
if state[w] == I:
state[v] = I
newly_infected[v] = True
elif random() < s:
state[v] = S
if state[v] == R:
removed[v] = True
if state[v] == S:
if I in [state[w] for w in v.out_neighbours()]:
vertex_sfcs[v] = Simg_fear
else:
vertex_sfcs[v] = Simg
else:
vertex_sfcs[v] = Iimg
# Filter out the recovered vertices
g.set_vertex_filter(removed, inverted=True)
# The following will force the re-drawing of the graph, and issue a
# re-drawing of the GTK window.
win.graph.regenerate_surface(lazy=False)
win.graph.queue_draw()
# if doing an offscreen animation, dump frame to disk
if offscreen:
global count
pixbuf = win.get_pixbuf()
pixbuf.savev(r'./frames/zombies%06d.png' % count, 'png', [], [])
if count > max_count:
sys.exit(0)
count += 1
# We need to return True so that the main loop will call this function more
# than once.
return True
# Bind the function above as an 'idle' callback.
cid = gobject.idle_add(update_state)
# We will give the user the ability to stop the program by closing the window.
win.connect("delete_event", Gtk.main_quit)
# Actually show the window, and start the main loop.
win.show_all()
Gtk.main()
Cookbook
========
Contents:
.. toctree::
:maxdepth: 3
:glob:
animation
\ No newline at end of file
.. graph-tool documentation master file, created by sphinx-quickstart on Sun Oct 26 18:29:16 2008.
You can adapt this file completely to your liking, but it should at least
contain the root `toctree` directive.