def plot(matriz,
         legends,
         benchmark=None,
         titulo='',
         titulo_x='',
         titulo_y='',
         salvar=False,
         limites=(0, 0),
         dir=''):
    x = [i for i in range(1, len(matriz[0]) + 1)]
    fig = plt.figure()
    ax = fig.add_subplot(111)
    plt.plot(x, matriz[0], '-.o', label=legends[0])
    plt.plot(x, matriz[1], ':x', label=legends[1])
    plt.plot(x, matriz[2], '--', label=legends[2])

    lgd = plt.legend(loc=2, borderaxespad=0., bbox_to_anchor=(1.05, 1))
    plt.title(titulo)
    plt.xlabel(titulo_x)
    plt.ylabel(titulo_y)

    ax.set_ylim(
        Benchmark.info(benchmark)[3][0] + limites[0],
        Benchmark.info(benchmark)[3][0] + limites[1])
    if salvar:
        plt.savefig(dir + titulo + '.pdf')
        plt.savefig(dir + titulo + '.pdf',
                    bbox_extra_artists=(lgd, ),
                    bbox_inches='tight')
    plt.show()
    def salvar_resultados_teste(self, dir, titulo, melhores, geracoes_finais,
                                Max, Avg, Min, nao_convergidos):
        file = open(dir + '/' + titulo + '.txt', 'w')
        file.write('Resultados do Teste: ' + titulo + '\n')

        file.write('\nAtributos do Teste: \n')
        file.write('    Benchmark = ' + Benchmark.info(self.benchmark)[4] +
                   '\n')
        file.write('    Número de Testes = ' + str(self.num) + '\n')
        file.write('    Número de Testes não convergidos= ' +
                   str(nao_convergidos) + '\n')

        Media, dp, va = media(melhores)
        file.write('\nMelhores Individuos: \n')
        file.write('    ' + str(melhores) + '\n')
        file.write('    Media = ' + str(Media) + '\n')
        file.write('    Desvio Padrão = ' + str(dp) + '\n')
        file.write('    Variância = ' + str(va) + '\n')
        Media, dp, va = media(geracoes_finais)
        file.write('\nGerações Finais: \n')
        file.write('    ' + str(geracoes_finais) + '\n')
        file.write('    Media = ' + str(Media) + '\n')
        file.write('    Desvio Padrão = ' + str(dp) + '\n')
        file.write('    Variância = ' + str(va) + '\n')
        file.close()

        print('Arquivo Salvo em: ' + dir + '/' + titulo + '.txt')
def FluidGA(benchmark=Benchmark.rastrigin,
            tam_entradas=24,
            num_entradas=2,
            max_geracoes=250,
            populacao_inicial=100,
            prob_mut=0.2,
            prob_p_flip_bit=0.05,
            prob_p_cruz=0.5,
            tam_torneio=3):

    lim_min, lim_max, pesos, solucoes, str_benchmark = Benchmark.info(
        benchmark)

    creator.create("avaliacao", base.Fitness,
                   weights=pesos)  ##setando objetivo das avaliacoes ###

    creator.create("Individuo", list,
                   fitness=creator.avaliacao)  ##Criando tipo de Individuos

    toolbox = base.Toolbox()  ## Instanciando objeto Toolbox

    toolbox.register(
        "ini_gene", random.randint, 0,
        1)  ## registrando ferramenta para pegar bit ramdomico (0 ou 1)

    tam = tam_entradas * num_entradas

    toolbox.register(
        "individuo", tools.initRepeat, creator.Individuo, toolbox.ini_gene, tam
    )  ## registrando ferramenta para criar individuo com 48 bits apartir da ferramenta "ini_gene"

    toolbox.register(
        "populacao", tools.initRepeat, list, toolbox.individuo
    )  ##registrando ferramenta para criar populacao com base na ferramenta "individuo"

    indiv = Benchmark.Benchmark(
        num_entradas, tam_entradas, lim_min, lim_max,
        benchmark)  ##Instanciando Objeto para Benchmark

    toolbox.register(
        "avaliacao", indiv.fitness
    )  ##registrando ferramenta para avaliar com base na nossa função fitness do Objeto Benchmark

    #toolbox.register("crusar", tools.cxTwoPoint)  ##registrando ferramenta para crusar dois individuos

    #toolbox.register("mutar", tools.mutFlipBit, indpb=prob_p_flip_bit)  ##registrando ferramenta para mutar individuos com chance de mutação de 5%

    toolbox.register(
        "selecionar", tools.selTournament, tournsize=tam_torneio
    )  ##registrando ferramenta para selecionar pais em um torneio.

    toolbox.register(
        "selecao_elitista", tools.selBest
    )  ##registrando ferramenta para selecionar pais de forma totalmente elitista.

    return run_Fluid(toolbox, populacao_inicial, max_geracoes, pesos, solucoes,
                     tam)
