def graficar_arbol(instrucciones): raiz = Node("root") metodo = raiz contador = 0 instr_restantes = [] for instr in instrucciones: if isinstance(instr, Imprimir): n_print = Node("imprimir", parent=raiz) #hijo = Node(instr.cad,parent=n_print) elif isinstance(instr, Definicion_Asignacion): n_asing = Node("asignar", parent=raiz) #graficar_hijos(instr,n_asing) elif isinstance(instr, Definicion_Asignacion_Arreglo): n_arr = Node("asignar arreglo", parent=raiz) elif isinstance(instr, Definicion_Asignacion_Arreglo_Multiple): n_arr_m = Node("asignar arreglo multiple", parent=raiz) elif isinstance(instr, If): n_if = Node("if", parent=raiz) elif isinstance(instr, Borrar): n_borrar = Node("borrar", parent=raiz) elif isinstance(instr, Definicion_Metodo): n_metodo = Node("metodo", parent=raiz) instr_restantes = [] contador = 0 for instruccion in instrucciones: #print("contador instrucciones en goto",contador) if isinstance(instruccion, Definicion_Metodo): #print("es un metodo:", instruccion.id, " ",instr.metodo.id) if instr.id == instruccion.id: instr_restantes = instrucciones[contador + 1:] #print("instrucciones restantes",instr_restantes) graficar_hijos(instr_restantes, n_metodo) UniqueDotExporter(raiz).to_picture("ast.png") return #print("metodo no existe") contador += 1 elif isinstance(instr, Goto): #print("entro al goto") n_goto = Node("goto", parent=raiz) elif isinstance(instr, Exit): #print("exit") n_exit = Node("exit", parent=raiz) else: print('Error: instruccion no valida graficar') UniqueDotExporter(raiz).to_picture("ast.png")
def evaluarEntradas(size, obstaculos, txtSize, txtObst): txtSize.config(state=DISABLED) txtObst.config(state=DISABLED) nodoRaiz = None # nodoRaiz, nodoSalida = doAlgorithm(size, obstaculos) while (True): nodoRaiz, nodoSalida = doAlgorithm(size, obstaculos) # if(showRecorridos(nodoRaiz).find("-100") == -1): # break if (showRecorridos(nodoSalida).find("-100") > 0): break UniqueDotExporter(nodoRaiz).to_picture("arbol_unique.png") # showRecorridos(nodoRaiz) # showRecorridos(nodoRaiz, tablero) cv2.namedWindow("Arbol resultante", cv2.WINDOW_NORMAL) imagenResultante = cv2.imread("arbol_unique.png", cv2.IMREAD_GRAYSCALE) ventanaImagenResizable = cv2.resize(imagenResultante, (800, 600)) cv2.imshow('Arbol resultante', ventanaImagenResizable) cv2.waitKey() cv2.destroyAllWindows() txtSize.config(state=NORMAL) txtObst.config(state=NORMAL) messagebox.showinfo(message="Algoritmo terminado", title="Información")
def doAlgorithm(size, obstaculos): tablero, xInicio, yInicio = construirTablero(size, obstaculos) if tablero[xInicio][yInicio] != 0: messagebox.showerror( message= "Por azares del destino, el tablero no cuenta con una casilla de salida, que mala suerte...", title="Upss") raise Exception( "Por azares del destino, el tablero no cuenta con una casilla de salida, que mala suerte..." ) nodoRaiz = Node(tablero[xInicio][yInicio], id=uniqueID()) pilaDeNodos = [] mostrarTablero(tablero) buscarAlosAlrededores(pilaDeNodos, nodoRaiz, tablero, xInicio, yInicio) UniqueDotExporter(nodoRaiz).to_picture("arbol_unique.png") showRecorridos(nodoRaiz, tablero) imagenResultante = cv2.imread("arbol_unique.png", cv2.IMREAD_COLOR) cv2.imshow('Arbol resultante', imagenResultante) cv2.waitKey(0) cv2.destroyAllWindows() pygame.quit()
def semantica(arquivoNome): arvore = sintatica.generate(arquivoNome) if(arvore): arvorePoda(arvore) criarTabela(arvore) confereErroArvore(arvore) confereErroTabela() atribuicaoDistinta(arvore) juntaFunc(arvore) pesquisaFuncao(arvore) declaracao_funcao(arvore, arvore) verificaArray(arvore) for tabela in vetTabela: print("\n_______________________________________\n") print(" tipo: " , tabela.getTipo() , "\n nome: " , tabela.getNome() , "\n tipoValor: " , tabela.getTipoValor() , "\n parametros: " , tabela.getParametros() , "\n dimensoes: " , tabela.getDimensoes() , "\n escopo: " , tabela.getEscopo() , "\n declarada: " , tabela.getDeclarada() , "\n inicializada: " , tabela.getInicializada() , "\n utilizada: ", tabela.getUtilizada(), "\n" ) UniqueDotExporter(arvore).to_picture("programaPoda.png") return[vetTabela, arvore, vetError]
def generar_imagen_arbol(nodoRaiz): UniqueDotExporter(nodoRaiz).to_picture("arbol_unique.png") cv2.namedWindow("Arbol resultante", cv2.WINDOW_NORMAL) imagenResultante = cv2.imread("arbol_unique.png", cv2.IMREAD_GRAYSCALE) ventanaImagenResizable = cv2.resize(imagenResultante, (800, 600)) cv2.imshow('Arbol resultante', ventanaImagenResizable) cv2.waitKey() cv2.destroyAllWindows()
def main(): arquivo_teste = open(sys.argv[1], 'r', encoding='utf-8').read() numero_linhas = sum(1 for linha in open(sys.argv[1], 'r', encoding='utf-8')) # Sintatico arvore, sintatico_sucesso = sin.analisador(arquivo_teste, numero_linhas) # Semantico if (sintatico_sucesso): UniqueDotExporter(arvore).to_picture("arvore.png") arvore, tabela_simbolos, sema_sucesso = sem.semantica(arvore) UniqueDotExporter(arvore).to_picture("arvore_podada.png") # Geracao de codigo if (sema_sucesso): ger.gera_codigo(arvore, tabela_simbolos, sema_sucesso)
def visualize_parse_tree(trace): if trace: # for pre, fill, node in RenderTree(trace[0]): # print(f'{pre}{node.name}') UniqueDotExporter(trace[0]).to_picture("arith_pt.png") Image.open(rf'D:/GeeK/ComViz/arith_pt.png').show()
def export(path): """Crea una imagen png del árbol de dominios Parameters: path (str): Path donde se almacenará la imagen """ from anytree.exporter import UniqueDotExporter UniqueDotExporter(root).to_picture(path) print("Se exportó una imagen png")
def show_config_requirements(experiment_type: str, format: str = 'text'): """ show experiment file requirements Arguments: - experiment_type : str - format : str """ if not format in ['text', 'figure']: raise RuntimeError( 'unsupported format %s, supported : `text`, `figure`' % (format)) config = __get_config(experiment_type) if format == 'text': return str(RenderTree(config)) else: filename = 'config_requirements.gv' from tempfile import NamedTemporaryFile try: from graphviz import Source except ImportError as e: raise ImportError( "unable to import graphviz, you can install it using `pip3 install graphviz`" ) with NamedTemporaryFile("wb", delete=False) as dotfile: dotfilename = dotfile.name def edgetypefunc(node, child): return '->' def nodeattrfunc(node): return 'label="%s", %s' % (node.name, "shape=box" if node.is_required() else "shape=oval") exporter = UniqueDotExporter(config, edgetypefunc=edgetypefunc, nodeattrfunc=nodeattrfunc) exporter.to_dotfile('test.dot') for line in exporter: dotfile.write(("%s\n" % line).encode("utf-8")) dotfile.flush() gv = Source.from_file(dotfilename) return gv
def retorna_root(filename): if len(filename) == 0: print("Erro! Informe o nome do arquivo") exit() data = open(filename) source_file = data.read() parser.parse(source_file) UniqueDotExporter(root).to_picture(filename + ".png") return root
def main(): global root aux = argv[1].split('.') if aux[-1] != 'tpp': raise IOError("Not a .tpp file!") data = open(argv[1]) source_file = data.read() root = parser.parse(source_file) if root and root.children != (): print( '\n* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * \n') print("Generating AST, please waiexport_ASTt...") UniqueDotExporter(root).to_picture("tree.png") UniqueDotExporter(root).to_dotfile("tree.dot") print("AST was successfully generated.\nOutput file: 'tree.png'") else: log.error("Unable to generate AST -- Syntax nodes not found") print('\n\n')
def generate(arquivoRead): yacc.yacc() arquivo = open(arquivoRead) data = arquivo.read() programa = yacc.parse(data) if(not error): UniqueDotExporter(programa).to_picture("programa.png") return programa return False
def printGraph(formula, output, inputnode, printmodes, name): # for the current tests there is only one single formula in each output. So this suffices if PRINT_RESULT in printmodes: outputgraph_or = nestedListToGraph(output) UniqueDotExporter(outputgraph_or).to_picture(PICTURE_PATH + name + ".png") print("Printed a graph with only the result in it") # In case one wishes for the output in listform to be on top as a node: if PRINT_ATOMDECOMP in printmodes: outputgraph_ad = nestedListToGraph(output) rootnode_ad = Node(output, children={outputgraph_ad}) UniqueDotExporter(rootnode_ad).to_picture(PICTURE_PATH_WITH_DECOMP + name + ".png") print("Printed a graph with the result in listform") if PRINT_INPUTFORMULA in printmodes: outputgraph_wi = nestedListToGraph(output) rootnode_wi = Node(output, parent=inputnode, children={outputgraph_wi}) UniqueDotExporter(inputnode).to_picture(PICTURE_PATH_WITH_FORMULAS + name + ".png") print("Printed a graph with input formula and result in listform")
def main(): if (len(argv) < 2): print("Erro! Informe o nome do arquivo") data = open("semantica-testes/sema-003.tpp") # exit() else: data = open(argv[1]) source_file = data.read() parser.parse(source_file) global erro try: if root and root.children != () and erro != False: print("Generating Syntax Tree Graph...") # DotExporter(root).to_picture(argv[1] + ".ast.png") UniqueDotExporter(root).to_picture(argv[1] + ".unique.ast.png") # DotExporter(root).to_dotfile(argv[1] + ".ast.dot") UniqueDotExporter(root).to_dotfile(argv[1] + ".unique.ast.dot") # print(RenderTree(root, style=AsciiStyle()).by_attr()) print("Graph was generated.\nOutput file: " + argv[1] + ".ast.png") DotExporter( root, graph="graph", nodenamefunc=MyNode.nodenamefunc, nodeattrfunc=lambda node: 'label=%s' % (node.type), edgeattrfunc=MyNode.edgeattrfunc, edgetypefunc=MyNode.edgetypefunc).to_picture(argv[1] + ".ast2.png") # DotExporter(root, nodenamefunc=lambda node: node.label).to_picture(argv[1] + ".ast3.png") else: print('\n--------------------------------\n') print('Não foi possível gerar a árvore!') except NameError as error: print("Erro: " + str(error)) print('Não foi possível gerar a árvore!')
def visualize_ast(node=None): if node: pre_order(node) global trace # for pre, fill, node in RenderTree(trace[0]): # print(f'{pre}{node.name}') UniqueDotExporter(trace[0]).to_picture("arith_ast.png") # re_trace = trace # trace = [] Image.open(rf'D:/GeeK/ComViz/arith_ast.png').show() return trace
def main(): test_file = open(sys.argv[1], 'r', encoding = 'utf-8').read() file_num_lines = sum(1 for line in open(sys.argv[1], 'r', encoding = 'utf-8')) # Syntax tree, syntax_success = syn.parser(test_file, file_num_lines) # Semantics if (syntax_success): tree, symbol_table, sema_success = sem.semantics(tree) UniqueDotExporter(tree).to_picture("program.png") if(sema_success): gen.gen_code(tree, symbol_table, sema_success)
def main(): print() aux = argv[1].split(".") if aux[-1] != "tpp": raise IOError("Not a .tpp file!") data = open(argv[1]) source_file = data.read() parser.parse(source_file) try: if root and root.children != (): print("\n-------------OK--------------") print("Generating Syntax Tree Graph...") DotExporter(root).to_picture(argv[1] + ".ast.png") UniqueDotExporter(root).to_picture(argv[1] + ".unique.ast.png") DotExporter(root).to_dotfile(argv[1] + ".ast.dot") UniqueDotExporter(root).to_dotfile(argv[1] + ".unique.ast.dot") print(RenderTree(root, style=AsciiStyle()).by_attr()) print("Graph was generated.\nOutput file: " + argv[1] + ".ast.png") DotExporter( root, graph="graph", nodenamefunc=MyNode.nodenamefunc, nodeattrfunc=lambda node: "label=%s" % (node.type), edgeattrfunc=MyNode.edgeattrfunc, edgetypefunc=MyNode.edgetypefunc, ).to_picture(argv[1] + ".ast2.png") DotExporter(root, nodenamefunc=lambda node: node.label).to_picture( argv[1] + ".ast3.png" ) except NameError: print("Não foi possível gerar a árvore sintática.") print("\n\n")
def semantica_main(data): raiz = sin.retorna_root(data) if raiz is None: print("Árvore não foi gerada!") else: print("Árvore gerada!") analisa_arvore(raiz) print("---------------------------------") verifica_existe_principal() verifica_variaveis_usadas() verifica_funcoes_utilizadas() print_erro() print_warnings() print("---------------------------------") if raiz and raiz.children != (): try: print("Generating Syntax Tree Graph...") UniqueDotExporter(raiz).to_picture(argv[1] + ".unique.ast.png") print("Graph was generated.\nOutput file: " + argv[1] + ".ast.png") except IndexError: print("Generating Syntax Tree Graph... v2") UniqueDotExporter(raiz).to_picture("arvoregerada.unique.ast.png") print("Graph was generated.\nOutput file: " + " arvoregerada.ast.png") return raiz
def parser(lists, terminal_symbols, non_terminal_symbols): formula = lists[6] attempted_formula = [] current_symbol = 0 origin = Node("@F") check = recursiveCheck(lists, terminal_symbols, non_terminal_symbols, origin, formula, attempted_formula, current_symbol) # check output if check[0] == 0: return check elif len(attempted_formula) != len(formula): if len(attempted_formula) < len(formula): x = len(formula) - len(attempted_formula) return ( 0, f"The Parse Tree didn't match original formula. The formula has {x} more symbol(s) at the end: {formula[len(formula)-x:len(formula)]}" ) elif len(attempted_formula) > len(formula): x = len(attempted_formula) - len(formula) return ( 0, f"The Parse Tree didn't match original formula. The parse tree formulas {x} more symbol(s) at the end: {attempted_formula[len(attempted_formula)-x:len(attempted_formula)]}" ) check = True wrong = 0 for i in range(len(attempted_formula)): if attempted_formula[i] != formula[i]: wrong = i check = False break if check: # output graph UniqueDotExporter(origin).to_picture("parseTree.png") print( "Full Parse Tree successfully constucted and saved to parseTree.png" ) print() return (1, "None") else: return ( 0, f"The Parse Tree didn't match original formula. Difference found at symbol '{wrong}' with symbol '{formula[wrong]}'" )
def test_tree1(): """Tree1.""" root = Node("root") s0 = Node("sub0", parent=root) s0b = Node("sub0B", parent=s0) id_root = hex(id(root)) id_s0 = hex(id(s0)) id_s0b = hex(id(s0b)) lines = tuple(UniqueDotExporter(root)) eq_(lines, ('digraph tree {', ' "{id_root}" [label="root"];'.format( id_root=id_root), ' "{id_s0}" [label="sub0"];'.format(id_s0=id_s0), ' "{id_s0b}" [label="sub0B"];'.format(id_s0b=id_s0b), ' "{id_root}" -> "{id_s0}";'.format( id_root=id_root, id_s0=id_s0), ' "{id_s0}" -> "{id_s0b}";'.format( id_s0=id_s0, id_s0b=id_s0b), '}'))
def get_next_links(link, tn, tn_root, level): #driver = webdriver.Firefox(firefox_options=options, capabilities=cap, executable_path="geckodriver.exe") driver.get(link) fn = link if level != 0: fn = link.replace(original_link, "") fn = fn.replace("/", ".") fn = fn.replace(":", "") with open('html_files/' + fn + ".html", "w", encoding="utf-8") as f: f.write(driver.page_source) list_done.append(link) list_links = driver.find_elements_by_tag_name('a') print('lengte:', len(list_done)) print('lengte:', len(list_links)) for i in range(len(list_links)): #driver = webdriver.Firefox(firefox_options=options, capabilities=cap, executable_path="geckodriver.exe") #driver.set_page_load_timeout(5) print('current page:' + link) driver.get(link) list_links = driver.find_elements_by_tag_name('a') #print(list_links) next_link = list_links[i].get_attribute('href') tn_next = AnyNode(id=next_link, name=next_link, parent=tn, level=level) #tn.add_child(tn_next) UniqueDotExporter(tn_root).to_dotfile(site_name + ".dot") if next_link != '' and 'http' in next_link and not next_link in list_done and site_name in next_link: print('van:', link, 'naar:', list_links[i].get_attribute('href')) try: #driver.quit() get_next_links(next_link, tn_next, tn_root, level + 1) except Exception as inst: #driver.quit() print('Something went wrong when trying to load:', next_link) f = open('errors.log', 'a') f.write(str(inst)) f.write(str(list_links[i]) + '\n') f.write('op pagina ' + link + '\n\n') f.close() print('Error message saved to log')
def print_in_file(self, file_name="tree_test.png"): """ Function to plot generated tree as an image file Args: file_name (str): full name of image to be created """ base_dir="./img/" image_file_name = base_dir + file_name # define local functions def aux(n): a = 'label="{}" {}'.format(n.ascii, n.style(parent=n.parent)) return a # self.remove_leaves() os.makedirs(os.path.dirname(image_file_name), exist_ok=True) UniqueDotExporter(self.root, nodeattrfunc=aux, edgeattrfunc=lambda parent, child: 'arrowhead=vee').to_picture(image_file_name) log.info("Tree image saved in {}".format(image_file_name))
def evaluarEntradas(size, txtSize): nodoRaiz = None nodoRaiz, nodoSalida = doAlgorithm(size) while nodoSalida == None: nodoRaiz, nodoSalida = doAlgorithm(size) print(nodoRaiz) print(nodoSalida) showRecorridos(nodoSalida) UniqueDotExporter(nodoRaiz).to_picture("arbol_unique.png") # showRecorridos(nodoRaiz) # showRecorridos(nodoRaiz, tablero) cv2.namedWindow("Arbol resultante", cv2.WINDOW_NORMAL) imagenResultante = cv2.imread("arbol_unique.png", cv2.IMREAD_GRAYSCALE) ventanaImagenResizable = cv2.resize(imagenResultante, (800, 600)) cv2.imshow('Arbol resultante', ventanaImagenResizable) cv2.waitKey() cv2.destroyAllWindows() txtSize.config(state=NORMAL) txtObst.config(state=NORMAL) messagebox.showinfo(message="Algoritmo terminado", title="Información")
# src/__syntatic__.py import sys from anytree import RenderTree from anytree.exporter import UniqueDotExporter from lexer import tokenize from syntatic import parse if (len(sys.argv) < 2): exit(1) file = open(sys.argv[1], 'r') data = file.read() tree = 'trees/' + sys.argv[1].split('.')[0].split('/')[-1] logFile = open(tree + '.tree', 'w') p = parse(data) UniqueDotExporter(p).to_picture(tree + '.png') for prefix, cor, no in RenderTree(p): logFile.write(("%s%s\n" % (prefix, no.name)))
.format(" ".join(parse_formula), " ".join(grammar["formula"]))) exit() if parse_formula[j][0] != grammar["formula"][j]: for k in range(len(parse_formula)): parse_formula[k] = parse_formula[k][0] log.write( "Error, formula cannot be parsed correctly as parser produces semi-complete formula:\n\"{0}\"\nwhich mismatches the inputted formula:\n\"{1}\"\nupon reaching symbol \"{2}\" in the {3}'th position ( \"{2}\" != \"{4}\" ).\nPlease inspect the two above formulas and refer to the grammar production rules to see the types of valid expressions, and their formats." .format(" ".join(parse_formula), " ".join(grammar["formula"]), grammar["formula"][j], j, parse_formula[j])) exit() #check formula isnt longer than completed parsed formula if len(parse_formula) != len(grammar["formula"]): for k in range(len(parse_formula)): parse_formula[k] = parse_formula[k][0] log.write( "Error, formula cannot be parsed correctly as parser produces a complete formula:\n\"{0}\"\nwhich has unequal length to therefore mismatches the inputted formula:\n\"{1}\"\n(and may proceed no further using the production rules of the grammar, as no non-terminals remain).\nPlease inspect the two above formulas and refer to the grammar production rules to see the types of valid expressions, and their formats." .format(" ".join(parse_formula), " ".join(grammar["formula"]))) exit() #Once formula has been validated and tree constructed, render tree to file and write success to log UniqueDotExporter(root).to_picture("tree.png") log.write( "Success, both the input file format and formula are valid. Check \"tree.png\" for the produced parse tree." ) #N.B. ALL INDEXING IN ERRORS STARTS AT 0 !!!!!!!!!!!!!!!!!!!!!!
# src/__semantic__.py import sys from anytree import RenderTree from anytree.exporter import UniqueDotExporter from lexer import tokenize from syntatic import parse from semantic import semantic if (len(sys.argv) < 2): print("verifique os argumetos") exit(1) file = open(sys.argv[1], 'r') data = file.read() tree = parse(data) treeFile = 'logs/symbols/base-tree-' + sys.argv[1].split('.')[0].split('/')[-1] UniqueDotExporter(tree).to_picture(treeFile + '.png') newTree = semantic(tree) UniqueDotExporter(newTree).to_picture(treeFile + '-plunned.png')
def save_tree(self): UniqueDotExporter(self.root).to_picture('Outputs/' + self.file_name + '.png')
else: obj[new_key] = "Node_type: " + obj[ key] + "\n" + "Value: " + obj[ 'value'] + "\n" + "Line: " + str(obj['line']) del obj[key] return obj if __name__ == '__main__': arg_parser = argparse.ArgumentParser(description='Tree Gnerator!') arg_parser.add_argument("--i", default="AST.json", type=str, help="Input JSON file with Nodes") arg_parser.add_argument("--o", default="tree.png", type=str, help="Output image for tree ") args: argparse.Namespace = arg_parser.parse_args() input_filename: str = args.i output_filename: str = args.o with open(input_filename) as json_file: data = json.load(json_file) new_json = json.loads(json.dumps(data), object_hook=remove_dots) root = importer.import_(new_json) UniqueDotExporter(root).to_picture(output_filename)
def export(self, path: str, name: str = 'tree.png'): if self.empty(): return UniqueDotExporter(self.head).to_picture(os.path.join(path, name))
# nodeCount[r[:-1]] -= 1 # exhaustedStates = [] # # # if numUnvisited == 1 and current.id not in exhaustedStates: # exhaustedStates.append(current.id) # from anytree.exporter import DotExporter # DotExporter(startNode).to_picture("udo.png") print(nodeCount) from anytree.exporter import UniqueDotExporter # for line in UniqueDotExporter(startNode, nodeattrfunc=lambda n: 'label="%s"' % (n.id)): # print(line) UniqueDotExporter(startNode, nodeattrfunc=lambda n: 'label="%s"' % (n.id)).to_picture('test.png') # print(RenderTree(startNode)) # write_dot(tracesTree, 'test.dot') # pos = graphviz_layout(tracesTree, prog='dot') # plt.title('draw_networkx') # pos = hierarchy_pos(G, 1) # plt.title('draw_networkx') # pos = nx.planar_layout(tracesTree) # nx.draw(tracesTree, node_size=1000, node_color='r', node_shape='s', with_labels=False) # labels = {} # for i in tracesTree: # labels[i] = tracesTree.node[i]['value'] # nx.draw_networkx_labels(tracesTree, pos, labels, font_size=12)