コード例 #1
0
 def render(self, path_file, extension):
     try:
         main(path_file)  # check for errors
     except (parseError, ForkStatementDetected) as e:
         return e.message[0] + " " + e.message[1]  # return eventually an error message
     else:
         save_path = render('dot', extension, path_file)
         view(save_path)  # open the default image viewer
         return save_path
コード例 #2
0
ファイル: APICodeLEIA.py プロジェクト: posticarus/cap-labs
 def printDot(self, filename):
     # Only used in Lab 6
     graph = nx.DiGraph()
     self._start.printDot(graph, set())
     graph.graph['graph'] = dict()
     graph.graph['graph']['overlap'] = 'false'
     nx.drawing.nx_agraph.write_dot(graph, filename)
     gz.render('dot', 'pdf', filename)
     gz.view(filename + '.pdf')
コード例 #3
0
 def print_graph(graph: ESTGGraph,
                 file_name: str,
                 view_flag: bool = False,
                 overwrite_graph: bool = False):
     if os.path.isfile(TextParseESTG.PATH_TO_GRAPH + file_name) and not GraphUtil.__was_file_changed(file_name)\
             and not overwrite_graph:
         if view_flag:
             gv.view(TextParseESTG.PATH_TO_GRAPH + file_name +
                     TextParseESTG.SVG_EXTENSION)
         return
     g = gv.Digraph(format='svg', strict=True)
     initial_marking = graph.initial_places
     mark_traversed_transitions = {}
     mark_placed_places = {}
     for place in initial_marking:
         if place not in mark_placed_places:
             g.node(place.name,
                    shape="circle",
                    width=".5",
                    fixedsize="true")
             mark_placed_places[place] = 1
         for end_place in graph.stg_graph[place]:
             if end_place not in mark_placed_places:
                 g.node(end_place.name,
                        shape="circle",
                        width=".5",
                        fixedsize="true")
                 mark_placed_places[end_place] = 1
             key = place.name + end_place.name + str(
                 graph.stg_graph_transitions[(place, end_place)])
             if key not in mark_traversed_transitions:
                 transition = graph.stg_graph_transitions[(place,
                                                           end_place)]
                 g.node(transition.name,
                        label="",
                        xlabel=GraphUtil.__transition_to_string(
                            transition.transition),
                        shape="box",
                        width="0.5",
                        height="0.001")
                 g.edge(place.name,
                        transition.name,
                        arrowhead="onormal",
                        arrowsize="0.5")
                 g.edge(transition.name, end_place.name)
                 mark_traversed_transitions[key] = 1
             GraphUtil.__aux_print_graph(mark_traversed_transitions,
                                         mark_placed_places, g, end_place,
                                         graph)
     g.render(TextParseESTG.PATH_TO_GRAPH + file_name)
     g.save(TextParseESTG.PATH_TO_GRAPH + file_name)
     if view_flag:
         gv.view(TextParseESTG.PATH_TO_GRAPH + file_name +
                 TextParseESTG.SVG_EXTENSION)
コード例 #4
0
    def plot(self):

        from networkx.drawing.nx_agraph import to_agraph

        dot = to_agraph(self.G)
        dot.layout("dot")
        dot.draw("../graphs/pseudo_mpe.png", format="png")

        from graphviz import view
        view("../graphs/pseudo_mpe.png")

        return
コード例 #5
0
ファイル: controller.py プロジェクト: vairodp/Corinne-2
    def render(self, path_file, extension, V_rend_on_default_image_viewer):
        try:
            main(path_file)  # check for errors
        except (parseError, ForkStatementDetected) as e:
            print("non riesco a creare il render")
            return e.message[0] + " " + e.message[
                1]  # return eventually an error message
        else:
            #V voglio mettere che lo apre se glielo dico io,altirmenti mi rendera quello
            #che volgio
            save_path = render('dot', extension, path_file)

            if V_rend_on_default_image_viewer == True:
                view(save_path)  # open the default image viewer
            return save_path
コード例 #6
0
    def saveAndView(self,name='./myDFA.gv'):
        """
        Saves a copy of the constructed DFA and opens a PDF version for viewing.

        Parameters
        ----------
        name : str, optional
            The name AND relative (or absolute) path for your saved DFA.
            The default is './myDFA.gv'.

        Returns
        -------
        None.

        """
        nx.drawing.nx_agraph.write_dot(self.__DFA,name)
        gv.render('dot','pdf',name)
        ViewName = name + '.pdf'
        gv.view(ViewName)
コード例 #7
0
def render(
    source: gv.Source,
    out_path: str,
    format: str = None,
    engine: str = None,
    renderer: str = None,
    formatter: str = None,
    view: bool = False,
) -> None:
    """
    Render source with Graphviz.

    Parameters
    ----------
    source
        Graphviz source to render
    out_path
        path to visualisation file to write
    format
        Graphviz render file format
    engine
        Graphviz layout engine
    renderer
        Graphviz output renderer
    formatter
        Graphviz output formatter
    view
        after rendering, display with the default application
    """
    image_bytes = gv.pipe(
        engine or source.engine,
        format,
        str(source).encode(),
        renderer=renderer,
        formatter=formatter,
    )
    out_path = Path(out_path).with_suffix('.' + format)
    out_path.parent.mkdir(parents=True, exist_ok=True)
    out_path.write_bytes(image_bytes)
    if view:
        gv.view(str(out_path))
コード例 #8
0
 def printDot(self, filename, view=False):
     # Only used in Lab 5
     graph = nx.DiGraph()
     names = dict()
     for i, instruction in enumerate(self._listIns):
         names[instruction] = str(i) + "_" + str(instruction)
     # nodes
     for instruction in self._listIns:
         graph.add_node(names[instruction])
     # edges
     for instruction in self._listIns:
         for child in instruction._out:
             graph.add_edge(names[instruction], names[child])
     # Add a fake "START" node to mark the entry of the CFG
     if i == 0:
         graph.add_node("START")
         graph.add_edge("START", names[self._start])
     graph.graph['graph'] = dict()
     graph.graph['graph']['overlap'] = 'false'
     nx.drawing.nx_agraph.write_dot(graph, filename)
     gz.render('dot', 'pdf', filename)
     if view:
         gz.view(filename + '.pdf')
コード例 #9
0
def test_view_mocked(mocker, mock_platform, mock_popen, mock_startfile, quiet):
    assert graphviz.view('nonfilepath', quiet=quiet) is None

    if mock_platform == 'windows':
        mock_startfile.assert_called_once_with('nonfilepath')
        return

    if quiet:
        kwargs = {'stderr': subprocess.DEVNULL}
    else:
        kwargs = {}

    if mock_platform == 'darwin':
        mock_popen.assert_called_once_with(['open', 'nonfilepath'], **kwargs)
    elif mock_platform in ('linux', 'freebsd'):
        mock_popen.assert_called_once_with(['xdg-open', 'nonfilepath'], **kwargs)
    else:
        raise RuntimeError
コード例 #10
0
def test_view_unknown_platform():
    with pytest.raises(RuntimeError, match=r'platform'):
        graphviz.view('nonfilepath')
コード例 #11
0
print("MD=4 Train accuracy: {:.3f}".format(tree.score(X_train, y_train)))

print("MD=4 Test accuracy: {:.3f}".format(tree.score(X_test, y_test)))

s = export_graphviz(tree,
                    out_file='tree.dot',
                    class_names=['malignant', 'benign'],
                    feature_names=cancer.feature_names,
                    impurity=False,
                    filled=True)

f = open('tree.dot', "r")
dot_graph = f.read()
f.close()
graphviz.Source(dot_graph, format='pdf', filename='tree.pdf')
graphviz.view(dot_graph)

print(
    "\n\x1b[0;30;47mPour voir le graphe, aller sur http://webgraphviz.com/, copier l'affichage en balise\x1b[0m"
)

print("Feature Importance:\n{}".format(tree.feature_importances_))

plot_feature_importances_cancer(tree)

from IPython.display import display

