示例#1
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
示例#2
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)
示例#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 listdir_nohidden(path):
    filespath = os.path.join(os.path.dirname(__file__), path)
    print("Arquivos encontrados:\n")
    files = os.listdir(filespath)
    for i in files:
        if (not i.endswith('~')):
            printc("lyellow", i)
示例#5
0
 def make_bloxLeft(self, phrase=""):
     printc(self.color, self.brick, end='')
     void = (self.size - 4 - len(phrase))
     printc(self.color, '  ', end='')
     printc(self.color, phrase, end='')
     for i in range(void):
         printc(self.color, ' ', end='')
     printc(self.color, self.brick)
示例#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 algorithms_options2(alg, graph):
    graph = "Nenhum" if graph == "" else graph
    aux.printc("cyan", "Grafo escolhido: \033[1;35m" + graph)
    print()
    options = [
        "1. Executar " + alg, "", "2. Visualizar grafo", "",
        "3. Visualizar resultados", "", "4. Escolher um Grafo", "", "5. Voltar"
    ]
    b.options_blox(options, "yellow")
    cursor_up = len(options) + 3  # Caso especial de cursor up
    return cursor_up
示例#8
0
def generateRandomData():
    A1 = np.random.randint(-40, 40, (5, 5))
    B1 = np.random.randint(-100, 100, (5, 1))
    S1 = np.concatenate((A1, B1), axis=1)
    A2 = np.random.randint(-15, 15, (5, 5))
    B2 = np.random.randint(-400, 800, (5, 1))
    S2 = np.concatenate((A2, B2), axis=1)
    matrix = np.concatenate((S1, S2), axis=0)
    A1, B1, A2, B2 = matrixToSystems(matrix)
    printSystem(A1, B1, A2, B2)
    saveData(S1, S2, "random")
    printc("cyan", "Os sistemas foram salvos no arquivo \"random\"!\n")
def menu(error_message=False):
    aux.clear_screen()
    a = getDataInputConfigs()
    if (a == 0): return
    texts.print_blox("CONFIGURAÇÕES")
    if (error_message):
        aux.error_option()
    print("Formato dos dados: ", end="")
    if (a == '1'):
        aux.printc("purple", "Matrizes e vetores separados em arquivos.\n")
    elif (a == '0'):
        aux.printc("purple", "Os 2 sistemas em um só arquivo.\n")
    options()
def options():
    aux.printc("cyan", "1. Alterar formato de obtenção dos dados.")
    aux.printc("cyan", "2. Voltar.\n")
    option = input("Insira a opção desejada: ")
    aux.clear_screen()
    if (option == '1'):
        actual = getDataInputConfigs()
        if (actual == '0'): setDataInputConfigs("apart")
        else: setDataInputConfigs("together")
        menu()
    elif (option == '2'):
        aux.clear_screen()
        return
    else:
        menu(True)
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
示例#13
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
示例#14
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
示例#15
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
def pred(net, batch_size):
    option = input("Deseja escolher um arquivo? (s/n): ")
    if (option == 's' or option == 'S'):
        path = 'Images'
        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)):
            image = dm.load_image(path)
            classes = ('plane', 'car', 'bird', 'cat', 'deer', 'dog', 'frog',
                       'horse', 'ship', 'truck')
            output = net(image)
            _, predicted = torch.max(output, 1)
            print("Predição da rede: " + classes[predicted])
            print()
        else:
            aux.printc("red", "O arquivo " + path + " não foi encontrado!")
            print()
    else:
        testloader, classes = dm.load_testset_CIFAR10(batch_size)
        dataiter = iter(testloader)
        images, labels = dataiter.next()
        imshow(torchvision.utils.make_grid(images))
        print('Labels das imagens: ',
              ' '.join('%5s' % classes[labels[j]] for j in range(batch_size)))
        plt.title('Amostra de teste')
        plt.show()
        outputs = net(images)
        _, predicted = torch.max(outputs, 1)
        print(
            "Predição da rede: ",
            ' '.join('%5s' % classes[predicted[j]] for j in range(batch_size)))
        print()
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
示例#18
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)
示例#19
0
def credit():
    printc(
        "white",
        "#########################################################################"
    )
    printc(
        "white",
        "#                                                                       #"
    )
    printc(
        "white",
        "#                 UECE - Universidade Estadual do Ceará                 #"
    )
    printc(
        "white",
        "#                                                                       #"
    )
    printc(
        "white",
        "#                                Docente:                               #"
    )
    printc(
        "white",
        "#                     Suzana Matos Franca de Oliveira                   #"
    )
    printc(
        "white",
        "#                                                                       #"
    )
    printc(
        "white",
        "#                               Discentes:                              #"
    )
    printc(
        "white",
        "#         Alan Pereira de Vasconcelos Junior (Coding + Interface)       #"
    )
    printc(
        "white",
        "#                  Camila Alves Barbosa (Coding + Frontend)             #"
    )
    printc(
        "white",
        "#               Gabriel Furtado Lins Melo (Coding + Math)               #"
    )
    printc(
        "white",
        "#            Hianuy Esperidiao de Sousa Pinto (Coding + Debug)          #"
    )
    printc(
        "white",
        "#             (líder) Vinicius Amaro Sampaio (Coding + Backend)         #"
    )
    printc(
        "white",
        "#                                                                       #"
    )
    printc(
        "white",
        "#                      Linguagem de Desenvolvimento:                    #"
    )
    printc(
        "white",
        "#                              Python 3.4.3                             #"
    )
    printc(
        "white",
        "#                                                                       #"
    )
    printc(
        "white",
        "#########################################################################"
    )
    print("")
