Sunday, December 2, 2012

pyGraphviz

After i switched to using a Mac, I have really been missing MS Paint. Not many Apps for Mac can do the same things in the same way. Used to be, I used MS Paint for everything. If I needed a graph of nodes and edges, I used Paint.

When I started studying, I realised that this approach was lacking. Creating large graphs is tedious and when I discover an error, it takes time to correct.

This led me to find the DOT language. A language for representing graphs as text and rendering them with a binary into a .PNG or .SVG or similar. This is a very powerful tool, but I quickly got tired of the syntax. It has a lot of special characters, that I don't normally use, and so; takes time to get used to it.

Luckily, I was able to find a python implementation :)

The first goody is that the syntax is now wrapped in python objects, making me able to be smart with loops and conditions. The other up-side is that the syntax is more readable to me. Below is the example of a graph written in DOT:


digraph {
 graph [rankdir=LR];
 node [shape=circle];
 s0  [shape=doublecircle];
 s0 -> s0  [label="[0,3-9]"];
 s0 -> s1  [label=1];
 s0 -> s2  [label=2];
 s1 -> s0  [label=2];
 s1 -> s1  [label="[0,3-9]"];
 s2 -> s0  [label=1];
 s2 -> s2  [label="[0,3-9]"];
}

And now, in python:

g=pgv.AGraph(strict=False, directed=True, rankdir='LR')
g.node_attr['shape']='circle'

g.add_node('s0', shape="doublecircle")

g.add_edge('s0','s0', label='[0,3-9]')
g.add_edge('s0','s1', label='1')
g.add_edge('s1','s1', label='[0,3-9]')
g.add_edge('s1','s0', label='2')
g.add_edge('s0','s2', label='2')
g.add_edge('s2','s2', label='[0,3-9]')
g.add_edge('s2','s0', label='1')

print g.string()
g.draw(path+'w1-4a.png', prog='dot')

This is a tool I really appreciate. Now I can make logic statements in my graphs and editing them has never been easier.

No comments:

Post a Comment