def draw(self): string = """digraph G{ label = """ + '"' + '' + '"' + """ rankdir = LR; node [shape = circle]; node [shape = doublecircle]; """ s = [self.init_state] edge_set = set() for e in self.final_states: string = string + ' ' + "\""+e.name+"\"" string += ';\nnode [shape = circle];\n' string += "\""+self.init_state.name+"\"[fillcolor=gray, style=filled];" alphabet = self.alphabet if 'ε' in self.alphabet else self.alphabet + ['ε'] while len(s) != 0: state = s.pop() for c in alphabet: if len(self.table[state][c]) != 0 and (state, c) not in edge_set: edge_set.add((state, c)) for des in self.table[state][c]: if c != 'ε': string = string + '\n'+'"'+state.name+'"'+' -> '+'"'+des.name+'"'+' [label = "' + c + '"];' else: string = string + '\n'+'"'+state.name+'"'+' -> '+'"'+des.name+'"'+' [label = "' + 'ε' + '"];' s.extend(list(self.table[state][c])) string += '}' s = Source(string, filename="nfa.gv", format="png") s.render()
def generate_buchi(formula: LTL, file_path: str): # if platform.system() != "Linux": # print(platform.system() + " is not supported for buchi generation") # return try: dot_file_path = os.path.dirname(file_path) if dot_file_path == "": file_path = results_folder + file_path print(formula) b_formula, new_vars, old_vars = traslate_boolean(formula.formula) print(b_formula) result = subprocess.check_output( ["ltl2tgba", "-B", b_formula, "-d"], encoding='UTF-8', stderr=subprocess.DEVNULL).splitlines() result = [x for x in result if not ('[Büchi]' in x)] result = "".join(result) dot_file_path = os.path.dirname(file_path) dot_file_name = os.path.splitext(file_path)[0] save_to_file(result, dot_file_name + ".dot") src = Source(result, directory=dot_file_path, filename=dot_file_name, format="eps") src.render(cleanup=True) print(dot_file_name + ".eps -> buchi generated") except Exception as e: raise e
def graficar(self): self.grafo = "digraph G {\n" + "graph [rankdir = TB];\n" + "node [shape = record,height=.1]; {\n" if self.estaVacia() == True: self.grafo += "\"ListaVacia\" [label = \"Lista Vacia\"]" else: temp = self.inicio i = 0 while temp != None: self.grafo += "\"" + str(i) + "\" [label = \"" + str( temp.getDia()) + "\"];\n" if i > 0: self.grafo += "\"" + str(i - 1) + "\" -> \"" + str( i) + "\" ;\n" self.grafo += "\"" + str(i) + "\" -> \"" + str( i - 1) + "\" ;\n" temp = temp.siguiente i = i + 1 self.grafo += "} labelloc=\"t\"; label=\" LISTA DOBLE DIAS\";}" print(self.grafo) src = Source(self.grafo) src.format = "png" src.render('test-output/ListaDobleUsuarios', view=True)
def __show_graph__(name='complete_graph', fit=False): try: from graphviz import Source except ImportError: print('Oops! graphviz is not available.') raise file = open(log_path + '/monitor/' + name + '.dot', 'r') text = file.read() if fit: try: # Convert to png and show full picture filename = log_path + '/monitor/' + name extension = 'png' import os if os.path.exists(filename + '.' + extension): os.remove(filename + '.' + extension) s = Source(text, filename=filename, format=extension) s.render() from IPython.display import Image image = Image(filename=filename + '.' + extension) return image except: print('Oops! Failed rendering the graph.') raise else: return Source(text)
def grafo_pda(gramaticas): gramatica = seleccionar("", "las Gramaticas ", gramaticas) dott = """digraph { graph [rankdir=LR] i [label=i shape=circle style=filled fillcolor=skyblue] p [label=p shape=circle style=filled fillcolor=skyblue] q [label=q height=1 shape=circle width = 1 style=filled fillcolor=skyblue] f [label=f shape=doublecircle style=filled fillcolor=skyblue]""" etq = label_grafo(gramatica) dott += etq etq1 = llenar_transformaciones(gramatica) etq2 = llenar_ter(gramatica.sim_terminales) dott += 'i -> p [label ="$ , $ ; #"]' dott += 'p -> q [label="$ , $ ; ' + gramatica.state_inicial + '"]' dott += 'q:s -> q:s [label="' + etq2 + '"]' dott += 'q:n -> q:n [label="' + etq1 + '"]' dott += 'q -> f [label="$ , # , $"]}' nom = 'AP_' + gramatica.nombre src = Source(dott) src.render("Templates/" + nom, format='png') print() print("=========================================") print(" AUTOMATA GENERADO EXITOSAMENTE ") print("=========================================") print() generar_pda(nom)
def draw(self): string = """digraph G{ label = """ + '"' + '' + '"' + """ rankdir = LR; node [shape = circle]; node [shape = doublecircle]; """ s = [self.init_state] edge_set = set() for e in self.final_states: string = string + ' ' + '"' + e.name + '"' string += ';\nnode [shape = circle];\n' string += '"' + self.init_state.name + '"' + "[fillcolor=gray, style=filled];" while len(s) != 0: state = s.pop() for c in self.alphabet: if self.table[state][c] is not None and (state, c) not in edge_set: edge_set.add((state, c)) string = string + '\n' + '"' + state.name + '"' + ' -> ' + '"' + self.table[ state][c].name + '"' + ' [label = "' + c + '"];' s.append(self.table[state][c]) string += '}' s = Source(string, filename="dfa.gv", format="png") s.render()
def decision_tree_id3(filename: str, concept_attribute_name: str): # process the csv file, load to pandas dataframe dataframe = pd.read_csv(filename, na_values=["."]) # get all attribute columns except the target concept column name attribute_names = [ name for name in dataframe.columns.tolist() if name != concept_attribute_name ] # initialize the tree nodes array tree_nodes = [] # begin algorithm build_decision_tree_id3(tree_nodes, dataframe, concept_attribute_name, attribute_names, None, None) # initialize the node description node_des = node_links = "" # print the tree for node in tree_nodes: node_des += node.describe_node() node_links += node.describe_link() print(repr(node_des + node_links)) # tree graph src = Source('digraph Tree {' + node_des + node_links + '}') src.render('decision_tree.gv', view=True) input("Press enter to continue")
def __show_graph__(name='complete_graph', fit=False): # type: (str, bool) -> ... """ Show graph. :param name: Graph to show (default: 'complete_graph') :param fit: Fit to width [ True | False ] (default: False) :return: None """ try: from graphviz import Source # noqa except ImportError: print('Oops! graphviz is not available.') return None monitor_file = open(LOG_PATH + '/monitor/' + name + '.dot', 'r') text = monitor_file.read() monitor_file.close() if fit: try: # Convert to png and show full picture filename = LOG_PATH + '/monitor/' + name extension = 'png' import os if os.path.exists(filename + '.' + extension): os.remove(filename + '.' + extension) s = Source(text, filename=filename, format=extension) s.render() from IPython.display import Image # noqa image = Image(filename=filename + '.' + extension) return image except Exception: print('Oops! Failed rendering the graph.') raise else: return Source(text)
def mqtt_on_message(client, userdata, msg): now = datetime.now() now_text = now.strftime("%Y.%m.%d %Hh%M") log.info("mqtt> message") topics = msg.topic.split('/') if (len(topics) == 4 and topics[3] == "graphviz"): server_name = topics[0] log.info(f"graph received for '{server_name}'") #'dot', 'neato', 'circo', 'sfdp' if (topics[0] == 'mzig'): engine_name = "fdp" elif (topics[0] == 'hzig'): engine_name = "dot" elif (topics[0] == 'lzig'): engine_name = "circo" else: print(f"unexpected server name : {topics[0]}") engine_name = "dot" graph_text = msg.payload.decode() graph_text.replace( "Custom devices (DiY) [CC2530 router](http://ptvo.info/cc2530-based-zigbee-coordinator-and-router-112/) (CC2530.ROUTER)", "CC2530.CC2591.ROUTER") g = Source(graph_text, format='svg', engine=engine_name) g.render("graphs\\" + now_text + " " + server_name + " " + engine_name + ".dot", view=True) if (topics[0] == 'lzig'): sys.exit(0) return
def graphviz(self, root, filename): filename = filename or 'tree_2.dot' out = 'digraph g { graph [ rankdir = "LR"];node [fontsize = "16" shape = "ellipse"]; edge [];' nodes = [] edges = [] self.graphviz_dfs(root, nodes, edges) for i in range(len(nodes)): node = nodes[i] node_text = node['name'] + '[' + 'label=' + node['label'] + ' shape = ' + node['shape'] + '];' out = out + node_text for i in range(len(edges)): edge = edges[i] # edge_text = str(edge['id_from']) + ':f0 -> ' + str(edge['id_to']) + ':f0 [ id = ' + str(edge['id']) + ' label = "' + edge['strategy'] + '"];' edge_text = str(edge['id_from']) + ':f0 -> ' + str(edge['id_to']) + ':f0 [ id = ' + str(edge['id']) + ' label = "' + 'strategy' + '"];' out = out + edge_text out = out + '}' #write into:t file # with open(arguments.data_directory + 'Dot/' + filename, 'wb') as fout: # fout.write(str(out)) #mjb src = Source(out) # src.view() #run graphviz program to generate image src.render('dot ' + arguments.data_directory + filename , view=True)
def to_graphviz(self, outfilename: str = None) -> Source: if not self.states: tpl = "digraph L{{label=\"{name}\"; node [shape=record]; a [label=\"empty\"]}}" res = tpl.format(name=self.name) else: res = """digraph finite_state_machine { rankdir=LR; size=\"8,5\"""" res += " label=\"{}\"".format(self.name) if self.acceptstates: accept = " ".join( map(lambda x: '"' + x + '"', self.acceptstates)) res += " node [shape = doublecircle]; {};\n".format(accept) res += " node [shape = circle];\n" res += " __I__ [label=\"\", style=invis, width=0]\n" res += " __I__ -> \"{}\"\n".format(self.initial) for (s, a, d) in self.transitions: sym = a if a != EPSILON else "ε" res += " \"{s}\" -> \"{d}\" [label = {a}];\n".format(s=s, d=d, a=sym) res += "}" output = Source(res) if outfilename: output.render(outfilename) return output
def draw(self, ab_th, rel_th, optionarrow): d_graph = Digraph(name=self.graph_name) d_graph.graph_attr.update(newrank="true") for sub in self.subgraphs: d_graph.subgraph(sub.create_graph(ab_th, rel_th)) edges = set() for key, val in self.algo_res.items(): if type(key) == tuple: for idx,k in enumerate(key): for idx2 in range(idx+1,len(key)): edges.add((k, key[idx2])) else: d_graph.node(key, style = "filled") already_seen = [] for e in edges: if(not optionarrow): if([e[1], e[0]] not in already_seen): d_graph.edge(e[0], e[1], color = "red", style = "dashed", arrowhead= "none") already_seen.append([e[0], e[1]]) else: d_graph.edge(e[0], e[1], color = "red", style = "dashed") d_graph.node(e[0], style = "filled") d_graph.node(e[1], style = "filled") testi=d_graph.source[:-1] samerank = "{rank=same;"+" ".join(["\"start_"+x.logname+"\";" for x in self.subgraphs])+"}" testi+=samerank+"\n}"; src = Source(testi) src.render(self.name, format='pdf', cleanup=False) #option cleanup: keep dot file
def printGraphWithPath(self, topicpath, modulename): graphstr = "digraph { \n" graphstr += "bgcolor=transparent \n" graphstr += "node [style=rounded shape=box]\n" for node_name in self.nodes: node_label = self.labels[self.nodes.index(node_name)] if node_name in topicpath: graphstr += node_name + ' [label=<' + node_label + '> URL="' + node_name + '.html" target="_top" penwidth=3 color=blue];\n' else: graphstr += node_name + ' [label=<' + node_label + '> URL="' + node_name + '.html" target="_top"];\n' # And the connections for j in range(0, len(self.nodes)): for k in range(0, len(self.nodes)): if self.graph[j, k] == 1: if (self.nodes[j] in topicpath) & (self.nodes[k] in topicpath): graphstr += self.nodes[j] + " -> " + self.nodes[ k] + ' [penwidth=3 color=blue];\n' else: graphstr += self.nodes[j] + " -> " + self.nodes[ k] + '\n' graphstr += "}" src = Source(graphstr, format='svg') src.render("html/" + modulename) # Delete the dot file os.remove("html/" + modulename)
def main(): """ Draws the topology of the SCION network in a gen folder. example: python scion_topology_graph -g "gen", -e, -n: will place a pdf file of the scion topology with edge and node labels into output/scion_topo.gv -g: path to the gen folder ex: SCION/gen -e: set this flag if edge labels should be drawn -n: set this flag if node labels should be drawn -o: path to the output file ex: output/scion_topo.gv """ parser = argparse.ArgumentParser() parser.add_argument('-g', '--gen_folder_path', default="gen", help='path to the gen folder') parser.add_argument('-e', '--edge_labels', action='store_true', default=False, help='set this flag if you want edge labels') parser.add_argument('-n', '--node_labels', action='store_true', default=False, help='set this flag if you want node labels') parser.add_argument('-o', '--output_path', default="output/scion_topo.gv", help='path to the output topology file') args = parser.parse_args() topo = parse_gen_folder(args.gen_folder_path) dot = draw_SCION_topology(topo, args.node_labels, args.edge_labels) s = Source(dot, filename=dot.filename, format="pdf") s.render(directory=args.output_path)
def grafo_pda_recorrido(gramatica, iteraciones): for iteracion in iteraciones: if iteracion.transicion == "f": dott = definir_estado("f", gramatica.state_inicial, iteracion, len(iteraciones)) else: dott = definir_estado(iteracion.id, gramatica.state_inicial, iteracion, len(iteraciones)) ter = colorear_terminos(gramatica.sim_terminales, iteracion) noter = colorear_noterminales(gramatica, iteracion) dott += "q:s -> q:s [label=<<table BORDER='0' CELLBORDER='0' CELLSPACING='0'>" + ter + "</table>>]" dott += "q:n -> q:n [label=<<table BORDER='0' CELLBORDER='0' CELLSPACING='0'>" + noter + "</table>>]}" if iteracion.id != "#" and iteracion.id != "&": nom = "Templates/imagen" + iteracion.id src = Source(dott) src.render(nom, format='png') print() print("=============================================") print(" REPORTE DE RECORRIDO GENERADO EXITOSAMENTE ") print("=============================================") print() reportar_recorrido(gramatica.nombre, iteraciones)
def generate_ast_tree(dot: str, errors): file_used_by_another = True i = 0 error_file_used_by_another_part_one = "Command '['dot', '-Tpdf', '-O', 'AST_Report_" + str( i) + "']' " error_file_used_by_another_part_two = "returned non-zero exit status 1. " error_file_used_by_another_part_three = "[stderr: b'Error: Could not open \"AST_Report_" + str( i) + ".pdf\" for writing : Permission denied\\r\\n']" error_file_used_by_another = error_file_used_by_another_part_one + error_file_used_by_another_part_two + error_file_used_by_another_part_three while file_used_by_another == True: error_file_used_by_another_part_one = "Command '['dot', '-Tpdf', '-O', 'AST_Report_" + str( i) + "']' " error_file_used_by_another_part_three = "[stderr: b'Error: Could not open \"AST_Report_" + str( i) + ".pdf\" for writing : Permission denied\\r\\n']" error_file_used_by_another = error_file_used_by_another_part_one + error_file_used_by_another_part_two + error_file_used_by_another_part_three try: src = Source(dot) src.render('AST_Report_' + str(i), view=True) file_used_by_another = False except Exception as e: if str(e) == error_file_used_by_another: file_used_by_another = True i += 1 else: file_used_by_another = False errors.append( Error("Unknown", "AST graphic not generated", 0, 0)) print_error("Unknown Error", "AST graphic not generated")
def draw_graph(cwd): ui = GraphOptions() ui.edit() max_patchcount = 2 * ui.limit # changes = get_changes(cwd, None, ui.limit, author=Config.AUTHOR) from_upstream = get_changes_from_upstream(cwd, Config.UPSTREAM_REPO, None, max_patchcount) changes = get_changes(cwd, None, max_patchcount) # print('format picked: {}'.format(ui.format)) dotSrcLines = darcs_show(cwd, ui.limit, ui.filename).splitlines() def changeColor(i, color): dotSrcLines[i] = dotSrcLines[i][:-2] + 'color="{}"];'.format(color) for i, l in enumerate(dotSrcLines): m = PATCH_PATTERN.search(l) if not m: continue title = m.group(1).replace("\\n", " ").strip() print(title) def find_in(lst): try: return next(c for c in lst if title == c.title) except StopIteration: return None up = find_in(from_upstream) # type: Patch loc = find_in(changes) # type: Patch if up: if not loc: print("patch in upstream but not local?? {}".format(title)) if up.author == Config.AUTHOR: changeColor(i, ui.acolor) else: changeColor(i, ui.bcolor) elif loc: if loc.author == Config.AUTHOR: changeColor(i, ui.color) dotSrc = "\n".join(dotSrcLines) print(dotSrc) # for l in enumerate(dotSrc.splitlines()): # print("{}: {}".format(*l)) # dot = parse_dot_data(dotSrc) # print(dot) dot = Source(dotSrc) # # print(dotObj.source) # # dot.graph_attr['rankdir'] = 'LR' dot.format = ui.format dot.render(ui.filename, view=ui.open, cleanup=ui.cleanup)
def render_system_with_graphviz(system, output_file="system_view.gz"): ''' Renders the Drake system (presumably a diagram, otherwise this graph will be fairly trivial) using graphviz to a specified file. ''' from graphviz import Source string = system.GetGraphvizString() src = Source(string) src.render(output_file, view=False)
def dibujarGrafoD(automata, filename): nombre = "" directorio = "Archivos/static" grafo = Source(automata.codigoDot(), filename=filename, directory=directorio, format='png') grafo.render('%s' % (nombre + filename), view=False)
def cargar1(self): archivo_entrada = filedialog.askopenfilename( initialdir="C:/Users/jezeh/OneDrive/Escritorio/IPC2/Proyecto2_ipc2", title="Selecciona un archivo", filetypes=(("xml files", "*.xml"), ("xml files", "*.*"))) archivo = ET.parse(archivo_entrada) root = archivo.getroot() for element in root: contador = 0 for subelement in element: if contador == 0: self.name1 = subelement.text contador = contador + 1 elif contador == 1: self.row1 = subelement.text contador = contador + 1 elif contador == 2: self.colum1 = subelement.text contador = contador + 1 elif contador == 3: ima1 = subelement.text x = 1 y = 0 contadorES = 0 contadorAS = 0 for i in ima1: if i == " ": continue elif i == "\n": y = y + 1 x = 1 else: if i == "-": contadorES = contadorES + 1 elif i == "*": contadorAS = contadorAS + 1 self.m.insertar(y, x, i) x = x + 1 contador = 0 Hora = self.hora() self.matris.insertar(self.fecha, Hora, self.name1, contadorES, contadorAS) a = self.m.cadena_grap() s = Source(a, filename="original.gv", format="png") s.render() self.img = ImageTk.PhotoImage( Image.open( "C:/Users/jezeh/OneDrive/Escritorio/IPC2/Proyecto2_ipc2/original.gv.png" )) self.lab1 = Label(self.frame2, image=self.img).grid(row=1, column=0, padx=10, pady=10, sticky="nsew") self.ventana_C.destroy()
def tracegraph(dot): g = Source(dot, "relations.gv", "dotout", "pdf", "neato") g.render(view=True) with open('dotout/relations.gv.pdf', 'rb') as pdf: response = HttpResponse(pdf.read()) response['content_type'] = 'application/pdf' response['Content-Disposition'] = 'attachment;filename=grafo.pdf' return response
def draw_algo2(self, ab_th, rel_th): d_graph = Digraph(name=self.name) d_graph.graph_attr.update(newrank="true") for sub in self.subgraphs: d_graph.subgraph(sub.create_graph(ab_th, rel_th)) edges = set() res = "" for key, val in self.algo_res.items(): if type(key) == tuple: if(key[0] != key[1]): for idx,k in enumerate(key): for idx2 in range(idx+1,len(key)): if(type(val) == float): d_graph.edge(key[idx], key[idx2], color = "red", style = "dashed", arrowhead = "none", xlabel = repr(round(val, 3))) d_graph.node(key[idx], style = "filled") d_graph.node(key[idx2], style = "filled") elif(type(val) == bool): if(val == True): d_graph.node(key[idx2], style = "filled") d_graph.node(key[idx], style = "filled") d_graph.edge(key[idx], key[idx2], color = "red", style = "dashed", arrowhead = "none") else: if(type(val[0]) == Event): d_graph.node(key[idx2], style = "filled") d_graph.node(key[idx], style = "filled") d_graph.edge(key[idx], key[idx2], color = "red", style = "dashed", arrowhead = "none") else: rules = str.join("\\n|| ",[str.join(" && ",[str.join("",[str(x[0])[:-1:]+" of " + (key[0] if int(str(x[0])[-1])==1 else key[1])]+ [str(y) for y in x[1::]]) for x in c]) for c in val]) d_graph.edge(key[idx], key[idx2], color = "red", style = "dashed", arrowhead = "none", xlabel=rules) d_graph.node(key[idx2], style = "filled") d_graph.node(key[idx], style = "filled") else: if(type(val) == float): d_graph.node(key[0], style = "filled", xlabel = repr(round(val, 3))) elif(type(val) == bool): if( val == True): d_graph.node(key[0], style = "filled") else: if(type(val[0]) == Event): d_graph.node(key[0], style = "filled") else: rules = str.join("\\n|| ",[str.join(" && ",[str.join("",[str(x[0])[:-1:]+" of " + ("start" if int(str(x[0])[-1])==1 else "complete")]+[str(y) for y in x[1::]]) for x in c]) for c in val]) d_graph.node(key[0], style = "filled", xlabel = rules) if(isinstance(key, str) and val): for v in val: if(type(v[0]) == int): res += " on " + str(v[1]) + " days " + str(v[0]) + " instances were started\n" elif(type(v[0]) == tuple and len(v[0]) == 2): res += "on " + str(v[1]) + " days " + str(v[0][0]) + " instances with <" + str(v[0][1]) + "> were started\n" else: res += "on " + str(v[1]) + " days " + str(v[0][0]) + " instances with <" + str(v[0][1]) + "> were started by <" + str(v[0][2]) +">\n" d_graph.attr(label = res) testi=d_graph.source[:-1] samerank = "{rank=same;"+" ".join(["\"start_"+x.logname+"\";" for x in self.subgraphs])+"}" testi+=samerank+"\n}"; src = Source(testi) src.render(self.name, format='pdf', cleanup=False) #option cleanup: keep dot file
def draw_decay_struct(decay_chain, show=False, **kwargs): from graphviz import Source a = DotGenerator.dot_chain(decay_chain) g = Source(a, **kwargs) if show: g.view() else: g.render()
def drawNumpy1DArray( self, array, showIndex=False, layout="row", ): maxLen = 0 for i in range(array.shape[0]): val = str(array[i]) if len(val) > maxLen: maxLen = len(val) size = 20 + 7 * maxLen if layout == "row": strArray = "<TR>" for i in range(array.shape[0]): strArray = strArray + '<TD border="1" fixedsize="true" width="' + str( size) + '" height="' + str(size) + '">' + str( array[i]) + '</TD>' strArray = strArray + '</TR>' if showIndex: strArray = strArray + "<TR>" for i in range(array.shape[0]): strArray = strArray + '<TD border="0" fixedsize="true" width="' + str( size) + '" height="' + str(size) + '">' + str( i) + '</TD>' strArray = strArray + '</TR>' elif layout == "column": strArray = "" for i in range(array.shape[0]): if not showIndex: strArray = strArray + '<TR><TD border="1" fixedsize="true" width="' + str( size) + '" height="' + str(size) + '">' + str( array[i]) + '</TD></TR>' else: strArray = strArray + '<TR><TD border="0" fixedsize="true" width="' + str( size ) + '" height="' + str(size) + '">' + str( i ) + '</TD><TD border="1" fixedsize="true" width="' + str( size) + '" height="' + str(size) + '">' + str( array[i]) + '</TD></TR>' if not self.animation: src = Source( 'graph "Array" { node [fontsize=15, shape=plaintext]; a0 [label=< <TABLE border="0" cellspacing="0" cellpadding="3">' + strArray + '</TABLE> >] }') src.render('lista.gv', view=True) display(SVG(src.pipe(format='svg'))) return None else: src = Source( 'graph "Array" { node [fontsize=15, shape=plaintext]; a0 [label=< <TABLE border="0" cellspacing="0" cellpadding="3">' + strArray + '</TABLE> >] }', format='png') return src
def cmdDot(self, show=True, filename=None, format='svg'): #png,pdf outf = filename if filename is not None else 'e%dg%do%d' % self.selected buf = StringIO() sa.print_dot(self.world, self.selectedOrg, buf) dot = buf.getvalue() if outf is not None: g = Source(dot, filename=outf, format=format) else: g = Source(dot, format=format) g.render(view=show) # NOTE: render appends extension
def generate_svg(self, token,graph): filename = os.path.join(SVG_CATALOGUE_PATH,token) graph_new = re.sub('dpi=\d*','dpi=0',graph) s = Source(graph_new, filename=filename, format="svg") s.render(filename=filename, format="svg") os.remove(filename) res = '' with open(filename+'.svg','r') as f: res = f.read() os.remove(filename+'.svg') return res
def expression_graph_as_png(expr, output_file, view=True): """ Save a PNG of rendered graph (graphviz) of the symbolic expression. :param expr: sympy expression :param output_file: string with .png extension :param view: set to True if system default PNG viewer should pop up :return: None """ assert output_file.endswith('.png') graph = Source(dotprint(expr)) graph.format = 'png' graph.render(output_file.rpartition('.png')[0], view=view, cleanup=True)
def csview(self, view=False): """View chemical shift values organized by amino acid residue. :param bool view: Open in default image viewer or save file in current working directory quietly. :return: None :rtype: None """ for starfile in nmrstarlib.read_files([self.from_path]): chains = starfile.chem_shifts_by_residue(self.aminoacids, self.atoms, self.nmrstarversion) for idx, chemshifts_dict in enumerate(chains): nodes = [] edges = [] for aminoacid in chemshifts_dict: aaname = '{}_{}'.format(aminoacid[1], aminoacid[0]) label = '"{{{}|{}}}"'.format(aminoacid[0], aminoacid[1]) color = 8 aanode_entry = " {} [label={}, fillcolor={}]".format( aaname, label, color) nodes.append(aanode_entry) currnodename = aaname for atomtype in chemshifts_dict[aminoacid]: atname = "{}_{}".format(aaname, atomtype) label = '"{{{}|{}}}"'.format( atomtype, chemshifts_dict[aminoacid][atomtype]) if atomtype.startswith("H"): color = 4 elif atomtype.startswith("C"): color = 6 elif atomtype.startswith("N"): color = 10 else: color = 8 atnode_entry = "{} [label={}, fillcolor={}]".format( atname, label, color) nextnodename = atname nodes.append(atnode_entry) edges.append("{} -> {}".format(currnodename, nextnodename)) currnodename = nextnodename if self.filename is None: filename = "{}_{}".format(starfile.bmrbid, idx) else: filename = "{}_{}".format(self.filename, idx) src = Source(self.dot_template.format("\n".join(nodes), "\n".join(edges)), format=self.csview_format) src.render(filename=filename, view=view)
def csview(self, view=False): """View chemical shift values organized by amino acid residue. :param view: Open in default image viewer or save file in current working directory quietly. :type view: :py:obj:`True` or :py:obj:`False` :return: None :rtype: :py:obj:`None` """ for starfile in fileio.read_files(self.from_path): chains = starfile.chem_shifts_by_residue(amino_acids=self.amino_acids, atoms=self.atoms, amino_acids_and_atoms=self.amino_acids_and_atoms, nmrstar_version=self.nmrstar_version) for idx, chemshifts_dict in enumerate(chains): nodes = [] edges = [] for seq_id in chemshifts_dict: aaname = "{}_{}".format(chemshifts_dict[seq_id]["AA3Code"], seq_id) label = '"{{{}|{}}}"'.format(seq_id, chemshifts_dict[seq_id]["AA3Code"]) color = 8 aanode_entry = " {} [label={}, fillcolor={}]".format(aaname, label, color) nodes.append(aanode_entry) currnodename = aaname for atom_type in chemshifts_dict[seq_id]: if atom_type in ["AA3Code", "Seq_ID"]: continue else: atname = "{}_{}".format(aaname, atom_type) label = '"{{{}|{}}}"'.format(atom_type, chemshifts_dict[seq_id][atom_type]) if atom_type.startswith("H"): color = 4 elif atom_type.startswith("C"): color = 6 elif atom_type.startswith("N"): color = 10 else: color = 8 atnode_entry = "{} [label={}, fillcolor={}]".format(atname, label, color) nextnodename = atname nodes.append(atnode_entry) edges.append("{} -> {}".format(currnodename, nextnodename)) currnodename = nextnodename if self.filename is None: filename = "{}_{}".format(starfile.id, idx) else: filename = "{}_{}".format(self.filename, idx) src = Source(self.dot_template.format("\n".join(nodes), "\n".join(edges)), format=self.csview_format) src.render(filename=filename, view=view)
def main(): """ Draws the topology of an example topology run """ topo = simulate_topology() topo_dict = [] for entry in topo: dict = entry.getdict() topo_dict.append(dict) print(topo_dict) dot = draw_topology(topo) s = Source(dot, filename=dot.filename, format="pdf") s.render(directory="output.gv")
def check_games_list(request): template = loader.get_template('games_list.html') triples = _sparql.check_games_list() if 'download_graph' in request.POST: g = Source(triples2dot(triples), "games_list.gv", "dotout", "pdf", "neato") g.render(view=True) with open('dotout/games_list.gv.pdf', 'rb') as pdf: response = HttpResponse(pdf.read()) response['content_type'] = 'application/pdf' response['Content-Disposition'] = 'attachment;filename=games_list.pdf' return response context = {'triples': triples} return HttpResponse(template.render(context, request))
def disassemble_sample_get_svg(sample_id, address): """ Gets SVG file data, with functions names. """ graph = disassemble_sample(sample_id, address) filename = Sample.query.get(sample_id).storage_file data = Source(graph, format='svg') out_file = filename + "_disass_" if address is not None: out_file += hex(address) out_file = data.render(out_file) beautify_svg(out_file) svg_data = open(out_file, 'rb').read() elements = re.findall("func_<!-- -->[0-9a-f]{3,}h", svg_data) for e in elements: et = e[13:-1] for i in Sample.query.get(sample_id).functions: if i.address == et: svg_data = svg_data.replace(e, i.name) elements = re.findall("loc_[0-9a-f]{3,}h", svg_data) for e in elements: et = e[4:-1] for i in Sample.query.get(sample_id).functions: if i.address == et: svg_data = svg_data.replace(e, i.name) return svg_data
def collate_xml(witness_a, witness_b): tokens_a = convert_xml_string_into_tokens(witness_a) tokens_b = convert_xml_string_into_tokens(witness_b) superwitness = align_tokens_and_return_superwitness(tokens_a, tokens_b) textgraph = convert_superwitness_to_textgraph(superwitness) dot_export = export_as_dot(textgraph, annotations=True) dot = Source(dot_export, format="svg") svg = dot.render() return display(SVG(svg))
def preview_dot(filename): from graphviz import Source with open(filename) as dot: src = Source(dot.read()) src.format = "png" outfile = src.render() with open(outfile, "rb") as content: data = content.read() return {"image/png": base64.b64encode(data).decode("ascii")}
def printChapterGraph(self,tlist,chapter): graphstr = "digraph { \n" graphstr += "bgcolor=transparent \n" graphstr += "node [style=rounded shape=box]\n" # Draw all nodes for inode in tlist : label = self.labels[self.nodes.index(inode)] graphstr += inode + ' [label=<' + label + '> URL="' + inode + '.html" target="_top"];\n' # Add the connections for inode in tlist : iind = self.nodes.index(inode) for jnode in tlist : jind = self.nodes.index(jnode) if self.graph[iind, jind] == 1 : graphstr += self.nodes[iind] + " -> " + self.nodes[jind] + '\n' # And finish printing the dot file graphstr += "}" src = Source( graphstr, format='svg' ) src.render("html/" + chapter) # Delete the dot file os.remove("html/" + chapter)
def collate_xml_svg(limit=1000): # convert XML files into tokens tokens1 = convert_xml_file_into_tokens("xml_source_transcriptions/ts-fol-test-small.xml") tokens2 = convert_xml_file_into_tokens("xml_source_transcriptions/tsq-test-small.xml") superwitness = align_tokens_and_return_superwitness(tokens1, tokens2) print(superwitness[0:20]) textgraph = convert_superwitness_to_textgraph(superwitness) dot_export = export_as_dot(textgraph, annotations=True, limit=limit) # print(dot_export) # render dot_export as SVG dot = Source(dot_export, format="svg") svg = dot.render() return display(SVG(svg))
def printFullGraph(self,filename): if self.set_conn == 0 : sys.error("graph must be set before print") graphstr = "digraph { \n" graphstr += "bgcolor=transparent \n" graphstr += "node [style=rounded shape=box]\n" for name in self.nodes : label = self.labels[ self.nodes.index(name) ] # Label here should be label from node file graphstr += name + ' [label=<' + label + '> URL="' + name + '.html" target="_top"];\n' # And the connections for i in range(0,len(self.nodes)): for j in range(0,len(self.nodes)): if self.graph[i,j] == 1 : graphstr += self.nodes[i] + " -> " + self.nodes[j] + '\n' # And finish printing the dot file graphstr += "}" src = Source( graphstr, format='svg' ) src.render("html/" + filename) # Delete the dot file os.remove("html/" + filename)
def printNodeGraph(self,node): label = self.labels[self.nodes.index(node)] graphstr = "digraph { \n" graphstr += "bgcolor=transparent \n" graphstr += "node [style=rounded shape=box]\n" # Write this node graphstr += node + ' [style="bold,rounded" color=blue label=<' + label + '> URL="' + node + '.html" target="_top"];\n' # Write nodes with forward and backwards connections i = self.nodes.index(node) forwardnodes = [] backnodes = [] for j in range(0,len(self.nodes)): if self.graph[ i, j ] == 1 : graphstr += self.nodes[j] + ' [label=<' + self.labels[j] + '> URL="' + self.nodes[j] + '.html" target="_top"];\n' graphstr += "edge[style=solid]; \n" graphstr += node + " -> " + self.nodes[j] + '\n' if (len(forwardnodes)>0) & (len(forwardnodes)%2==0) : graphstr += "edge[style=invis];\n" graphstr += forwardnodes[len(forwardnodes)-2] + " -> " + self.nodes[j] + '\n' forwardnodes.append(self.nodes[j]) if self.graph[ j, i ] == 1 : graphstr += self.nodes[j] + ' [label=<' + self.labels[j] + '> URL="' + self.nodes[j] + '.html" target="_top"];\n' graphstr += "edge[style=solid]; \n" graphstr += self.nodes[j] + " -> " + node + '\n' if (len(backnodes)>0) & (len(backnodes)%2==0) : graphstr += "edge[style=invis];\n" graphstr += backnodes[len(backnodes)-2] + " -> " + self.nodes[j] + '\n' backnodes.append(self.nodes[j]) for i in range(0,math.floor(len(forwardnodes)/2)+1) : if len(forwardnodes)>2*i+2 : graphstr += "{ rank=same; " + forwardnodes[2*i] + ";" + forwardnodes[2*i+1] + "; } \n" for i in range(0,math.floor(len(backnodes)/2)+1) : if len(backnodes)>2*i+2 : graphstr += "{ rank=same; " + backnodes[2*i] + ";" + backnodes[2*i+1] + "; } \n" graphstr += "}" src = Source( graphstr, format='svg' ) src.render("html/" + node) # Delete the dot file os.remove("html/" + node)
def main(): """ Draws the topology of the SCION network in a gen folder. example: python scion_topology_graph -g "gen", -e, -n: will place a pdf file of the scion topology with edge and node labels into output/scion_topo.gv -g: path to the gen folder ex: SCION/gen -n: set this flag if address/port information should be drawn -l: set this flag if location labels should be drawn -o: path to the output file ex: output/scion_topo.gv """ parser = argparse.ArgumentParser() parser.add_argument('-gp', '--gen_folder_path', default="gen", help='path to the gen folder') parser.add_argument('-lp', '--label_file_path', default="", help='path to the gen folder') parser.add_argument('-n', '--node_labels', action='store_true', default=False, help='set this flag to add address/port information') parser.add_argument('-l', '--location_labels', action='store_true', default=False, help='set this flag if add location labels') parser.add_argument('-o', '--output_path', default="output/scion_topo.gv", help='path to the output topology file') args = parser.parse_args() if os.path.exists(args.gen_folder_path): topo = parse_gen_folder(args.gen_folder_path, args.output_path) else: print('Error: No gen folder found at ' + args.gen_folder_path) return if args.location_labels: labels = parse_desc_labels(args.label_file_path) else: labels = {} dot = draw_SCION_topology(topo, args.node_labels, args.location_labels, labels) s = Source(dot, filename=dot.filename, format="pdf") s.render(directory=args.output_path)
def printGraphWithPath(self,topicpath,modulename): graphstr = "digraph { \n" graphstr += "bgcolor=transparent \n" graphstr += "node [style=rounded shape=box]\n" for node_name in self.nodes : node_label = self.labels[self.nodes.index(node_name)] if node_name in topicpath : graphstr += node_name + ' [label=<' + node_label + '> URL="' + node_name + '.html" target="_top" penwidth=3 color=blue];\n' else : graphstr += node_name + ' [label=<' + node_label + '> URL="' + node_name + '.html" target="_top"];\n' # And the connections for j in range(0,len(self.nodes)): for k in range(0,len(self.nodes)): if self.graph[j,k] == 1 : if (self.nodes[j] in topicpath) & (self.nodes[k] in topicpath) : graphstr += self.nodes[j] + " -> " + self.nodes[k] + ' [penwidth=3 color=blue];\n' else : graphstr += self.nodes[j] + " -> " + self.nodes[k] + '\n' graphstr += "}" src = Source( graphstr, format='svg' ) src.render("html/" + modulename) # Delete the dot file os.remove("html/" + modulename)
def write_graph(fields, containments, nests, matched_references, clusters): # Start a digraph graph = "digraph UML {\n" # Set the image's size, in inches graph += "size= \"33,33\";\n" # Add a title graph += "labelloc=\"t\";\n" graph += "label=<<FONT POINT-SIZE=\"45\">GA4GH Schema Diagram</FONT>>;\n" # Define node properties: shaped like UML items. graph += "node [\n" graph += "\tshape=plaintext\n" graph += "]\n\n" # Draw each node/type/record as a table for type_name, field_list in fields.items(): graph += "{} [label=<\n".format(type_name) graph += "<TABLE BORDER='0' CELLBORDER='1' CELLSPACING='0' CELLPADDING='4' bgcolor='#002060' color='#002060'>\n" graph += "\t<TR>\n" graph += "\t\t<TD COLSPAN='2' bgcolor='#79A6FF' border='3'><FONT POINT-SIZE='20' color='white'>{}</FONT>".format(type_name) graph += "</TD>\n" graph += "\t</TR>\n" # Now draw the rows of fields for the type. A field_list of # [a, b, c, d, e, f, g] will have [a, e] in row 1, [b, f] in # row 2, [c, g] in row 3, and just [d] in row 4 num_fields = len(field_list) for i in range(0, num_fields//2 + num_fields%2): # Draw one row. graph += "\t<TR>\n" # Port number and displayed text will be the i'th field's # name graph += "\t\t<TD align='left' port='{}'><FONT color='white'>- {}</FONT></TD>\n".format(field_list[i][0], field_list[i][0]) if (num_fields%2) == 1 and (i == num_fields//2 + num_fields%2 - 1): # Don't draw the second cell in the row if you have an # odd number of fields and it is the last row pass else: graph += "\t\t<TD align='left' port='{}'><FONT color='white'>- {}</FONT></TD>\n".format(field_list[num_fields//2 + num_fields%2 + i][0], field_list[num_fields//2 + num_fields%2 + i][0]) graph += "\t</TR>\n" # Finish the table graph += "</TABLE>>];\n\n" # Now define the clusters/subgraphs for cluster_name, cluster_types in clusters.items(): graph += "subgraph cluster_{} {{\n".format(cluster_name.replace(".", "_").replace("/", "_")) graph += "\tstyle=\"rounded, filled\";\n" graph += "\tcolor=lightgrey;\n" graph += "\tnode [style=filled,color=white];\n" graph += "\tlabel = \"{}\";\n".format(cluster_name.replace(".", "_")) # After all the cluster formatting, define the cluster types for cluster_type in cluster_types: # cluster_type should match up with a type_name from fields graph += "\t{};\n".format(cluster_type) graph += "}\n\n" # Define edge properties for containments graph += "edge [\n" graph += "\tdir=both\n" graph += "\tarrowtail=odiamond\n" graph += "\tarrowhead=none\n" graph += "\tcolor=\"#C55A11\"\n" graph += "\tpenwidth=2\n" graph += "]\n\n" for container, containee, container_field_name in containments: # Now do the containment edges # Only write the edge if the containee is a top-level field in fields. if containee in fields: graph += "{}:{}:w -> {}\n".format(container, container_field_name, containee) # Define edge properties for references graph += "\nedge [\n" graph += "\tdir=both\n" graph += "\tarrowtail=none\n" graph += "\tarrowhead=vee\n" graph += "\tstyle=dashed\n" graph += "\tcolor=\"darkgreen\"\n" graph += "\tpenwidth=2\n" graph += "]\n\n" for referencer, referencer_field, referencee in matched_references: # Now do the reference edges graph += "{}:{}:w -> {}:id:w\n".format(referencer, referencer_field, referencee) # Close the digraph off. graph += "}\n" graph = graph.replace("\n", " ").replace("\t", " ") src = Source(graph, format='svg') src.render('_build/generated_images/schema_uml')
# print("Example %d: label %s features %s" % (i, IRIS.target[i], IRIS.data[i])) # Build the classifier test_cohort = [0, 50, 100] train_target = numpy.delete(IRIS.target, test_cohort) train_data = numpy.delete(IRIS.data, test_cohort, axis=0) test_target = IRIS.target[test_cohort] test_data = IRIS.data[test_cohort] clf = tree.DecisionTreeClassifier().fit(train_data, train_target) # Print the expected labels and the predicted labels print(test_target) print(clf.predict(test_data)) # Generate a dot file and PDF dot_data = StringIO() tree.export_graphviz(clf, out_file=dot_data, feature_names=IRIS.feature_names, class_names=IRIS.target_names, filled=True, rounded=True, special_characters=True) src = Source(dot_data.getvalue()) src.render(filename='2-tree_viz.gv') # Print a sample data point print(test_data[0], test_target[0]) # Print the structure of the data print(IRIS.feature_names, IRIS.target_names)
def learnDiscreteBN(df, continous_columns, features_column_names, label_column='cat', draw_network=False): features_df = df.copy() features_df = features_df.drop(label_column, axis=1) labels_df = DataFrame() labels_df[label_column] = df[label_column].copy() for i in continous_columns: bins = np.arange((min(features_df[i])), (max(features_df[i])), ((max(features_df[i]) - min(features_df[i])) / 5.0)) features_df[i] = pandas.np.digitize(features_df[i], bins=bins) data = [] for index, row in features_df.iterrows(): dict = {} for i in features_column_names: dict[i] = row[i] dict[label_column] = labels_df[label_column][index] data.append(dict) print "Init done" learner = PGMLearner() test = learner.discrete_estimatebn(data=data, pvalparam=0.05, indegree=1) # print test.__dict__ f = open('heart_structure.txt', 'w') s = str(test.__dict__) f.write(s) f.flush() f.close() print "done learning" edges = test.E vertices = test.V probas = test.Vdata # print probas dot_string = 'digraph BN{\n' dot_string += 'node[fontname="Arial"];\n' dataframes = {} print "save data" for vertice in vertices: print "New vertice: " + str(vertice) dataframe = DataFrame() pp = pprint.PrettyPrinter(indent=4) # pp.pprint(probas[vertice]) dot_string += vertice.replace(" ", "_") + ' [label="' + vertice + '\n' + '" ]; \n' if len(probas[vertice]['parents']) == 0: dataframe['Outcome'] = None dataframe['Probability'] = None vertex_dict = {} for index_outcome, outcome in enumerate(probas[vertice]['vals']): vertex_dict[str(outcome)] = probas[vertice]["cprob"][index_outcome] od = collections.OrderedDict(sorted(vertex_dict.items())) # print "Vertice: " + str(vertice) # print "%-7s|%-11s" % ("Outcome", "Probability") # print "-------------------" for k, v in od.iteritems(): # print "%-7s|%-11s" % (str(k), str(round(v, 3))) dataframe.loc[len(dataframe)] = [k, v] dataframes[vertice] = dataframe else: # pp.pprint(probas[vertice]) dataframe['Outcome'] = None vertexen = {} for index_outcome, outcome in enumerate(probas[vertice]['vals']): temp = [] for parent_index, parent in enumerate(probas[vertice]["parents"]): # print str([str(float(index_outcome))]) temp = probas[vertice]["cprob"] dataframe[parent] = None vertexen[str(outcome)] = temp dataframe['Probability'] = None od = collections.OrderedDict(sorted(vertexen.items())) # [str(float(i)) for i in ast.literal_eval(key)] # str(v[key][int(float(k))-1]) # print "Vertice: " + str(vertice) + " with parents: " + str(probas[vertice]['parents']) # print "Outcome" + "\t\t" + '\t\t'.join(probas[vertice]['parents']) + "\t\tProbability" # print "------------" * len(probas[vertice]['parents']) *3 # pp.pprint(od.values()) counter = 0 # print number_of_cols for outcome, cprobs in od.iteritems(): for key in cprobs.keys(): array_frame = [] array_frame.append((outcome)) print_string = str(outcome) + "\t\t" for parent_value, parent in enumerate([i for i in ast.literal_eval(key)]): # print "parent-value:"+str(parent_value) # print "parten:"+str(parent) array_frame.append(int(float(parent))) # print "lengte array_frame: "+str(len(array_frame)) print_string += parent + "\t\t" array_frame.append(cprobs[key][counter]) # print "lengte array_frame (2): "+str(len(array_frame)) # print cprobs[key][counter] print_string += str(cprobs[key][counter]) + "\t" # for stront in [str(round(float(i), 3)) for i in ast.literal_eval(key)]: # print_string += stront + "\t\t" # print "print string: " + print_string # print "array_frame:" + str(array_frame) dataframe.loc[len(dataframe)] = array_frame counter += 1 print "Vertice " + str(vertice) + " done" dataframes[vertice] = dataframe for edge in edges: dot_string += edge[0].replace(" ", "_") + ' -> ' + edge[1].replace(" ", "_") + ';\n' dot_string += '}' src = Source(dot_string) if draw_network:src.render('../data/BN', view=draw_network) if draw_network:src.render('../data/BN', view=False) print "vizualisation done" return dataframes
for n,c in colors.items(): node = A.get_node(n) node.attr['color'] = c node.attr['style'] = 'filled' print n,c for n,c in edges_color.items(): node = A.get_edge(*n) node.attr['color'] = c node.attr['penwidth'] = 2 print n,c except Exception,e: print "Error on printing graph: ",e src = Source(A) src.format = 'png' src.render("test-output/"+name,view=True) def minimize(self): for n in self.nodes(): path_exist = False for m in self.graph['initial']: if nx.has_path(self,m,n): path_exist = True break if path_exist==False: self.remove_node_init_accept(n) def run_trace(self,state_trace): labels = nx.get_node_attributes(self,'label') return [labels[n] for n in state_trace]
def to_image(self, all_data): graph = Source(all_data, format="svg") graph.render(view=True)