示例#20
0
def print_blox(title="MENU"):
    printc("green",
           "############################################################")
    printc("green",
           "#                                                          #")
    printc("green",
           "#              Trabalho de Cálculo Numérico.               #")
    printc("green", "#                  Equipe やめてお姉ちゃん                 #")
    printc("green",
           "#                                                          #")
    printc("green",
           "############################################################")
    printc("yellow", "                 ~~~~~~~~ " + title + " ~~~~~~~~")
    print("")
示例#21
0
def instructions():
    printc(
        "white",
        "##########################################################################"
    )
    printc(
        "white",
        "#                                                                        #"
    )
    printc(
        "white",
        "# Instruções:                                                            #"
    )
    printc(
        "white",
        "#                                                                        #"
    )
    printc(
        "white",
        "# -> Inserção de dados customizados:                                     #"
    )
    printc(
        "white",
        "#    Para inserir os dados dos sistemas que deseja criar, basta abrir    #"
    )
    printc(
        "white",
        "#    ou criar um arquivo de texto na pasta \"data\" (não é recomendado     #"
    )
    printc(
        "white",
        "#    modificar o arquivo \"standard.txt\") e editá-lo conforme os mode-    #"
    )
    printc(
        "white",
        "#    los encontrados na pasta. As matrizes A's inseridas devem ser nxn.  #"
    )
    printc(
        "white",
        "#    É importante ressaltar que os vetores b\'s são inseridos como a      #"
    )
    printc(
        "white",
        "#    última coluna das matrizes A's. Quanto à precisão, esta é defini-   #"
    )
    printc(
        "white",
        "#    da na resolução.                                                    #"
    )
    printc(
        "white",
        "#                                                                        #"
    )
    printc(
        "white",
        "##########################################################################"
    )
    print("")
示例#22
0
def problemAnalysis():
    printc(
        "white",
        "##########################################################################"
    )
    printc(
        "white",
        "#                                                                        #"
    )
    printc(
        "white",
        "# Enunciado:                                                             #"
    )
    printc(
        "white",
        "# Uma pequena ponte está sendo analisada para que uma carga muito pesada #"
    )
    printc(
        "white",
        "# passe por ela. Existem alguns pontos amostrais, calculados pelo siste- #"
    )
    printc(
        "white",
        "# ma linear S1, em que a pressão pode ser descoberta pelo sistema linear #"
    )
    printc(
        "white",
        "# S2. O ponto mais frágil da ponte se encontra na média dos pontos amos- #"
    )
    printc(
        "white",
        "# trais.                                                                 #"
    )
    printc(
        "white",
        "#                                                                        #"
    )
    printc(
        "white",
        "# Análise do problema:                                                   #"
    )
    printc(
        "white",
        "# As posições dos pontos amostrais da ponte são obtidas através da reso- #"
    )
    printc(
        "white",
        "# lução do sistema S1, com o método da eliminação de Gauss, e suas res-  #"
    )
    printc(
        "white",
        "# pectivas pressões são calculadas pelo sistema S2, o qual é resolvido   #"
    )
    printc(
        "white",
        "# com o método de Gauss-Jacobi e sua convergência é verificada, basean-  #"
    )
    printc(
        "white",
        "# do-se na precisão fornecida e no número de iterações. O sistema S2 é   #"
    )
    printc(
        "white",
        "# submetido a uma intepolação quadrática, utilizando a forma de Newton,  #"
    )
    printc(
        "white",
        "# para calcular a pressão no ponto mais frágil da ponte, com sua posição #"
    )
    printc(
        "white",
        "# dada pela média dos pontos calculados em S1.                           #"
    )
    printc(
        "white",
        "#                                                                        #"
    )
    printc(
        "white",
        "##########################################################################"
    )
    print("")
示例#23
0
def options_blox(options, color="blue"):
    for i in range(len(options)):
        printc(color, "  " + options[i])
示例#24
0
 def make_blox(self, phrase=""):
     printc(self.color, self.brick, end='')
     void = int((self.size - 2 - len(phrase)) / 2)
     for i in range(void):
         printc(self.color, ' ', end='')
     printc(self.color, phrase, end='')
     for i in range(void):
         printc(self.color, ' ', end='')
     if (len(phrase) % 2 != 0): printc(self.color, ' ' + self.brick)
     else: printc(self.color, self.brick)
示例#25
0
 def make_cover(self):
     for i in range(self.size):
         printc(self.color, self.brick, end='')
     print()
示例#26
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)
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)
示例#28
0
def openData(op="standard"):
    a = getDataInputConfigs()

    if (op == "standard"):
        file_path = os.path.join(os.path.dirname(__file__), "data", "together",
                                 "standard")

    elif (op == "custom"):

        if (a == '0'):
            listdir_nohidden("data/together")
            filename = input("\nInsira o nome do arquivo que deseja usar: ")
            file_path = os.path.join(os.path.dirname(__file__), "data",
                                     "together", filename)

        elif (a == '1'):
            listdir_nohidden("data/apart")
            A1 = input("\nInsira o nome do arquivo da matriz A1: ")
            A1_path = os.path.join(os.path.dirname(__file__), "data", "apart",
                                   A1)
            if (not os.path.isfile(A1_path)):
                printc("red", "O arquivo " + A1_path + " não foi encontrado!")
                return 0
            b1 = input("Insira o nome do arquivo do vetor b1: ")
            b1_path = os.path.join(os.path.dirname(__file__), "data", "apart",
                                   b1)
            if (not os.path.isfile(b1_path)):
                printc("red", "O arquivo " + b1_path + " não foi encontrado!")
                return 0
            A2 = input("Insira o nome do arquivo da matriz A2: ")
            A2_path = os.path.join(os.path.dirname(__file__), "data", "apart",
                                   A2)
            if (not os.path.isfile(A2_path)):
                printc("red", "O arquivo " + A2_path + " não foi encontrado!")
                return 0
            b2 = input("Insira o nome do arquivo do vetor b2: ")
            b2_path = os.path.join(os.path.dirname(__file__), "data", "apart",
                                   b2)
            if (not os.path.isfile(b2_path)):
                printc("red", "O arquivo " + b2_path + " não foi encontrado!")
                return 0

            aux.clear_screen()
            with open(A1_path, 'r') as f:
                A1 = np.loadtxt(f)
            with open(b1_path, 'r') as f:
                b1 = np.loadtxt(f)
            with open(A2_path, 'r') as f:
                A2 = np.loadtxt(f)
            with open(b2_path, 'r') as f:
                b2 = np.loadtxt(f)
            matrix = systemToMatrix(A1, b1, A2, b2)
            return matrix

    if (a == '0' or op == "standard"):
        aux.clear_screen()
        if (os.path.isfile(file_path)):
            if (os.path.getsize(file_path) > 0):
                with open(file_path, 'r') as f:
                    matrix = np.loadtxt(
                        f, comments='S')  # ignora as linhas começadas com 'S'
                    return matrix
            else:
                printc("red", "O arquivo " + file_path + " está vazio!")
                return 0
        else:
            printc("red", "O arquivo " + file_path + " não foi encontrado!")
            return 0
示例#29
0
def print_blox(title="MENU"):
    printc("green",
           "############################################################")
    printc("green",
           "#                                                          #")
    printc("green",
           "#               Neural Network Trainer (CNN)               #")
    printc("green",
           "#                                                          #")
    printc("green",
           "############################################################")
    printc("yellow", "                 ~~~~~~~~ " + title + " ~~~~~~~~")
    print("")
示例#30
0
def options():
    learning_rate, minibatch, trainset, testset, epochs = get_configs()
    printc("cyan", "1. Learning rate: \033[1;33m" + str(learning_rate))
    printc("cyan", "2. Minibatch: \033[1;33m" + str(minibatch))
    printc("cyan", "3. Conjunto de treino: \033[1;33m" + str(trainset))
    printc("cyan", "4. Conjunto de teste: \033[1;33m" + str(testset))
    printc("cyan", "5. Épocas: \033[1;33m" + str(epochs))
    printc("cyan", "6. Voltar.\n")
    option = input("Insira a opção desejada: ")
    aux.clear_screen()
    if (option == '1'):
        x = input("Insira o novo valor: ")
        set_configs('learning_rate', x)
        menu()
    elif (option == '2'):
        x = input("Insira o novo valor: ")
        set_configs('minibatch', x)
        menu()
    elif (option == '3'):
        x = input("Insira o novo valor: ")
        set_configs('trainset', x)
        menu()
    elif (option == '4'):
        x = input("Insira o novo valor: ")
        set_configs('testset', x)
        menu()
    elif (option == '5'):
        x = input("Insira o novo valor: ")
        set_configs('epochs', x)
        menu()
    elif (option == '6'):
        return
    else:
        menu(True)