예제 #1
0
def results(graph_path):
    run(graph_path)
    results_path = "modules/Resultados/" + graph_path[:-4] + "_out.txt"
    report = read_file(results_path)
    print("Tudo pronto!\n")
    aux.press_enter()
    return report
예제 #2
0
def options():
    printc("cyan", "1. Enunciado e análise.")
    printc("cyan", "2. Ver ou inserir dados.")
    printc("cyan", "3. Resolução.")
    printc("cyan", "4. Configurações.")
    printc("cyan", "5. Créditos.")
    printc("cyan", "6. Sair.\n")
    option = input("Insira a opção desejada: ")
    aux.clear_screen()
    if (option == '1'):
        texts.problemAnalysis()
        aux.press_enter()
        menu()
    elif (option == '2'):
        dataManip.menu()
        menu()
    elif (option == '3'):
        resolution.menu()
        menu()
    elif (option == '4'):
        configs.menu()
        menu()
    elif (option == '5'):
        texts.credit()
        aux.press_enter()
        menu()
    elif (option == '6'):
        aux.clear_screen()
        exit(0)
    else:
        menu(True)
예제 #3
0
def algorithm_menu(alg):
    global graph_path
    global results
    error = False
    error2 = False
    while True:
        x = t.general_menu(alg, "algorithms_options2", alg, graph_path, error,
                           error2)
        error = False
        error2 = False
        if (x == "1"):
            if (graph_path not in os.listdir("modules/Grafos")): error2 = True
            else:
                results = call(alg)
                show_results(alg)
        elif (x == "2"):
            if (graph_path not in os.listdir("modules/Grafos")): error2 = True
            else:
                gd.draw_graph(graph_path)
        elif (x == "3"):
            if len(results) == 0:
                aux.printc("red", "Execute o algoritmo primeiro!\n")
                aux.press_enter()
            else:
                show_results(alg)
        elif (x == "4"):
            graph_path = choose_graph(alg)
        elif (x == "5"):
            break
        else:
            error = True
예제 #4
0
def instruction3():
    aux.clear_screen()
    text = [
        "Como inserir novos algoritmos:", "", "-> Inserindo em código:", "",
        "   O módulo com seu código deve estar na pasta \"~/modules\".",
        "   Abra o arquivo \"algorithms.py\" e, na sessão indicada por",
        "   comentários no código, insira as informações e o algoritmo",
        "   nos devidos locais instruídos. Bem como, deve-se importar",
        "   um módulo em python, com seu algoritmo, no local indicado.",
        "   Caso seu algoritmo não esteja em python, deve-se realizar ",
        "   uma interação entre as linguagens. Isto foi feito para nosso",
        "   algoritmo (dfs) e pode ser visualizado no arquivo \"dfs.py\".", "",
        "-> Formato dos retorno dos resultados:", "",
        "   Os resultados retornados pelo módulo em python devem estar",
        "   em um array, onde cada elemento é uma linha, terminada por",
        "   \"\\n\", se quiser ter uma quebra de linha. Recomendamos que",
        "   se leve em conta o tamanho do terminal na escritura dos",
        "   resultados. Uma maneira fácil de fazer isto é escrevendo os ",
        "   resultados em um arquivo de texto, com a formatação de seu",
        "   gosto, e ler as linhas do arquivo para um array. O que também",
        "   foi feito no módulo \"dfs.py\"."
    ]
    b.normal_blox(text, "@", 76, "white", True)
    print()
    aux.press_enter()
    aux.clear_screen()
예제 #5
0
def set_configs(config, value):
    path = 'configurations/configs'
    if (not os.path.isfile(path)):
        aux.printc("red",
                   "O arquivo " + path + " está corrompido ou não existe!")
        aux.press_enter()
        return
    if (config == 'learning_rate'):
        replaceAll(path, 'learning_rate',
                   'learning_rate          =' + str(value) + '\n')
    elif (config == 'minibatch'):
        replaceAll(path, 'minibatch',
                   'minibatch              =' + str(value) + '\n')
    elif (config == 'trainset'):
        replaceAll(path, 'trainset',
                   'trainset               =' + str(value) + '\n')
    elif (config == 'testset'):
        replaceAll(path, 'testset',
                   'testset                =' + str(value) + '\n')
    elif (config == 'epochs'):
        replaceAll(path, 'epochs',
                   'epochs                 =' + str(value) + '\n')
    else:
        aux.printc("red", "Configuração inválida!")
        aux.press_enter()
        return
예제 #6
0
def show_results(alg):
    aux.clear_screen()
    t.header(alg)
    aux.printc("bwhite", "Resultados:")
    print()
    for i in results:
        print(i, end='')
    print()
    aux.press_enter()
