Python pydot.Dot() Examples

The following are 30 code examples of pydot.Dot(). 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: relations.py    From oerplib with GNU Lesser General Public License v3.0 6 votes vote down vote up
def write(self, *args, **kwargs):
        """Write the resulting graph in a file.
        It is just a wrapper around the :func:`pydot.Dot.write` method
        (see the `pydot <http://code.google.com/p/pydot/>`_ documentation for
        details).  Below a common way to use it::

            >>> graph = oerp.inspect.relations(['res.partner'])
            >>> graph.write('relations_res_partner.png', format='png')

        About supported formats, consult the
        `Graphviz documentation <http://www.graphviz.org/doc/info/output.html>`_.
        """
        output = self.make_dot()
        return output.write(*args, **kwargs)

# vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4: 
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 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 #5
Source File: callgraph.py    From barf-project with BSD 2-Clause "Simplified" License 6 votes vote down vote up
def save(self, cf, filename, format='dot'):
        """Save basic block graph into a file.
        """
        try:
            dot_graph = Dot(**self.graph_format)

            # add nodes
            nodes = {}
            for cfg_addr in cf._graph.node.keys():
                nodes[cfg_addr] = self._create_node(cfg_addr, cf)

                dot_graph.add_node(nodes[cfg_addr])

            # add edges
            for cfg_src_addr in cf._graph.node.keys():
                for cfg_dst_addr in cf._edges.get(cfg_src_addr, []):
                    edge = self._create_edge(nodes, cfg_src_addr, cfg_dst_addr)

                    dot_graph.add_edge(edge)

            dot_graph.write("{}.{}".format(filename, format), format=format)
        except Exception:
            logger.error("Failed to save call graph: %s (%s)", filename, format, exc_info=True) 
Example #6
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 #7
Source File: vis_utils.py    From GraphicDesignPatternByPython with MIT License 6 votes vote down vote up
def _check_pydot():
    """Raise errors if `pydot` or GraphViz unavailable."""
    if pydot is None:
        raise ImportError(
            'Failed to import `pydot`. '
            'Please install `pydot`. '
            'For example with `pip install pydot`.')
    try:
        # Attempt to create an image of a blank graph
        # to check the pydot/graphviz installation.
        pydot.Dot.create(pydot.Dot())
    except OSError:
        raise OSError(
            '`pydot` failed to call GraphViz.'
            'Please install GraphViz (https://www.graphviz.org/) '
            'and ensure that its executables are in the $PATH.') 
Example #8
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 #9
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 #10
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 #11
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 #12
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 #13
Source File: BST_utils.py    From PrincetonAlgorithms with GNU General Public License v2.0 6 votes vote down vote up
def wr_png(fout_png, nodes_bst, childnames, log):
    """Save tree figure to png file."""
    # 1. create/initialize graph
    g = pydot.Dot(graph_type='digraph') # directed graph
    # 2. create pydot Nodes
    nodes_dot = _get_dotnodes(nodes_bst, childnames)
    # 3. add nodes to graph
    for dotnode in nodes_dot:
        g.add_node(dotnode)
    # 4. add edges between nodes to graph
    edges_dot = _get_dotedges(nodes_bst, childnames)
    for dotedge in edges_dot:
        g.add_edge(dotedge)
    # 5. write graph to png file
    g.write_png(fout_png)
    log.write("  wrote: {}\n".format(fout_png)) 
Example #14
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 #15
Source File: dependencies.py    From oerplib with GNU Lesser General Public License v3.0 6 votes vote down vote up
def write(self, *args, **kwargs):
        """Write the resulting graph in a file.
        It is just a wrapper around the :func:`pydot.Dot.write` method
        (see the `pydot <http://code.google.com/p/pydot/>`_ documentation for
        details).  Below a common way to use it::

            >>> graph = oerp.inspect.dependencies(['base'], ['res.partner'])
            >>> graph.write('dependencies_res_partner.png', format='png')
        
        About supported formats, consult the
        `Graphviz documentation <http://www.graphviz.org/doc/info/output.html>`_.
        """
        output = self.make_dot()
        return output.write(*args, **kwargs)

# vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4: 
Example #16
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 #17
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 #18
Source File: dot_parser.py    From pydot with MIT License 6 votes vote down vote up
def parse_dot_data(s):
    """Parse DOT description in (unicode) string `s`.

    @return: Graphs that result from parsing.
    @rtype: `list` of `pydot.Dot`
    """
    global top_graphs
    top_graphs = list()
    try:
        graphparser = graph_definition()
        graphparser.parseWithTabs()
        tokens = graphparser.parseString(s)
        return list(tokens)
    except ParseException as err:
        print(
            err.line +
            " "*(err.column-1) + "^" +
            err)
        return None 
