Blame | Last modification | View Log | RSS feed
#!/usr/bin/env python
import Graph
import yapgvb
class Key (object):
"""A class that makes a unique key for each pair of vertices."""
def __init__ (self, v1, v2):
self.__key = [v1, v2]
self.__key.sort ()
def __eq__ (self, rhs):
return (self.__key[0] == rhs.__key[0]) and (self.__key[1] == rhs.__key[1])
class DrawGraph (object):
"""A class that will draw an unweighted, undirected graph given the vertices and
edges in the same form that is used for the Graph class."""
def __init__ (self, name, vertices, edges):
"""Constructor"""
self.__name = str(name)
self.__vertices = vertices
self.__edges = edges
def render_graph (self, filename):
"""Draw the graph given into the file given. Please end the
filename in .svg."""
dg = yapgvb.Graph (self.__name)
g = Graph.Graph (self.__vertices, self.__edges)
visited = []
for v in g.vertices:
node = dg.add_node (str(v), label=str(v),
shape=yapgvb.shapes.circle, fontsize=14)
for c in g.get_children (v):
k = Key (v, c)
if k not in visited:
node_c = dg.add_node (str(c), label=str(c),
shape=yapgvb.shapes.circle,
fontsize=14)
node >> node_c
visited.append (k)
# Do the rendering
dg.layout (yapgvb.engines.neato)
dg.render (filename)
def main ():
vertices = ['a', 'b', 'c', 'd', 'e']
edges = ( ['a', 'b'], ['a', 'c'], ['a', 'd'], ['b', 'a'], ['b', 'c'],
['b', 'e'], ['e', 'b'], ['e', 'c'], ['e', 'd'],
['d', 'a'], ['d', 'c'], ['d', 'e'], ['c', 'a'],
['c', 'b'], ['c', 'd'], ['c', 'e'] )
print 'Drawing graph g1.svg'
DrawGraph ('g1', vertices, edges).render_graph ('g1.svg')
vertices = range (11)
edges = ( [0, 1], [0, 9], [0, 8], [8, 10], [8, 7], [9, 6], [9, 5],
[6, 7], [1, 4], [1, 3], [1, 2], [2, 0] )
print 'Drawing graph g2.svg'
DrawGraph ('g2', vertices, edges).render_graph ('g2.svg')
vertices = range (3)
edges = ( [0, 1], [1, 2], [2, 0] )
print 'Drawing graph g3.svg'
DrawGraph ('g3', vertices, edges).render_graph ('g3.svg')
if __name__ == '__main__':
main ()