def salvar_resultados(titulo, entrada, GAs, benchmark, dir=''):
    dir = criar_dir(dir + 'Test - ' + titulo)
    file = open(dir + '/' + titulo + '_info' + '.csv', 'w')
    file.write('Resultados do Teste:, ' + titulo + '\n')

    file.write('\nAtributos do Teste: \n')
    file.write('Benchmark ,' + Benchmark.info(benchmark)[4] + '\n')
    file.write('Número de Testes ,' + str(len(entrada[0])) + '\n')

    file.write('\n\nAlgoritimo, Média, Desvio Padrão, Variância\n')
    for i in range(len(entrada)):
        med, desv, var = media(entrada[i])
        file.write(
            str(GAs[i]) + ',' + str(med) + ',' + str(desv) + ',' + str(var) +
            '\n')

    file.close()

    print('Arquivo Salvo em: ' + dir + '/' + titulo + '_info' + '.csv')
    def teste(self):
        melhores = []
        geracoes_finais = []
        nao_convergidos = 0
        for i in range(self.num):
            print('Fazendo Teste Número ({})'.format(i))
            if (self.algoritmo == TrangenicGA.trangenicGA):
                melhor, geracao_f, Max, Avg, Min = self.algoritmo(
                    self.benchmark, self.tam_entradas, self.num_entradas,
                    self.max_geracoes, self.populacao_inicial, self.prob_mut,
                    self.prob_p_flip_bit, self.prob_p_cruz, self.tam_torneio,
                    self.fator_aprox_histo)
                melhores.append(melhor)
                geracoes_finais.append(geracao_f)
                if geracao_f == self.max_geracoes:
                    nao_convergidos = nao_convergidos + 1
                titulo, eixo_x_M, eixo_y_M, eixo_x_G, eixo_y_G = 'Transgenic GA with ' + Benchmark.info(
                    self.benchmark
                )[4], 'Number of the Test', 'Evaluation of the Best Individual', 'Number of the Test', 'Final Generation'
            elif self.algoritmo == Theory_Of_ChaosGA.chaosGA:
                melhor, geracao_f, Max, Avg, Min = self.algoritmo(
                    self.benchmark, self.tam_entradas, self.num_entradas,
                    self.max_geracoes, self.populacao_inicial, self.prob_mut,
                    self.prob_p_flip_bit, self.tam_torneio)
                melhores.append(melhor)
                geracoes_finais.append(geracao_f)
                if geracao_f == self.max_geracoes:
                    nao_convergidos = nao_convergidos + 1
                titulo, eixo_x_M, eixo_y_M, eixo_x_G, eixo_y_G = 'Theory of Chaos GA with ' + Benchmark.info(
                    self.benchmark
                )[4], 'Number of the Test', 'Evaluation of the Best Individual', 'Number of the Test', 'Final Generation'
            elif self.algoritmo == GABasico.GAbasico:

                melhor, geracao_f, Max, Avg, Min = self.algoritmo(
                    self.benchmark, self.tam_entradas, self.num_entradas,
                    self.max_geracoes, self.populacao_inicial, self.prob_mut,
                    self.prob_p_flip_bit, self.prob_p_cruz, self.tam_torneio)
                melhores.append(melhor)
                geracoes_finais.append(geracao_f)
                if geracao_f == self.max_geracoes:
                    nao_convergidos = nao_convergidos + 1
                titulo, eixo_x_M, eixo_y_M, eixo_x_G, eixo_y_G = 'Basic GA with ' + Benchmark.info(
                    self.benchmark
                )[4], 'Number of the Test', 'Evaluation of the Best Individual', 'Number of the Test', 'Final Generation'
            elif self.algoritmo == HomogeneousGA.homogeneousGA:
                melhor, geracao_f, Max, Avg, Min = self.algoritmo(
                    self.benchmark, self.tam_entradas, self.num_entradas,
                    self.max_geracoes, self.populacao_inicial, self.prob_mut,
                    self.prob_p_flip_bit, self.prob_p_cruz, self.tam_torneio,
                    self.fator_aprox_histo)
                melhores.append(melhor)
                geracoes_finais.append(geracao_f)
                if geracao_f == self.max_geracoes:
                    nao_convergidos = nao_convergidos + 1
                titulo, eixo_x_M, eixo_y_M, eixo_x_G, eixo_y_G = 'Transgenic GA with ' + Benchmark.info(
                    self.benchmark
                )[4], 'Number of the Test', 'Evaluation of the Best Individual', 'Number of the Test', 'Final Generation'
            elif self.algoritmo == FluidGA.FluidGA:
                melhor, geracao_f, Max, Avg, Min = self.algoritmo(
                    self.benchmark, self.tam_entradas, self.num_entradas,
                    self.max_geracoes, self.populacao_inicial, self.prob_mut,
                    self.prob_p_flip_bit, self.prob_p_cruz, self.tam_torneio)
                melhores.append(melhor)
                geracoes_finais.append(geracao_f)
                if geracao_f == self.max_geracoes:
                    nao_convergidos = nao_convergidos + 1
                titulo, eixo_x_M, eixo_y_M, eixo_x_G, eixo_y_G = 'Basic GA with ' + Benchmark.info(
                    self.benchmark
                )[4], 'Number of the Test', 'Evaluation of the Best Individual', 'Number of the Test', 'Final Generation'
        dir = 'Test - ' + titulo
        if self.salvar:
            dir = criar_dir(dir)
            self.salvar_resultados_teste(dir, titulo, melhores,
                                         geracoes_finais, Max, Avg, Min,
                                         nao_convergidos)
        self.plot(melhores, "Best Individuals - " + titulo, eixo_x_M, eixo_y_M,
                  self.salvar, dir)
        self.plot(geracoes_finais, "Final Generations - " + titulo, eixo_x_G,
                  eixo_y_G, self.salvar, dir)
        return melhores, geracoes_finais, nao_convergidos