Example #19
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 #20
Source File: graph.py    From boofuzz with GNU General Public License v2.0 6 votes vote down vote up
def render_graph_graphviz(self):
        """
        Render the graphviz graph structure.

        @rtype:  pydot.Dot
        @return: Pydot object representing entire graph
        """
        dot_graph = pydot.Dot()

        for node in listvalues(self.nodes):
            dot_graph.add_node(node.render_node_graphviz(self))

        for edge in listvalues(self.edges):
            dot_graph.add_edge(edge.render_edge_graphviz(self))

        return dot_graph 
Example #21
Source File: vis_utils.py    From keras-lambda with MIT License 5 votes vote down vote up
def _check_pydot():
    try:
        # Attempt to create an image of a blank graph
        # to check the pydot/graphviz installation.
        pydot.Dot.create(pydot.Dot())
    except Exception:
        # pydot raises a generic Exception here,
        # so no specific class can be caught.
        raise ImportError('Failed to import pydot. You must install pydot'
                          ' and graphviz for `pydotprint` to work.') 
Example #22
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 #23
Source File: nx_pydot.py    From Carnets with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def read_dot(path):
    """Returns a NetworkX :class:`MultiGraph` or :class:`MultiDiGraph` from the
    dot file with the passed path.

    If this file contains multiple graphs, only the first such graph is
    returned. All graphs _except_ the first are silently ignored.

    Parameters
    ----------
    path : str or file
        Filename or file handle.

    Returns
    -------
    G : MultiGraph or MultiDiGraph
        A :class:`MultiGraph` or :class:`MultiDiGraph`.

    Notes
    -----
    Use `G = nx.Graph(read_dot(path))` to return a :class:`Graph` instead of a
    :class:`MultiGraph`.
    """
    pydot = _import_pydot()
    data = path.read()

    # List of one or more "pydot.Dot" instances deserialized from this file.
    P_list = pydot.graph_from_dot_data(data)

    # Convert only the first such instance into a NetworkX graph.
    return from_pydot(P_list[0]) 
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):
        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 #25
Source File: vis_utils.py    From DeepLearning_Wavelet-LSTM with MIT License 5 votes vote down vote up
def _check_pydot():
    try:
        # Attempt to create an image of a blank graph
        # to check the pydot/graphviz installation.
        pydot.Dot.create(pydot.Dot())
    except Exception:
        # pydot raises a generic Exception here,
        # so no specific class can be caught.
        raise ImportError('Failed to import pydot. You must install pydot'
                          ' and graphviz for `pydotprint` to work.') 
Example #26
Source File: nx_pydot.py    From aws-kube-codesuite with Apache License 2.0 5 votes vote down vote up
def read_dot(path):
    """Return a NetworkX :class:`MultiGraph` or :class:`MultiDiGraph` from the
    dot file with the passed path.

    If this file contains multiple graphs, only the first such graph is
    returned. All graphs _except_ the first are silently ignored.

    Parameters
    ----------
    path : str or file
        Filename or file handle.

    Returns
    -------
    G : MultiGraph or MultiDiGraph
        A :class:`MultiGraph` or :class:`MultiDiGraph`.

    Notes
    -----
    Use `G = nx.Graph(read_dot(path))` to return a :class:`Graph` instead of a
    :class:`MultiGraph`.
    """
    pydot = _import_pydot()
    data = path.read()

    # List of one or more "pydot.Dot" instances deserialized from this file.
    P_list = pydot.graph_from_dot_data(data)

    # Convert only the first such instance into a NetworkX graph.
    return from_pydot(P_list[0]) 
Example #27
Source File: vis_utils.py    From DeepLearning_Wavelet-LSTM with MIT License 5 votes vote down vote up
def _check_pydot():
    try:
        # Attempt to create an image of a blank graph
        # to check the pydot/graphviz installation.
        pydot.Dot.create(pydot.Dot())
    except Exception:
        # pydot raises a generic Exception here,
        # so no specific class can be caught.
        raise ImportError('Failed to import pydot. You must install pydot'
                          ' and graphviz for `pydotprint` to work.') 
Example #28
Source File: vis_utils.py    From DeepLearning_Wavelet-LSTM with MIT License 5 votes vote down vote up
def _check_pydot():
    try:
        # Attempt to create an image of a blank graph
        # to check the pydot/graphviz installation.
        pydot.Dot.create(pydot.Dot())
    except Exception:
        # pydot raises a generic Exception here,
        # so no specific class can be caught.
        raise ImportError('Failed to import pydot. You must install pydot'
                          ' and graphviz for `pydotprint` to work.') 
Example #29
Source File: vis_utils.py    From DeepLearning_Wavelet-LSTM with MIT License 5 votes vote down vote up
def _check_pydot():
    try:
        # Attempt to create an image of a blank graph
        # to check the pydot/graphviz installation.
        pydot.Dot.create(pydot.Dot())
    except Exception:
        # pydot raises a generic Exception here,
        # so no specific class can be caught.
        raise ImportError('Failed to import pydot. You must install pydot'
                          ' and graphviz for `pydotprint` to work.') 
Example #30
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')