예제 #7
0
def options():
    printc("cyan", "1. Ver dados padrões.")
    printc("cyan", "2. Ver dados customizados.")
    printc("cyan", "3. Gerar dados aleatórios.")
    printc("cyan", "4. Instruções.")
    printc("cyan", "5. Voltar.\n")
    option = input("Insira a opção desejada: ")
    aux.clear_screen()
    if (option == '1'):
        printData()
        aux.press_enter()
        menu()
    elif (option == '2'):
        printData("custom")
        aux.press_enter()
        menu()
    elif (option == '3'):
        generateRandomData()
        aux.press_enter()
        menu()
    elif (option == '4'):
        texts.instructions()
        aux.press_enter()
        menu()
    elif (option == '5'):
        aux.clear_screen()
        return
    else:
        menu(True)
예제 #8
0
def instruction1():
    aux.clear_screen()
    text = [
        "Como utilizar o programa:", "",
        "   Escolha a opção \"Iniciar\", então escolha o algoritmo que deseja",
        "   executar. ", "",
        "   Após isto, escolha o grafo no qual deseja usar o algoritmo.", "",
        "   Por fim, escolha a opção \"Executar\".", "",
        "   Para visualizar os resultados novamente escolha \"Visualizar ",
        "   resultados\".", "",
        "   Se desejar visualizar o grafo escolha \"Visualizar grafo\"."
    ]
    b.normal_blox(text, "@", 76, "white", True)
    print()
    aux.press_enter()
    aux.clear_screen()
def load_model(net):
	texts.print_blox("CARREGAR")
	path = 'architectures'
	# print("PATH: ", os.getcwd())
	print("Arquivos encontrados:\n")
	files = os.listdir(path)
	for i in files:
		if (not i.endswith('~')):
			aux.printc("lyellow", i)
	name = input("\nInsira o nome do arquivo: ")
	path = path + '/' + name
	if(any(name == i for i in files)):
		net.load_state_dict(torch.load(path))
		print("Sucesso no carregamento!\n")
	else:
		aux.printc("red", "O arquivo "+path+" não foi encontrado!\n")
		aux.press_enter()
def getDataInputConfigs():
    file_path = os.path.join(os.path.dirname(__file__), "configurations")
    if (os.path.isfile(file_path)):
        with open(file_path, 'r') as f:
            text = f.read()
            if (text[35] != '0' and text[35] != '1'):
                aux.printc("red",
                           "O arquivo " + file_path + " está corrompido!")
                aux.press_enter()
                return 0
            return text[35]
    else:
        aux.printc(
            "red",
            "O arquivo " + file_path + " está corrompido ou não existe!")
        aux.press_enter()
        return 0
예제 #11
0
def get_configs():
    path = 'configurations/configs'
    if (os.path.isfile(path)):
        with open(path, 'r') as f:
            text = f.read()
            matrix = [item.split() for item in text.split('\n')[:-1]]
            # print(matrix)
            learning_rate = float(matrix[2][1][1:])
            minibatch = int(matrix[3][1][1:])
            trainset = int(matrix[4][1][1:])
            testset = int(matrix[5][1][1:])
            epochs = int(matrix[6][1][1:])
            return learning_rate, minibatch, trainset, testset, epochs
    else:
        aux.printc("red",
                   "O arquivo " + path + " está corrompido ou não existe!")
        aux.press_enter()
        return 0.001, 4, 1250, 250, 2
예제 #12
0
def choose_custom(alg):
    x = ""
    graphs = os.listdir("modules/Grafos")
    while (x not in graphs):
        aux.clear_screen()
        t.header(alg)
        print()
        aux.printc("yellow", "Grafos encontrados:\n")
        for i in graphs:
            aux.printc("lyellow", i)
        print("")
        x = input("Escolha um grafo (ou exit para voltar): ")
        if (x == "exit"): return ""
        elif (x not in graphs):
            print()
            aux.error_msg(3)
            aux.press_enter()
    return x
예제 #13
0
def instruction2():
    aux.clear_screen()
    text = [
        "Como adicionar grafos personalizados:", "",
        "-> Grafos personalizados:", "",
        "   O arquivo de grafo tem extensão \".txt\" e suas linhas devem",
        "   conter o seguinte formato:",
        "   > Primeira linha - número de vértices e de arestas, nesta ordem e",
        "   separados por um espaço",
        "   > Linhas seguintes - primeiro vértice, segundo vértice e peso (ou",
        "   distância) da aresta, nesta ordem e separados por um espaço.", "",
        "-> Inserir / Remover os arquivos personalizados:", "",
        "   Os arquivos estão localizados no caminho \"~/modules/Grafos\"."
    ]
    b.normal_blox(text, "@", 76, "white", True)
    print()
    aux.press_enter()
    aux.clear_screen()
예제 #14
0
def options():
    printc("cyan", "1. Usar dados padrões.")
    printc("cyan", "2. Usar dados customizados.")
    printc("cyan", "3. Voltar.\n")
    option = input("Insira a opção desejada: ")
    aux.clear_screen()
    if (option == '1'):
        solve()
        aux.press_enter()
        menu()
    elif (option == '2'):
        solve("custom")
        aux.press_enter()
        menu()
    elif (option == '3'):
        aux.clear_screen()
        return
    else:
        menu(True)