Exemple #6
0
# ---------------------------------------------------------------------------------------------------- #

benchmark = Benchmark.schaffer

Basic = Teste(100, GABasico.GAbasico, False)
Basic.config_basico(benchmark=benchmark, max_geracoes=250)
mbi1, mgf1, nc1 = Basic.teste()

Theory = Teste(100, Theory_Of_ChaosGA.chaosGA, False)
Theory.config_chaos(benchmark=benchmark, max_geracoes=250)
mbi2, mgf2, nc2 = Theory.teste()

Trans = Teste(100, TrangenicGA.trangenicGA, False)
Trans.config_trans(benchmark=benchmark, max_geracoes=250)
mbi3, mgf3, nc3 = Trans.teste()

l = ['Basic GA', 'Theory of Chaos GA', 'Transgenic GA']
#mgf = [mgf1, mgf2, mgf3]
mbi = [mbi1, mbi2, mbi3]

#plot(mgf, l, 'Final Generation with ' + Benchmark.info(benchmark)[4], benchmark, 'Execution Number', 'Final Generation', True)
plot(mbi, l, benchmark,
     'Best Individuals with ' + Benchmark.info(benchmark)[4],
     'Execution Number', 'Best Individuals Fitness', True, (-0.01, 0.1))
salvar_resultados('Melhores Individuos com ' + Benchmark.info(benchmark)[4],
                  mbi, ['Basic GA', 'Theory of Chaos GA', 'Trangenic GA'],
                  benchmark)

# -------------------------------------------------------------------------------------------------- #