Subversion Repositories programming

Rev

Details | Last modification | View Log | RSS feed

Rev Author Line No. Line
377 ira 1
#!/usr/bin/env python
2
 
378 ira 3
__author__    = "Ira W. Snyder (devel@irasnyder.com)"
4
__copyright__ = "Copyright (c) 2006 Ira W. Snyder (devel@irasnyder.com)"
5
__license__   = "GNU GPL v2 (or, at your option, any later version)"
6
 
377 ira 7
import Graph
8
import yapgvb
9
 
10
class Key (object):
11
	"""A class that makes a unique key for each pair of vertices."""
12
 
13
	def __init__ (self, v1, v2):
14
		self.__key = [v1, v2]
15
		self.__key.sort ()
16
 
17
	def __eq__ (self, rhs):
18
		return (self.__key[0] == rhs.__key[0]) and (self.__key[1] == rhs.__key[1])
19
 
20
 
21
class DrawGraph (object):
22
	"""A class that will draw an unweighted, undirected graph given the vertices and
23
	edges in the same form that is used for the Graph class."""
24
 
379 ira 25
	def __init__ (self, name, graph):
377 ira 26
		"""Constructor"""
27
		self.__name = str(name)
379 ira 28
		self.__graph = graph
377 ira 29
 
30
	def render_graph (self, filename):
378 ira 31
		"""Draw the graph given into the file given. This will render
32
		to SVG, PNG, and JPG."""
377 ira 33
		dg = yapgvb.Graph (self.__name)
379 ira 34
		g = self.__graph
377 ira 35
 
36
		visited = []
37
 
38
		for v in g.vertices:
39
			node = dg.add_node (str(v), label=str(v),
40
					shape=yapgvb.shapes.circle, fontsize=14)
41
 
42
			for c in g.get_children (v):
43
				k = Key (v, c)
44
 
45
				if k not in visited:
46
					node_c = dg.add_node (str(c), label=str(c),
47
							shape=yapgvb.shapes.circle,
48
							fontsize=14)
379 ira 49
					edge = dg.add_edge (node, node_c)
50
					edge.color = g.get_edge_color (v, c)
51
					edge.label = g.get_edge_label (v, c)
377 ira 52
					visited.append (k)
53
 
54
		# Do the rendering
55
		dg.layout (yapgvb.engines.neato)
56
		dg.render (filename)
57
 
58
 
59
def main ():
60
 
61
	vertices = ['a', 'b', 'c', 'd', 'e']
62
	edges = ( ['a', 'b'], ['a', 'c'], ['a', 'd'], ['b', 'a'], ['b', 'c'],
63
			['b', 'e'], ['e', 'b'], ['e', 'c'], ['e', 'd'],
64
			['d', 'a'], ['d', 'c'], ['d', 'e'], ['c', 'a'],
65
			['c', 'b'], ['c', 'd'], ['c', 'e'] )
66
 
67
	print 'Drawing graph g1.svg'
379 ira 68
	g1 = Graph.Graph (vertices, edges)
69
	DrawGraph ('g1', g1).render_graph ('g1.svg')
377 ira 70
 
71
	vertices = range (11)
72
	edges = ( [0, 1], [0, 9], [0, 8], [8, 10], [8, 7], [9, 6], [9, 5],
73
			[6, 7], [1, 4], [1, 3], [1, 2], [2, 0] )
74
 
75
	print 'Drawing graph g2.svg'
379 ira 76
	g2 = Graph.Graph (vertices, edges)
77
	DrawGraph ('g2', g2).render_graph ('g2.svg')
377 ira 78
 
79
	vertices = range (3)
80
	edges = ( [0, 1], [1, 2], [2, 0] )
81
 
82
	print 'Drawing graph g3.svg'
379 ira 83
	g3 = Graph.Graph (vertices, edges)
84
	DrawGraph ('g3', g3).render_graph ('g3.svg')
377 ira 85
 
86
 
87
if __name__ == '__main__':
88
	main ()
89