Commit fd6d2c0d authored by Bram Schoenmakers's avatar Bram Schoenmakers

Add dot output to the Graph class.

parent 2ce645df
......@@ -181,3 +181,25 @@ class DirectedGraph(object):
for edge in removals:
self.remove_edge(edge[0], edge[1])
def dot(self, p_print_labels=True):
""" Prints the graph in Dot format. """
out = 'digraph g {\n'
for from_node, neighbors in self._edges.iteritems():
out += " %s\n" % from_node
for neighbor in neighbors:
out += " %s -> %s" % (from_node, neighbor)
edge_id = self.edge_id(from_node, neighbor)
if edge_id and p_print_labels:
out += ' [label="%s"]' % edge_id
out += "\n"
out += '}\n'
return out
def __str__(self):
""" Returns the graph in Dot format. """
return self.dot()
......@@ -126,3 +126,11 @@ class GraphTest(unittest.TestCase):
# the one and only edge must be removed now
self.assertFalse(self.graph.has_edge(1, 3))
def test_str_output(self):
out = 'digraph g {\n 1\n 1 -> 2 [label="1"]\n 1 -> 3\n 2\n 2 -> 4\n 3\n 3 -> 5\n 4\n 4 -> 3\n 4 -> 6\n 5\n 6\n 6 -> 2\n}\n'
self.assertEquals(str(self.graph), out)
def test_dot_output_without_labels(self):
out = 'digraph g {\n 1\n 1 -> 2\n 1 -> 3\n 2\n 2 -> 4\n 3\n 3 -> 5\n 4\n 4 -> 3\n 4 -> 6\n 5\n 6\n 6 -> 2\n}\n'
self.assertEquals(self.graph.dot(False), out)
Markdown is supported
0%
or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment