Esempio n. 1
0
 def build_graphViz(self):
     render(
         'dot', 'png',
         'file.dot')  # saves the graphViz plot to current working directory
     graphviz.Source.from_file(
         'file.dot'
     )  # does the same thing, but renders the plot if ran interactively
Esempio n. 2
0
def treetest():
    cancer = load_breast_cancer()
    x_train, x_test, y_train, y_test = train_test_split(cancer.data,
                                                        cancer.target,
                                                        stratify=cancer.target,
                                                        random_state=42)
    tree = DecisionTreeClassifier(max_depth=4, random_state=0)
    tree.fit(x_train, y_train)

    # 导出决策树到文件
    export_graphviz(tree,
                    out_file="../tree.dot",
                    class_names=["malignant", "benign"],
                    feature_names=cancer.feature_names,
                    impurity=False,
                    filled=True)

    print("Accuracy on training set: {:.3f}".format(
        tree.score(x_train, y_train)))
    print("Accuracy on test set: {:.3f}".format(tree.score(x_test, y_test)))
    tree.predict()
    # 读取决策树并显示
    with open("../tree.dot") as f:
        dot_graph = f.read()
    graphviz.Source(dot_graph)
    graphviz.render('round-table.gv')
Esempio n. 3
0
def mlCreateDecisionClassifierTree(test_name, goodPlacementsIds,
                                   badPlacementsIds):
    allFeaturesForRecognition, recognitionMarks = mlGetPlacementsInfo(
        test_name=test_name,
        teacher=True,
        goodPlacementsIds=goodPlacementsIds,
        badPlacementsIds=badPlacementsIds)
    print "creating tree"
    treeClassifier = tree.DecisionTreeClassifier().fit(
        allFeaturesForRecognition, recognitionMarks)
    joblib.dump(treeClassifier,
                "decision_classifier_tree_weekly.pkl",
                compress=1)
    feature_names = [
        "Sunday ctr", "Sunday cvr", "Sunday cpc", "Sunday cpm", "Sunday cpa",
        "Monday ctr", "Monday cvr", "Monday cpc", "Monday cpm", "Monday cpa",
        "Tuesday ctr", "Tuesday cvr", "Tuesday cpc", "Tuesday cpm",
        "Tuesday cpa", "Wednesday ctr", "Wednesday cvr", "Wednesday cpc",
        "Wednesday cpm", "Wednesday cpa", "Thursday ctr", "Thursday cvr",
        "Thursday cpc", "Thursday cpm", "Thursday cpa", "Friday ctr",
        "Friday cvr", "Friday cpc", "Friday cpm", "Friday cpa", "Saturday ctr",
        "Saturday cvr", "Saturday cpc", "Saturday cpm", "Saturday cpa"
    ]
    class_names = ["bad", "good"]
    print "save png"
    dot_data = tree.export_graphviz(
        treeClassifier,
        out_file="decision_classifier_tree_weekly.dot",
        feature_names=feature_names,
        class_names=class_names,
        filled=True,
        rounded=True,
        special_characters=True)
    graphviz.render("dot", "png", "decision_classifier_tree_weekly.dot")
Esempio n. 4
0
def export_decision_tree(dtree,cols,dataset,label):
    # Export decision tree
    OUTPUT_DIRECTORY = "output"
    graph_data = tree.export_graphviz(dtree, out_file=None, feature_names=cols,class_names=label)
    graph_data = graphviz.Source(graph_data)
    graphviz.render("out[ut/images/{}_dtree.png".format(dataset),view=True)
    # system("dot -Tpng /home/liuwensui/Documents/code/dtree2.dot -o /home/liuwensui/Documents/code/dtree2.png")
Esempio n. 5
0
def Imprimir_solucao(solucao,filename,mapa):
    
    node_list = []
    parent = solucao
    while (parent):
        node_list.append(parent)
        parent = parent.parent
        
    list_solucao = []
    custo_total = 0
    list_id = []
    for node in reversed(node_list):
        name = [x.strip() for x in node.name.split(',')][0]
        list_id.append(node.city_id)
        if(node.parent):
            list_solucao.append(Node(name,parent = list_solucao[-1]))
            custo_total += calc_dist_haversine(mapa.change_id2pos(node.city_id),mapa.change_id2pos(node.parent.city_id))
        else:
           list_solucao.append(Node(name))

    
    DotExporter(list_solucao[0]).to_dotfile(filename)
    render('dot', 'pdf', filename)
    print("Altura da Arvore de busca: ",node_list[-1].height)
    print("Numero de nós da Arvore de busca",len(node_list[-1].descendants) +1)
    print("Custo Total: ",custo_total)
    print("IDS: ",list_id)
Esempio n. 6
0
def main():
    g, tree, root = ensure_graph_data()
    if g:
        g.render(graph_file, view=False, cleanup=True)
    else:
        print('!!!!!Cached Response!!!!!')
        render(engine, file_type, graph_file)
    def crearImagen(self):
        nombreImagen = 'miAgenda.dot'
        salidaImagen = open(nombreImagen, 'w')
        salidaImagen.write('digraph G { \n')
        salidaImagen.write('node [shape=plaintext] \n')
        salidaImagen.write(
            'a [label=<<table border="0" cellborder="1" cellspacing="0"> \n')
        cantidad = self.verCantidad()
        salidaImagen.write(
            '<tr><td colspan="3"> Contactos de mi agenda </td></tr>\n')
        salidaImagen.write('<tr> \n')
        salidaImagen.write('\t <td> Nombre </td>')
        salidaImagen.write('<td> Apellido </td>')
        salidaImagen.write('<td> Telefono </td>')
        salidaImagen.write('</tr> \n')
        temporal = self.inicio
        while temporal != None:
            salidaImagen.write('<tr> \n')
            salidaImagen.write('\t <td>' + temporal.nombre + '</td> <td>' +
                               temporal.apellido + '</td> <td>' +
                               str(temporal.telefono) + '</td>')
            salidaImagen.write('</tr> \n')
            temporal = temporal.siguiente

        salidaImagen.write('</table>>]; \n')
        salidaImagen.write('}')
        salidaImagen.close()
        render('dot', 'png', nombreImagen)  #Renderizar el archivo DOT escrito

        webbrowser.open_new_tab(
            "miAgenda.dot.png")  #Abrir navegador para visualizar agenda
def recorrer_arbol(nodoRaiz):
    #print(nodoRaiz.hijos)
    #for nodo in nodoRaiz.hijos:

    #  recorrer_arbol(nodo)
    graficar_arbol(imprimir_arbol(nodoRaiz, 0))
    render('dot', 'png', 'AST_Desc.dot')
    def draw(self, _filename="fsm", makePng=False):

        if not GraphvizImportSuccessful:
            print(
                "You need to successfully install graphviz to use draw method")
            return

        f = Digraph("Finite_State_Machine", filename=_filename + ".gv")

        f.attr("node", shape="circle")

        for node in self.nodes:
            for i in range(self.numOfInputs):
                if (node.transitions[i][0] != None):
                    f.edge(str(node.index),
                           str(node.transitions[i][0].index),
                           label="i:{}/o:{}".format(i, node.transitions[i][1]))

        try:
            f.view()  #Tries to view the graph
        except Exception as e:
            print(e)
            print("Unable to draw the graph")
            return

        if makePng:
            render("dot", "png", _filename + ".gv")  # Makes a png file
Esempio n. 10
0
    def dump_graph_for_graphviz(self, node_attrs: list = [], edge_attrs: list = [], nodes_to_dump: list = None,
                                save_to_svg=False, highlight_nodes: list = None):
        log.debug("---- GRAPHVIZ OUTPUT STARTS ----")
        if nodes_to_dump is None:
            nodes_to_dump = self.nodes()
        string = '\ndigraph {\n'
        string += 'node [color=lightblue2, style=filled];\n'

        for node in nodes_to_dump:
            attrs = ""
            if hasattr(node, 'enabled') and not node.enabled:
                attrs += "color=gray70,"
            string += '"{}" [{}];\n'.format(node, attrs)

        visited_nodes = set()
        for src_node_name, dst_node_name, attrs in self.edges(data=True):
            visited_nodes.add(src_node_name)
            visited_nodes.add(dst_node_name)
            if src_node_name not in nodes_to_dump or dst_node_name not in nodes_to_dump:
                continue
            src_node = self.node[src_node_name]
            dst_node = self.node[dst_node_name]
            src_node_string = str(src_node_name) + '\\n'.join(
                [str(key) + '=' + str(src_node.get(key, 'None')) for key in node_attrs if key in src_node])
            dst_node_string = str(dst_node_name) + '\\n'.join(
                [str(key) + '=' + str(dst_node.get(key, 'None')) for key in node_attrs if key in dst_node])
            edge_string = ' '.join([str(key) + '=' + str(attrs.get(key, 'None')) for key in edge_attrs if key in attrs])
            string += '"{}" -> "{}" [label = "{}"];\n'.format(src_node_string, dst_node_string, edge_string)

        for node in nodes_to_dump:
            if node not in visited_nodes:
                string += '"{}";\n'.format(node)
                visited_nodes.add(node)

        string += '}'
        log.debug(string)
        log.debug("---- GRAPHVIZ OUTPUT ENDS ----")

        if save_to_svg:
            try:
                import graphviz
                import os
                file_name = "{}_{}.txt".format(self.name.replace('/', '_'), 0)
                id = 1
                while os.path.exists(file_name):
                    file_name = "{}_{}.txt".format(self.name.replace('/', '_'), id)
                    id += 1
                with open(file_name, "w") as f:
                    f.write(string)
                graphviz.render('dot', 'svg', file_name)
                print('Graph was saved to {}.{}'.format(file_name, 'svg'))
            except ImportError:
                raise ImportError('Can\'t import graphviz')
            except Exception as e:
                raise Error('Can\'t save graph to svg') from e

        return string
    def visualize(self, path):
        """! @brief Creates a pdf and a DOT-format file with a proper visualisatzion of the graph.
        
            @param path     path to the dot-format file and the pdf
        """
        vis_graph = self.getVisGraph()

        nx.drawing.nx_pydot.write_dot(vis_graph, path + ".gv")
        render('dot', 'pdf', path + ".gv")
Esempio n. 12
0
 def codigoBoton():
     consola.delete(1.0, 'end')
     contenido = texto.get(1.0, 'end')
     nod = Node()
     nod = g.Analizador(str(contenido))
     consola.insert(INSERT, str(nod.Resultado()) + "\n")
     CrearArchivo(str(nod.traducir()))
     #render('dot', 'Tjpg','arbol.dot','-O', 'arbol.jpg')
     render('dot', 'jpg', 'arbol.dot')
Esempio n. 13
0
 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')
Esempio n. 14
0
def test_render_raises_mocked(tmp_path, mock_run, args, kwargs,
                              expected_exception, match):
    if issubclass(expected_exception, FileExistsError):
        existing_outfile = tmp_path / kwargs['outfile']
        existing_outfile.touch()

    with _common.as_cwd(tmp_path):
        with pytest.raises(expected_exception, match=match):
            graphviz.render(*args, **kwargs)
Esempio n. 15
0
def create_graph(filename):

    # lines = get_dot(root).split("\n")
    # lines[0] = "digraph "+filename+" {"
    # lines = "\n".join(lines)
    # f = open("charts/"+filename+".txt", 'w')
    # f.write(lines)
    # f.close()
    render("dot", "svg", 'charts/' + filename + '.txt')
Esempio n. 16
0
def recorrer_arbol(nodoRaiz):
    #print(nodoRaiz.hijos)
    #for nodo in nodoRaiz.hijos:

    #  recorrer_arbol(nodo)
    try:
        graficar_arbol(imprimir_arbol(nodoRaiz, 0))
        render('dot', 'png', 'AST_asc.dot')
    except:
        print("Error recorrido arbol AST\n")
Esempio n. 17
0
def visualize_gv_manually(gv_file, render_mode='dot'):
    '''
    手动生成可视化图
    :param gv_file:
    :param render_mode:
    :return:
    '''

    render(engine=render_mode, format='pdf', filepath=gv_file, quiet=False)
    return
Esempio n. 18
0
 def show(self):
     self.__nb_null = 0
     with open("tree.dot", 'w') as dot_file:
         dot_file.write('digraph G{\n\tgraph [ordering="out"];\n')
         list_of_relation_strings = []
         self.__sub_write__(dot_file, list_of_relation_strings, self.root)
         dot_file.write("\n")
         dot_file.writelines(list_of_relation_strings)
         dot_file.write("}")
     graphviz.render("dot", "png", "tree.dot")
Esempio n. 19
0
    def render(self, img_name, style):
        """

        :param img_name:
        :type img_name: str
        :param style:
        :type style: dict
        """
        graph = self.build_graph_()
        gv = apply_styles(graph, style)
        gv.render(img_name)
def Graficar(raiz):
    file = open("arbol.dot", "w")
    file.write(
        " digraph G {\n" + "     rankdir=TB; " + "" +
        " node[ shape=record,  style=filled ,fillcolor=seashell2, fontcolor=black, color=coral1];  \n"
        + "edge[color=chartreuse1] \n")
    file.write(recorrerarbol(raiz))
    file.write("} \n")

    file.close()
    render('dot', 'jpg', 'arbol.dot')
Esempio n. 21
0
			def gen():
				graphing_wrapper.generate_bnf()
				graph = graphing_wrapper.generate('grammar')
				graphing_wrapper.generate_gv_dot(graph)
				import graphviz
				print("generate svg")
				graphviz.render('dot', 'svg', 'grammar.gv')
				graph = graphing_wrapper.generate2('grammar2', s.c_syms[inp.start])
				graphing_wrapper.generate_gv_dot(graph)
				print("generate svg")
				graphviz.render('dot', 'svg', 'grammar2.gv')
 def graph_draw_gen(self):
     for key, value in self.graph.items():
         graph_name = value
     # write_dot(self, 'Image-Graphs/' + graph_name + '.gv') DROP ????
     render('dot', 'png', 'Image-Graphs/' + graph_name + '.gv')
     graph_list_pos = nx.nx_pydot.pydot_layout(self, prog='dot')
     edge_labels = nx.get_edge_attributes(self, 'choice')
     nx.draw_networkx_edge_labels(self, graph_list_pos, edge_labels=edge_labels, font_size=4)
     nx.draw(self, graph_list_pos, with_labels=True, node_size=150, font_size=8)
     plt.savefig('SOP/' + graph_name + '.png', dpi=1000, bbox_inches='tight', pad_inches=0, transparent=True)
     plt.clf()
Esempio n. 23
0
def graficarAST(raiz):

    file = open("astPL.dot", "w")
    file.write(
        'digraph G {\n' + 'rankdir=TB; ' +
        'node[fillcolor=\"darkturquoise:darkslategray2\", shape=record ,fontname = \"Berlin Sans FB\" ,style = filled]  \n'
        + 'edge[arrowhead=none]; \n')
    file.write(recorrerNodos(raiz))
    file.write('}\n')
    file.close()
    render('dot', 'svg', 'astPL.dot')
def graphDrawGen(graph_list):
    for graphList in graph_list:
        for key, value in graphList.graph.items():
            graphName = value
            print(graphName)
        write_dot(graphList, 'SOP/' + graphName + '.gv')
        render('dot', 'png', 'SOP/' + graphName + '.gv')
        graphListPos = nx.nx_pydot.pydot_layout(graphList, prog='dot')
        nx.draw(graphList, graphListPos, with_labels=True)
        plt.savefig('SOP/' + graphName + '.png', dpi=1000)
        plt.clf()
        cyclomaticNumber(graphList)
Esempio n. 25
0
 def __str__(self) -> str:
     from anytree.dotexport import DotExporter
     from graphviz import render
     DotExporter(
         self.rootNode,
         nodenamefunc=lambda node: node.node_value,
         nodeattrfunc=lambda node: "style = filled, fillcolor = red"
         if node.depth % 2 == 0 else "style = filled, fillcolor = blue",
         edgeattrfunc=lambda node, child: "label =" + str(
             node.evaluator_value)).to_dotfile("test.dot")
     render("dot", "png", "test.dot")
     return "The graph has been rendered"
Esempio n. 26
0
File: neural.py Progetto: jrbr/cscs
def draw_network(g, layers, inLay, numInputs, numOutputs):
    print "drawing network"
    plt.subplot(121)
    layout = grid_layout(g, layers, inLay, numInputs, numOutputs)

    edge_labels = dict([((
        u,
        v,
    ), d['weight']) for u, v, d in net.edges(data=True)])

    write_dot(g, "file.gv")
    gv.render('dot', 'png', 'file.gv')
Esempio n. 27
0
    def dot_to_png(self, temp_input, filename_output):
        """ Convert the dot file to png file """
        # method using the render from graphviz module
        render('dot', 'png', temp_input)

        # remove the file if already exist
        try:
            remove(filename_output)
        except OSError:
            pass
        rename(temp_input + '.png', filename_output)
        remove(temp_input)
Esempio n. 28
0
def _get_data():
    data = request.get_json()
    pprint.pprint(data)
    formula_text = (diagram_functions.latex2text(data.get("formula")))
    file_path_self_generated = diagram_functions.text2bddExpr(formula_text)
    file_path_getted = diagram_functions.get_dot_from_json(data, "json_from_server")
    render("dot", "png", file_path_getted)
    # print(file_path_self_generated)
    # print(file_path_getted)
    answer = diagram_functions.dot_files_comparator(file_path_getted, file_path_self_generated)
    print(answer)
    respond = jsonify(answer=answer)
    return respond