예제 #15
0
def credits():
    aux.clear_screen()
    text = [
        "UECE - Universidade Estadual do Ceará",
        "Curso de Ciência da Computação",
        "Disciplina de Teoria dos Grafos",
        "",
        "Docente:",
        "Mestra Camila Campos Colares das Dores",
        "",
        "Discentes:",
        "Gabriel Furtado Lins Melo",
        "José Gabriel Uchoa Holanda",
        "Lucas Almeida Aguiar",
        "Vinicius Amaro Sampaio",
        "",
        "Linguagens de Desenvolvimento:",
        "Python 3",
        "C++",
    ]
    b.normal_blox(text, size=74, color="white")
    print()
    aux.press_enter()
    aux.clear_screen()
def setDataInputConfigs(value):
    file_path = os.path.join(os.path.dirname(__file__), "configurations")
    if (os.path.isfile(file_path)):
        with open(file_path, 'r') as f:
            text = f.read()
            if (text[35] != '0' and text[35] != '1'):
                aux.printc("red",
                           "O arquivo " + file_path + " está corrompido!")
                aux.press_enter()
                return 0
        text = list(text)
        if (value == "apart"):
            text[35] = '1'
        elif (value == "together"):
            text[35] = '0'
        text = ''.join(text)
        with open(file_path, 'w') as f:
            f.write(text)
    else:
        aux.printc(
            "red",
            "O arquivo " + file_path + " está corrompido ou não existe!")
        aux.press_enter()
        return 0
예제 #17
0
def random_menu(alg):
    while True:
        aux.clear_screen()
        t.header(alg)
        print()
        vertex = input("Informe a quantidade de vértices do grafo: ")
        if (not vertex.isdigit()):
            aux.printc("red", "\nPor favor digite um inteiro positivo.")
            aux.press_enter()
            continue
        vertex = int(vertex)
        ans = input("Quer um grafo completo? (s/n): ").lower()
        if (ans != 's' and ans != 'n'):
            aux.printc("red",
                       "\nPor favor digite apenas \'s\' ou \'n\' (sem o \')")
            aux.press_enter()
            continue
        complete = True if ans == 's' else False
        if (complete): connected = True
        else:
            ans = input("O grafo é conexo? (s/n): ").lower()
            if (ans != 's' and ans != 'n'):
                aux.printc(
                    "red",
                    "\nPor favor digite apenas \'s\' ou \'n\' (sem o \')")
                aux.press_enter()
                continue
            connected = True if ans == 's' else False
        aux.printc("yellow",
                   "\nInforme o nome com o qual deseja salvar o arquivo")
        aux.printc("yellow", "que contém o grafo (sem a extensão), ou apenas")
        filename = input(
            "\033[1;33mpressione enter para salvar como \"random.txt\": \033[0m"
        ) + ".txt"
        if (filename == ".txt"): filename = "random.txt"
        print()
        rg.generate(vertex, complete, connected, filename)
        return filename
예제 #18
0
def options():
	learning_rate, minibatch, trainset, testset, epochs = config.get_configs()
	printc("cyan","1. Visualizar arquitetura.")
	printc("cyan","2. Treinar rede.")
	printc("cyan","3. Testar rede.")
	printc("cyan","4. Predição individual.")
	printc("cyan","5. Carregar modelo.")
	printc("cyan","6. Salvar modelo.")
	printc("cyan","7. Resetar pesos.")
	printc("cyan","8. Configurações.")
	printc("cyan","9. Créditos.")
	printc("cyan","10. Sair.\n")
	option = input("Insira a opção desejada: ")
	aux.clear_screen()
	if(option=='1'):
		actions.print_model(net, minibatch)
		aux.press_enter()
		menu()
	elif(option=='2'):
		actions.train(net, epochs, trainset, minibatch, learning_rate) # (net, epochs, trainset, minibatch, learning rate)
		aux.press_enter()
		menu()
	elif(option=='3'):
		actions.test(net, testset, minibatch) # (net, testset, minibatch)
		aux.press_enter()
		menu()
	elif(option=='4'):
		actions.pred(net, minibatch)
		aux.press_enter()
		menu()
	elif(option=='5'):
		dm.load_model(net)
		menu()
	elif(option=='6'):
		dm.save_model(net)
		aux.press_enter()
		menu()
	elif(option=='7'):
		dm.reset_weights(net)
		menu()
	elif(option=='8'):
		config.menu()
		menu()
	elif(option=='9'):
		texts.credit()
		aux.press_enter()
		menu()
	elif(option=='10'):
		aux.clear_screen()
		exit(0)
	else:
		menu(True)
예제 #19
0
def generate(v, complete, connected, filename):
    G = create(v, complete, connected)
    save_file(v, G.number_of_edges(), list(G.edges(data='weight')), filename)
    aux.printc("green", "Grafo salvo em: " + filename)
    aux.press_enter()