tree = dsets.plot_tree_not_monotone()
display(tree)
コード例 #12
0
ファイル: network.py プロジェクト: aguellier/apart
    def draw_routes(self, *args, blocking=False):
        """Draw the routes between one or several pairs of nodes
        
        For each sender-receiver pair in argument, the function will draw all
        the routes that the sender knows towards the receiver.
        
        
        Arguments:
            args(list of 2-tuple):  a list of 2-tuple, each specifying a source and a destination
            blocking (bool, optional): whether or not the python program
                            should be stopped until the gtk window is closed, or
                            should continue to run in the background
        """

        for from_node, to_node in args:
            if (not isinstance(from_node, int) or from_node < 0
                    or from_node > self._sim_params.nb_nodes
                    or not isinstance(to_node, int) or to_node < 0 or to_node
                    >= self._sim_params.nb_nodes) or from_node == to_node:
                continue

            # Create a directed graph with no edges, using the physical graph
            routes_graph = nx.MultiGraph()
            for n in self.nodes:
                routes_graph.add_edges_from(((n.id, neighbor)
                                             for neighbor in n.neighbors
                                             if neighbor > n.id))
            edge_labels = c.defaultdict(lambda: "")

            # Recursive function crawling through the nodes' tables
            def trace_route(current_node,
                            next_node,
                            next_cid,
                            previous_node=None):
                # Update the edge list and edge labels
                if previous_node is None:
                    edge_labels[current_node,
                                next_node] = str(current_node) + " "
                else:
                    edge_labels[current_node, next_node] = edge_labels[
                        previous_node, current_node] + str(current_node) + " "
                routes_graph.add_edge(current_node,
                                      next_node,
                                      label=edge_labels[current_node,
                                                        next_node],
                                      penwidth=2)

                if next_node == to_node:
                    return

                # Retrieve, using the RT+PRTof the "next_node", the next hop.
                # VERY WRONG : this table lookup triggers a sql query. SQL
                # queries inside loops are wrooooong, and can often be avoided.
                # But this is much simpler, and this function's efficiency is
                # not critical, since called only for debug
                entries = self.nodes[next_node].rt.joint_lookup(
                    PRT,
                    fields=[RT.NEXT_NODE, RT.NEXT_CID],
                    join_on=(RT.ROWID, PRT.RT_ROWID),
                    constraints={
                        PRT.PREV_NODE: current_node,
                        PRT.PREV_CID: next_cid
                    })
                assert len(
                    entries
                ) == 1, "{} entries returned: {}\nWhile tracing from node {} to node {}, with current_node = {}, next_hop = {}. See tables".format(
                    len(entries), [[v for v in r] for r in entries], from_node,
                    to_node, current_node, (next_node, next_cid),
                    self.nodes[next_node].display_node_table())
                next_hop = entries[0]

                # There may be several possible next hops that lead to the destination
                # For each possible next hop, call trace_route again (unless the next _node is the destination)
                trace_route(next_node,
                            next_hop[RT.NEXT_NODE],
                            next_hop[RT.NEXT_CID],
                            previous_node=current_node)

            # Add edges according to the RT of nodes in the network
            starts_of_routes = self.nodes[from_node].rt.lookup(
                fields=[RT.NEXT_NODE, RT.NEXT_CID],
                constraints={RT.ACTUAL_RCVR: to_node})
            #             self._db.execute("SELECT rowid, * FROM drt WHERE _node=? AND actualdest=? AND istemporary=0 AND actualnexthop<>-1", (from_node, to_node,))
            #             drt_entries = self._db.fetchall()
            logging.info("Drawing {} routes from {} to {}".format(
                len(starts_of_routes), from_node, to_node))

            for route in starts_of_routes:
                trace_route(from_node, route[RT.NEXT_NODE], route[RT.NEXT_CID])

            nx.drawing.nx_pydot.write_dot(
                routes_graph,
                '/tmp/routes_graph_{}-{}.dot'.format(from_node, to_node))
            graphviz.render(
                'dot', 'png',
                '/tmp/routes_graph_{}-{}.dot'.format(from_node, to_node))
            time.sleep(1)
            graphviz.view('/tmp/routes_graph_{}-{}.dot.png'.format(
                from_node, to_node))
            os.remove('/tmp/routes_graph_{}-{}.dot'.format(from_node, to_node))