Esempio n. 29
0
def simple_net(important_vars,
               important_features,
               file,
               var_list=None,
               mode_list=None,
               dir='TB'):
    file = file if file.endswith('.gv') else (file + '.gv')
    dot_bg = ['digraph G {\nrankdir = ' + dir + ';\nsubgraph {']
    dot_ed = ['} /* closing subgraph */\n}']
    nodes = []
    edges = []

    features = set()
    rank0 = '{rank = same;'
    for mode in important_features:
        mode_name = 'm{}'.format(
            mode) if mode_list is None else mode_list[mode]
        rank0 += mode_name + ';'
        nodes.append('{} [label=\"{}\", shape=box]'.format(
            mode_name, mode_name))  # mode nodes
        for fea in important_features[mode]:
            features.add(fea)
            edges.append('fe{} -> {}'.format(fea,
                                             mode_name))  # feature to mode
    rank0 += '}'

    vars = set()
    rank1 = '{rank = same;'
    for fea in features:
        nodes.append('fe{} [label=\"fe{}\", shape=ellipse]'.format(
            fea, fea))  # feature nodes
        rank1 += 'fe{};'.format(fea)
        for v in important_vars[fea]:
            var_name = 'v{}'.format(v) if var_list is None else var_list[v]
            vars.add(v)
            edges.append('{} -> fe{}'.format(var_name,
                                             fea))  # variable to feature
    rank1 += '}'

    rank2 = '{rank = same;'
    for v in vars:
        var_name = 'v{}'.format(v) if var_list is None else var_list[v]
        nodes.append('{} [label=\"{}\", shape=ellipse]'.format(
            var_name, var_name))  # var nodes
        rank2 += (var_name + ';')
    rank2 += '}'
    dot_file = dot_bg + nodes + edges + [rank0, rank1, rank2] + dot_ed
    with open(file, 'w') as f:
        f.write('\n'.join(dot_file))
    render('dot', 'svg', file)
Esempio n. 30
0
def graficarAST():
    ast = """digraph {
        A [label="King Arthur"]
        B [label="Sir Bedevere the Wise"]
        L [label="Sir Lancelot the Brave"]
        A -> B
        A -> L
        B -> L [constraint=false]
    }
    """
    with open("C:\\Users\\Jossie Castrillo\\Desktop\\ast1.dot", "w") as f:
        f.write(ast)
        f.closed
    t.render('dot', 'png', 'C:\\Users\\Jossie Castrillo\\Desktop\\ast1.dot')
def plot_graph_of_decision_classifier(model, X, y):
    """
    Stores the Decision Classifier Tree in a graph and plots a barchart of the feature_importances

    :param model: Fitted decision Classifier instance
    :param X: Feature matrix
    :param y: labels

    Folder:     Report/
    Plot name:  decision_tree_graph.pdf

    """
    print('Plotting Decision Tree...')

    params_decision_tree = {"max_depth": 2, "class_weight": 'balanced'}
    model.set_params(**params_decision_tree)
    model.fit(X, y)

    sorted_importances = sorted(model.feature_importances_, reverse=True)
    sorted_feature_names = [
        x for _, x in sorted(zip(model.feature_importances_,
                                 f_factory.feature_names),
                             reverse=True)
    ]

    hp.plot_barchart('Feature importances with Decision Tree Classifier',
                     'Feature', 'Importance', sorted_feature_names,
                     sorted_importances, 'Importance',
                     'feature_importances.pdf')

    tree.export_graphviz(
        model,
        out_file='decision_tree_graph',
        feature_names=f_factory.feature_names,
        class_names=['no crash', 'crash'],
        filled=True,
        rounded=True,
        proportion=True,
        special_characters=True,
    )

    graphviz.render('dot', 'pdf', 'decision_tree_graph')

    os.remove(sd.working_directory_path + '/decision_tree_graph')
    if not os.path.exists(sd.working_directory_path + '/Plots/Report/'):
        os.makedirs(sd.working_directory_path + '/Plots/Report/')

    os.rename(
        sd.working_directory_path + '/decision_tree_graph.pdf',
        sd.working_directory_path + '/Plots/Report/decision_tree_graph.pdf')
Esempio n. 32
0
def showGraph(solution, layout='twopi'):
  gv = graph(solution)
  gv.render(filename='/tmp/graph.gv')
  call([layout, '-Tsvg', '/tmp/graph.gv', '-o', '/tmp/graph.svg'])
  call(['eog', '/tmp/graph.svg'])