Python pydot.Edge() Examples

The following are 30 code examples of pydot.Edge(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module pydot , or try the search function .
Example #1
Source File: graph.py    From dcc with Apache License 2.0 7 votes vote down vote up
def draw(self, name, dname, draw_branches=True):
        from pydot import Dot, Edge,Node
        g = Dot()
        g.set_node_defaults(color='lightgray',
                            style='filled',
                            shape='box',
                            fontname='Courier',
                            fontsize='10')
        if len(self.nodes) == 1:
            g.add_node(Node(str(self.nodes[0])))
        else:
            for node in sorted(self.nodes, key=lambda x: x.num):
                for suc in self.sucs(node):
                    g.add_edge(Edge(str(node), str(suc), color='blue'))
                for except_node in self.catch_edges.get(node, []):
                    g.add_edge(Edge(str(node),
                                    str(except_node),
                                    color='black',
                                    style='dashed'))

        g.write_png('%s/%s.png' % (dname, name)) 
Example #2
Source File: edge.py    From boofuzz with GNU General Public License v2.0 6 votes vote down vote up
def render_edge_graphviz(self):
        """
        Render an edge suitable for use in a Pydot graph using the set internal attributes.

        @rtype:  pydot.Edge()
        @return: Pydot object representing edge
        """

        # no need to validate if nodes exist for src/dst. graphviz takes care of that for us transparently.

        dot_edge = pydot.Edge(self.src, self.dst)

        if self.label:
            dot_edge.label = self.label

        dot_edge.color = "#%06x" % self.color

        return dot_edge 
Example #3
Source File: graph.py    From MARA_Framework with GNU Lesser General Public License v3.0 6 votes vote down vote up
def draw(self, name, dname, draw_branches=True):
        from pydot import Dot, Edge
        g = Dot()
        g.set_node_defaults(color='lightgray',
                            style='filled',
                            shape='box',
                            fontname='Courier',
                            fontsize='10')
        for node in sorted(self.nodes, key=lambda x: x.num):
            if draw_branches and node.type.is_cond:
                g.add_edge(Edge(str(node), str(node.true), color='green'))
                g.add_edge(Edge(str(node), str(node.false), color='red'))
            else:
                for suc in self.sucs(node):
                    g.add_edge(Edge(str(node), str(suc), color='blue'))
            for except_node in self.catch_edges.get(node, []):
                g.add_edge(Edge(str(node),
                                str(except_node),
                                color='black',
                                style='dashed'))

        g.write_png('%s/%s.png' % (dname, name)) 
Example #4
Source File: graph.py    From MARA_Framework with GNU Lesser General Public License v3.0 6 votes vote down vote up
def draw(self, name, dname, draw_branches=True):
        import pydot
        g = pydot.Dot()
        g.set_node_defaults(**{'color': 'lightgray', 'style': 'filled',
                    'shape': 'box', 'fontname': 'Courier', 'fontsize': '10'})
        for node in sorted(self.nodes, key=lambda x: x.num):
            if draw_branches and node.is_cond():
                edge_true = pydot.Edge(str(node), str(node.true))
                edge_false = pydot.Edge(str(node), str(node.false))
                edge_true.set_color('green')
                edge_false.set_color('red')
                g.add_edge(edge_true)
                g.add_edge(edge_false)
            else:
                succs = self.sucs(node)
                for suc in succs:
                    edge = pydot.Edge(str(node), str(suc))
                    edge.set_color('blue')
                    g.add_edge(edge)
        g.write_png('%s/%s.png' % (dname, name)) 
Example #5
Source File: graph.py    From MARA_Framework with GNU Lesser General Public License v3.0 6 votes vote down vote up
def draw(self, name, dname, draw_branches=True):
        from pydot import Dot, Edge
        g = Dot()
        g.set_node_defaults(color='lightgray', style='filled', shape='box',
                            fontname='Courier', fontsize='10')
        for node in sorted(self.nodes, key=lambda x: x.num):
            if draw_branches and node.type.is_cond:
                g.add_edge(Edge(str(node), str(node.true), color='green'))
                g.add_edge(Edge(str(node), str(node.false), color='red'))
            else:
                for suc in self.sucs(node):
                    g.add_edge(Edge(str(node), str(suc), color='blue'))
            for except_node in self.catch_edges.get(node, []):
                g.add_edge(Edge(str(node), str(except_node),
                                color='black', style='dashed'))

        g.write_png('%s/%s.png' % (dname, name)) 
Example #6
Source File: Digraph.py    From PrincetonAlgorithms with GNU General Public License v2.0 6 votes vote down vote up
def wr_png(self, fout_png="Digraph.png", prt=sys.stdout, **kwargs):
    """Make a png showing a diagram of the connected components."""
    import pydot
    # 1. Create/initialize Graph
    G = pydot.Dot(graph_type='digraph') # Undirected Graph
    # 2. Create Nodes
    nodes = [pydot.Node(v) for v in self.keys]
    # 3. Add nodes to Graph
    for node in nodes:
      G.add_node(node)
    # 4. Add Edges between Nodes to Graph
    for v, w in self.get_edges():
      if v != w: # Print only edges from one node to another (not to self)
        G.add_edge(pydot.Edge(v, w))
    # 5. Write Graph to png file
    G.write_png(fout_png)
    prt.write("  WROTE: {}\n".format(fout_png)) 
Example #7
Source File: graph.py    From AndroBugs_Framework with GNU General Public License v3.0 6 votes vote down vote up
def draw(self, name, dname, draw_branches=True):
        from pydot import Dot, Edge
        g = Dot()
        g.set_node_defaults(color='lightgray', style='filled', shape='box',
                            fontname='Courier', fontsize='10')
        for node in sorted(self.nodes, key=lambda x: x.num):
            if draw_branches and node.type.is_cond:
                g.add_edge(Edge(str(node), str(node.true), color='green'))
                g.add_edge(Edge(str(node), str(node.false), color='red'))
            else:
                for suc in self.sucs(node):
                    g.add_edge(Edge(str(node), str(suc), color='blue'))
            for except_node in self.catch_edges.get(node, []):
                g.add_edge(Edge(str(node), str(except_node),
                                color='black', style='dashed'))

        g.write_png('%s/%s.png' % (dname, name)) 
Example #8
Source File: BaseComp.py    From PrincetonAlgorithms with GNU General Public License v2.0 6 votes vote down vote up
def wr_png(self, fout_png="components.png", prt=sys.stdout, **kwargs):
    """Make a png showing a diagram of the connected components."""
    import pydot
    label = get_png_label(self.ID, kwargs)
    # 1. Create/initialize Graph
    G = pydot.Dot(label=label, graph_type='digraph') # Directed Graph
    # 2. Create Nodes
    nodes = [pydot.Node(str(idx)) for idx in range(len(self.ID))]
    # 3. Add nodes to Graph
    for node in nodes:
      G.add_node(node)
    # 4. Add Edges between Nodes to Graph
    for child, parent in enumerate(self.ID):
      if child != parent: # Print only edges from one node to another (not to self)
        G.add_edge(pydot.Edge(nodes[parent], nodes[child]))
    # 5. Write Graph to png file
    G.write_png(fout_png)
    prt.write("  WROTE: {}\n".format(fout_png)) 
Example #9
Source File: binary_heaps.py    From PrincetonAlgorithms with GNU General Public License v2.0 6 votes vote down vote up
def wr_png_array(bh_st, kwargs):
  """Given an array for a binary heap, draw tree."""
  import pydot
  prt = sys.stdout if 'prt' not in kwargs else kwargs['prt']
  fout_png = "binary_heap_{}.png".format('_'.join(str(e) for e in bh_st))
  label = get_png_label(bh_st, kwargs)
  # 1. Create/initialize Graph
  G = pydot.Dot(label=label, graph_type='digraph') # Directed Graph
  edge_idxs = get_edges(bh_st)
  badcol = {c:'#fe2f4a' for p, c in edge_idxs if bh_st[p] < bh_st[c]}
  # 2. Create Nodes
  mknode = lambda i, v: pydot.Node(
    "{V}[{I}]".format(I=i+1, V=v), 
    style = "filled",
    fillcolor = badcol.get(i, "beige"))
  nodes = [mknode(i,v) for i, v in enumerate(bh_st) if v is not None]
  # 3. Add nodes to Graph
  for node in nodes:
    G.add_node(node)
  # 4. Add Edges between Nodes to Graph
  for p, c in edge_idxs:
    G.add_edge(pydot.Edge(nodes[p], nodes[c]))
  # 5. Write Graph to png file
  G.write_png(fout_png)
  prt.write("  WROTE: {}\n".format(fout_png)) 
Example #10
Source File: Graph.py    From PrincetonAlgorithms with GNU General Public License v2.0 6 votes vote down vote up
def wr_png(self, fout_png="Graph.png", prt=sys.stdout, **kwargs):
    """Make a png showing a diagram of the connected components."""
    import pydot
    # 1. create/initialize graph
    g = pydot.Dot(graph_type='graph') # undirected graph
    # 2. create nodes
    nodes = [pydot.Node(v) for v in self.keys]
    # 3. add nodes to graph
    for node in nodes:
      g.add_node(node)
    # 4. add edges between nodes to graph
    for v, w in self.get_edges():
      if v != w: # print only edges from one node to another (not to self)
        g.add_edge(pydot.Edge(v, w))
    # 5. write graph to png file
    g.write_png(fout_png)
    prt.write("  wrote: {}\n".format(fout_png)) 
Example #11
Source File: graph.py    From TimeMachine with GNU Lesser General Public License v3.0 6 votes vote down vote up
def draw(self, name, dname, draw_branches=True):
        from pydot import Dot, Edge
        g = Dot()
        g.set_node_defaults(color='lightgray', style='filled', shape='box',
                            fontname='Courier', fontsize='10')
        for node in sorted(self.nodes, key=lambda x: x.num):
            if draw_branches and node.type.is_cond:
                g.add_edge(Edge(str(node), str(node.true), color='green'))
                g.add_edge(Edge(str(node), str(node.false), color='red'))
            else:
                for suc in self.sucs(node):
                    g.add_edge(Edge(str(node), str(suc), color='blue'))
            for except_node in self.catch_edges.get(node, []):
                g.add_edge(Edge(str(node), str(except_node),
                                color='black', style='dashed'))

        g.write_png('%s/%s.png' % (dname, name)) 
Example #12
Source File: plot_hierarchy.py    From semantic-embeddings with MIT License 6 votes vote down vote up
def plot_hierarchy(hierarchy, filename, class_names = None):
    
    if isinstance(hierarchy, ClassHierarchy):
        hierarchy = hierarchy.children
    
    graph = pydot.Dot(graph_type = 'digraph', rankdir = 'LR')
    nodes = {}
    for lbl, children in hierarchy.items():
        nodes[lbl] = pydot.Node(lbl, label = lbl if class_names is None else class_names[lbl], style = 'filled', fillcolor = '#ffffff' if len(children) == 0 else '#eaeaea')
        for child in children:
            if child not in hierarchy:
                nodes[child] = pydot.Node(child, label = child if class_names is None else class_names[child], style = 'filled', fillcolor = '#ffffff')
    for node in nodes.values():
        graph.add_node(node)
    
    for parent, children in hierarchy.items():
        for child in children:
            graph.add_edge(pydot.Edge(nodes[parent], nodes[child]))
    
    graph.write_svg(filename, prog = 'dot') 
Example #13
Source File: dht_server_commons.py    From calvin-base with Apache License 2.0 6 votes vote down vote up
def drawNetworkState(name, servers, amount_of_servers):
    """Save image describinh network of `servers` as `name`."""
    if pydot is None:
        return
    graph = pydot.Dot(graph_type='digraph',
                     nodesep=0,
                     ranksep=0,
                     rankdir="BT")
    for servno in range(0, amount_of_servers):
        rndnode = Node(hashlib.sha1(str(random.getrandbits(255))).digest())
        findNeighbors = servers[servno].dht_server.kserver.protocol.router.findNeighbors
        neighbors = map(tuple, findNeighbors(rndnode, k=50))
        for neighbor in neighbors:
            printPort = servers[servno].dht_server.port.getHost().port
            edge = pydot.Edge(str(printPort),
                             str(neighbor[2]),
                             label=str(neighbor[0].encode('hex')[-4:]))
            graph.add_edge(edge)
    graph.write_png(name) 
Example #14
Source File: pydot_unittest.py    From pydot with MIT License 6 votes vote down vote up
def test_unicode_ids(self):

        node1 = '"aánñoöüé€"'
        node2 = '"îôø®çßΩ"'

        g = pydot.Dot()
        g.set_charset('latin1')
        g.add_node( pydot.Node( node1 ) )
        g.add_node( pydot.Node( node2 ) )
        g.add_edge( pydot.Edge( node1, node2 ) )

        self.assertEqual( g.get_node(node1)[0].get_name(), node1 )
        self.assertEqual( g.get_node(node2)[0].get_name(), node2 )

        self.assertEqual( g.get_edges()[0].get_source(), node1 )
        self.assertEqual( g.get_edges()[0].get_destination(), node2 )
        graphs = pydot.graph_from_dot_data(g.to_string())
        (g2,) = graphs

        self.assertEqual( g2.get_node(node1)[0].get_name(), node1 )
        self.assertEqual( g2.get_node(node2)[0].get_name(), node2 )

        self.assertEqual( g2.get_edges()[0].get_source(), node1 )
        self.assertEqual( g2.get_edges()[0].get_destination(), node2 ) 
Example #15
Source File: relationship.py    From relationships with MIT License 6 votes vote down vote up
def get_network(self, output):

        user_id = self._get_actor()

        try:
            import pydot
        except ImportError:
            raise ImportError("You need pydot library to get network functionality.")

        graph = pydot.Dot('network_of_user_{}'.format(user_id), graph_type='digraph')
        target_node = pydot.Node(user_id)

        for _id in self(user_id).following():
            user_node = pydot.Node(_id)
            graph.add_edge(pydot.Edge(target_node, user_node))

        for _id in self(user_id).followers():
            user_node = pydot.Node(_id)
            graph.add_edge(pydot.Edge(user_node, target_node))

        graph.write_png(output) 
Example #16
Source File: edge.py    From boofuzz with GNU General Public License v2.0 6 votes vote down vote up
def __init__(self, src, dst):
        """
        Class constructor.

        @type  src: Mixed
        @param src: Edge source
        @type  dst: Mixed
        @param dst: Edge destination
        """

        # the unique id for any edge (provided that duplicates are not allowed) is the combination of the source and
        # the destination stored as a long long.
        self.id = (src << 32) + dst
        self.src = src
        self.dst = dst

        # general graph attributes.
        self.color = 0x000000
        self.label = ""

        # gml relevant attributes.
        self.gml_arrow = "none"
        self.gml_stipple = 1
        self.gml_line_width = 1.0 
Example #17
Source File: create_call_graph.py    From macke with Apache License 2.0 5 votes vote down vote up
def create_pydot_edges():
    for n in list(edges.keys()):
        node_ends = edges[n]

        for e in node_ends:
            if e not in nodes:
                continue
            if n=='main':
                print(e)
            pydot_edges[(pydot_nodes[n], pydot_nodes[e])] = pydot.Edge(pydot_nodes[n], pydot_nodes[e]) 
Example #18
Source File: render.py    From flare-bytecode_graph with Apache License 2.0 5 votes vote down vote up
def dot(self, splines="ortho", show_comments=True, show_hex=False):

        graph = pydot.Dot(graph_type='digraph', splines=splines, rankdir="TD")
        
        graph.set_node_defaults(shape="box",
                                fontname="Courier New",
                                fontsize = "9")
        
        blocks = self.get_blocks()
        edges = self.get_edges(blocks)

        for start, stop in blocks:
            lbl = disassemble(self.co, start=start.addr, stop=stop.addr+1,
                              show_labels=False, show_hex=show_hex)

            if show_comments:
                comments = self.get_comments(start, stop)

                for addr, comment, lineno in comments:
                    m = re.search("^[ ]*%d .*$" % addr, lbl, re.MULTILINE)
                    if m is None:
                        continue

                    lbl = lbl[:m.end(0)] + "\n\n# %d " % lineno +\
                        comment + "\n" + lbl[m.end(0):]
                        
            # left alignment
            lbl = lbl.replace("\n", "\\l")
            lbl += "\\l"
            
            tmp = pydot.Node("%08x" % start.addr, label=lbl)
            graph.add_node(tmp)

        for edge in edges:
            tmp = pydot.Edge("%08x" % edge[0].addr,
                             "%08x" % edge[1].addr,
                             color=self.colors[edge[2]])
            graph.add_edge(tmp)

        return graph 
Example #19
Source File: trees.py    From Projects with MIT License 5 votes vote down vote up
def make_graph(graph, root, root_node):
    for child in root.children:
        child_node = pydot.Node(get_next_id(), label=child.decision)
        dot_edge = pydot.Edge(root_node, child_node)
        graph.add_node(child_node)
        graph.add_edge(dot_edge)
        make_graph(graph, child, child_node) 
Example #20
Source File: BST_utils.py    From PrincetonAlgorithms with GNU General Public License v2.0 5 votes vote down vote up
def _get_dotedges(nodes_bst, childnames):
    """Get a list of pydot Edges."""
    edges_dot = []
    for bstnode in nodes_bst:
        for cname, color in childnames.items():
            child_node = getattr(bstnode, cname)
            if child_node is not None:
                edges_dot.append(pydot.Edge(str(bstnode), str(child_node), color=color))
            else:
                null_child = _get_name_nullchild(bstnode, cname)
                edges_dot.append(pydot.Edge(str(bstnode), null_child, style='invis'))
    return edges_dot 
Example #21
Source File: Plots.py    From pyaf with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def plot_hierarchy(structure , iAnnotations, name):
    import pydot
    graph = pydot.Dot(graph_type='graph', rankdir='LR', fontsize="12.0");
    graph.set_node_defaults(shape='record')
    lLevelsReversed = sorted(structure.keys(), reverse=True);
    for level in  lLevelsReversed:
        color = '#%02x%02x%02x' % (255, 255, 127 + int(128 * (1.0 - (level + 1.0) / len(lLevelsReversed))));
        for col in structure[level].keys():
            lLabel = col if iAnnotations is None else str(iAnnotations[col]);
            if iAnnotations is not None:
                lLabel = build_record_label(iAnnotations[col]);
            node_col = pydot.Node(col, label=lLabel, style="filled", fillcolor=color, fontsize="12.0")
            graph.add_node(node_col);
            for col1 in structure[level][col]:
                lLabel1 = col1
                if iAnnotations is not None:
                    lLabel1 = build_record_label(iAnnotations[col1]);
                color1 = '#%02x%02x%02x' % (255, 255, 128 + int(128 * (1.0 - (level + 2.0) / len(lLevelsReversed))));
                node_col1 = pydot.Node(col1, label=lLabel1, style="filled",
                                       fillcolor=color1, fontsize="12.0")
                graph.add_node(node_col1);
                lEdgeLabel = "";
                if iAnnotations is not None:
                    lEdgeLabel = iAnnotations[col + "_" + col1];
                lEdge = pydot.Edge(node_col, node_col1, color="red", label=lEdgeLabel, fontsize="12.0")
                graph.add_edge(lEdge)
    # print(graph.obj_dict)
    if(name is not None):
        graph.write_png(name);
    else:
        from IPython.display import Image, display
        plot1 = Image(graph.create_png())
        display(plot1) 
Example #22
Source File: graph.py    From struct-learning-with-flow with MIT License 5 votes vote down vote up
def is_independent_set(self, nodes, show=False):
        """Checks if a list of nodes is an independent set. If show=True and the
        result is False, prints the first counter-example found.
        """
        #return all(not self.edge(m, n) for m in nodes for n in nodes)
        for m in nodes:
            for n in nodes:
                if self.edge(m, n):
                    if show:
                        print("Edge found:", (m, n))
                    return False
        return True 
Example #23
Source File: graph.py    From struct-learning-with-flow with MIT License 5 votes vote down vote up
def get_dot_graph(self, nodes=None):
        if nodes == None:
            nodes = self.nodes
        g = pydot.Dot()
        g.set_type('graph')
        for i in range(1, len(nodes)):
            node = nodes[i]
            for j in range(i):
                # maybe:
                #if self.edge(str(node), str(nodes[j])):
                if self.edge(node, nodes[j]):
                    e = pydot.Edge(node, nodes[j])
                    g.add_edge(e)
        return g 
Example #24
Source File: graph.py    From struct-learning-with-flow with MIT License 5 votes vote down vote up
def get_dot_graph(self, nodes=None, w_min=1):
        if nodes == None:
            nodes = self.nodes_list()
        g = pydot.Dot()
        g.set_type('graph')
        for i in range(1, len(nodes)):
            node = nodes[i]
            for j in range(i):
                # maybe:
                #if self.edge(str(node), str(nodes[j])):
                if self.edge_weight(node, nodes[j]) >= w_min:
                    e = pydot.Edge(node, nodes[j])
                    g.add_edge(e)
        return g 
Example #25
Source File: call_graph.py    From ida-scripts with The Unlicense 5 votes vote down vote up
def walk_graph(g,seen,callees,start):
	if start in callees.keys() and start not in seen: #Who needs recursion?
		seen.add(start)
		next = callees[start]
		for i in next:
			g.add_edge(pydot.Edge(start, i))
			walk_graph(g,seen,callees,i) 
Example #26
Source File: XRef.py    From MARA_Framework with GNU Lesser General Public License v3.0 5 votes vote down vote up
def addNodes(str1, str2):
	global graph
	node_a = pydot.Node(str1, style="filled", shape="box", color="#cccccc", fontname="Sans", fontsize=8)
	node_b = pydot.Node(str2, style="filled", shape="box", color="#cccccc", fontname="Sans", fontsize=8)
	graph.add_node(node_a)
	graph.add_node(node_b)
	graph.add_edge(pydot.Edge(node_a, node_b,color="#666666", arrowhead="open", weight=1))

# search for function (mode)references on dir/**/*.smali files 
Example #27
Source File: Flow.py    From MARA_Framework with GNU Lesser General Public License v3.0 5 votes vote down vote up
def add_edge(self, b1, b2, label="CONT"):
		""" join two pydot nodes / create nodes edge """
		# Edge color based on label text
		if label=='false':
			ecolor = "red"
		elif label=='true':
			ecolor = 'green'
		elif label == 'exception':
			ecolor = 'orange'
		elif label == 'try':
			ecolor = 'blue'
		else:
			ecolor = 'gray'
		# node shape based on block type (First or Last instruction)
		nodes = [None, None]
		blocks = [b1,b2]
		for i in range(2):
			if Block.isTag(blocks[i].instructions[-1], 'isConditional'):
				ncolor = "cornflowerblue"
			elif Block.isTag(blocks[i].instructions[0], 'isLabel'):
				ncolor = "tan"
			elif Block.isTag(blocks[i].instructions[-1], 'isJump'):
				ncolor = "darkgreen"
			elif Block.isTag(blocks[i].instructions[-1],'isCall'):
				ncolor = "lightyellow4"
			else:
				ncolor = "mediumaquamarine"
			nodes[i] = pydot.Node(b1.label, color=ncolor, style="filled", shape="box", fontname="Courier", fontsize="8")
			bis="%s\l%s\l" % (blocks[i].label, "\l".join(blocks[i].instructions))
			nodes[i].set_name(bis)
			self.graph.add_node(nodes[i])

		ed = pydot.Edge(nodes[0], nodes[1], color=ecolor, label=label, fontname="Courier", fontsize="8", arrowhead="open")
		self.graph.add_edge(ed) 
Example #28
Source File: graph.py    From dcc with Apache License 2.0 5 votes vote down vote up
def draw(self, name, dname, draw_branches=True):
        """
        Writes the current graph as a PNG file

        :param str name: filename (without .png)
        :param str dname: directory of the output png
        :param draw_branches:
        :return:
        """
        from pydot import Dot, Edge
        import os

        g = Dot()
        g.set_node_defaults(color='lightgray',
                            style='filled',
                            shape='box',
                            fontname='Courier',
                            fontsize='10')
        for node in sorted(self.nodes, key=lambda x: x.num):
            if draw_branches and node.type.is_cond:
                g.add_edge(Edge(str(node), str(node.true), color='green'))
                g.add_edge(Edge(str(node), str(node.false), color='red'))
            else:
                for suc in self.sucs(node):
                    g.add_edge(Edge(str(node), str(suc), color='blue'))
            for except_node in self.catch_edges.get(node, []):
                g.add_edge(Edge(str(node),
                                str(except_node),
                                color='black',
                                style='dashed'))

        g.write(os.path.join(dname, '%s.png' % name), format='png') 
Example #29
Source File: tree.py    From lark with MIT License 5 votes vote down vote up
def pydot__tree_to_png(tree, filename, rankdir="LR", **kwargs):
    """Creates a colorful image that represents the tree (data+children, without meta)

    Possible values for `rankdir` are "TB", "LR", "BT", "RL", corresponding to
    directed graphs drawn from top to bottom, from left to right, from bottom to
    top, and from right to left, respectively.

    `kwargs` can be any graph attribute (e. g. `dpi=200`). For a list of
    possible attributes, see https://www.graphviz.org/doc/info/attrs.html.
    """

    import pydot
    graph = pydot.Dot(graph_type='digraph', rankdir=rankdir, **kwargs)

    i = [0]

    def new_leaf(leaf):
        node = pydot.Node(i[0], label=repr(leaf))
        i[0] += 1
        graph.add_node(node)
        return node

    def _to_pydot(subtree):
        color = hash(subtree.data) & 0xffffff
        color |= 0x808080

        subnodes = [_to_pydot(child) if isinstance(child, Tree) else new_leaf(child)
                    for child in subtree.children]
        node = pydot.Node(i[0], style="filled", fillcolor="#%x"%color, label=subtree.data)
        i[0] += 1
        graph.add_node(node)

        for subnode in subnodes:
            graph.add_edge(pydot.Edge(node, subnode))

        return node

    _to_pydot(tree)
    graph.write_png(filename) 
Example #30
Source File: pydot_unittest.py    From pydot with MIT License 5 votes vote down vote up
def test_graph_pickling(self):


        g = pydot.Graph()
        s = pydot.Subgraph("foo")
        g.add_subgraph(s)
        g.add_edge( pydot.Edge('A','B') )
        g.add_edge( pydot.Edge('A','C') )
        g.add_edge( pydot.Edge( ('D','E') ) )
        g.add_node( pydot.Node( 'node!' ) )
        pickle.dumps(g)