def tournamentSelectionWithCrossover(self) -> Population:
     fighters: List[Sentence] = self.population.sentences.copy()
     winners: List[Sentence] = []
     childs: List[Sentence] = []
     while len(fighters) > 0:
         fighterIndex1: int = random.randrange(0, len(fighters))
         fighter1: Sentence = fighters[fighterIndex1]
         fighters.remove(fighter1)
         fighterIndex2: int = random.randrange(0, len(fighters))
         fighter2: Sentence = fighters[fighterIndex2]
         fighters.remove(fighter2)
         if fighter1.fitness > fighter2.fitness:
             winners.append(fighter1)
         else:
             winners.append(fighter2)
     random.shuffle(winners)
     while len(winners) > 0:
         childs.append(Crossover(winners[0], winners[1]).crossover())
         childs.append(Crossover(winners[1], winners[0]).crossover())
         winners.remove(winners[0])
         winners.remove(winners[0])
     newSentences: List[Sentence] = childs
     for s in newSentences:
         s.mutate(configuration.MUTATION_RATE)
     self.population.sortByFitness()
     originalSize: int = len(self.population.sentences)
     while len(newSentences) < originalSize:
         newSentences.append(self.population.sentences[0])
         self.population.sentences.remove(self.population.sentences[0])
     newPopulation: Population = Population()
     newPopulation.createByList(newSentences, self.target)
     return newPopulation
Exemplo n.º 2
0
def cross_trees(population):
    result_trees = []
    parent1 = choice(population)
    parent2 = choice(population)
    j = randint(1, CROSS_PROBABILITY)
    if j <= 9:
        cr = Crossover(parent1, parent2)
        if cr.cross():
            result_trees.append(cr.new_tree1)
            result_trees.append(cr.new_tree2)
    return result_trees
Exemplo n.º 3
0
    def next_generation(self, population):
        selection = Selection(deepcopy(population),
                              strategy=SelectionStrategy.TOURNAMENT.value)
        selection.apply()
        mating = Mating(selection)
        mating.apply()
        crossover = Crossover(mating)
        crossover.apply()

        for i, individual in enumerate(
                crossover.mating.selection.population.individuals):
            mutation = Mutation(individual)
            crossover.mating.selection.population.individuals[
                i] = mutation.mutate()

        print(f'Individuals: {len(self.individuals)}')
        print(f'New generation: {len(crossover.new_generation)}')
        return crossover.mating.selection.population
Exemplo n.º 4
0
def generate_child(parent_a, parent_b, mutation_probability):
    child_a_chromosome, child_b_chromosome = Crossover.cut_and_crossfill(
        parent_a.chromosome, parent_b.chromosome)
    child_a = Individual(chromosome=child_a_chromosome)
    child_b = Individual(chromosome=child_b_chromosome)

    if should_event_happen(mutation_probability):
        child_a.mutate()

    if should_event_happen(mutation_probability):
        child_b.mutate()

    return child_a, child_b
    def createChildren(self, parents):
        roulette = Roulette(parents)
        children = []
        for _ in range(5):
            parent_1 = roulette.select_parent()
            parent_2 = roulette.select_parent()
            new_children = Crossover(parent_1, parent_2).generate_children()
            Mutation(new_children[0]).mutate()
            Mutation(new_children[1]).mutate()
            children.append(new_children[0])
            children.append(new_children[1])

        return children
 def createChildren(self, parents):
     # Cria a roleta
     roulette = Roulette(parents)
     children = []
     # Cria 10 filhos
     for _ in range(5):
         parent_1 = roulette.select_parent()
         parent_2 = roulette.select_parent()
         new_children = Crossover(parent_1, parent_2).generate_children()
         # Realiza a mutação nos filhos (respeitando a proporcionalidade)
         Mutation(new_children[0]).mutate()
         Mutation(new_children[1]).mutate()
         children.append(new_children[0])
         children.append(new_children[1])
         
     return children
Exemplo n.º 7
0
creator.create("Individual", Individual, fitness=creator.FitnessMax)

toolbox = base.Toolbox()

# Structure initializers
toolbox.register("individual", initIndividual, creator.Individual)
toolbox.register("population", tools.initRepeat, list, toolbox.individual)

# use multiple processors 
pool = multiprocessing.Pool(5)
toolbox.register("map", pool.map)

# register operators 
fit = Fitness("data/"+trainset_name)
mut = Mutation()
cross = Crossover()

toolbox.register("evaluate", fit.evaluate)
toolbox.register("mate", cross.cxOnePoint)
toolbox.register("mutate", mut.mutate)
toolbox.register("select", tools.selTournament, tournsize=3)

def main(id, checkpoint_name=None):
    # random.seed(64)

    if checkpoint_name:
        # A file name has been given, then load the data from the file
        cp = pickle.load(open(checkpoint_name, "rb"))
        pop = cp["population"]
        start_gen = cp["generation"] + 1
        hof = cp["halloffame"]
Exemplo n.º 8
0
    def GA(self, seed):
        global mutex
        global newIndividuals
        split = splitAl()
        np.random.seed(seed)
        # define população inicial
        pop = Population()
        population = pop.definePopulation(config.SIZE_POP)

        def minor(x, y):
            return x if x.get_cost() < y.get_cost() else y

        best = 0
        bestPrev = 0
        cont = 0
        timeControl = 0
        threads = []
        level = 2
        # avalie a população

        # critério de parada
        i = 0
        timeIni = time.time()
        while i < config.GEN and cont <= 2 * config.GEN_NO_EVOL and timeControl < config.TIME_TOTAL:
            tAllIni = time.time()
            bestPrev = best
            tLS = 0

            # sizePopulation = len(population)
            descendant = []
            for j in range(round(config.SIZE_DESC / 2)):
                tGenIni = time.time()
                selProbalities = pop.get_selProbabilities(
                )  # probabilidade de seleção
                # print("prob: "+str(len(selProbalities)))

                # selecione os pais

                aux = np.random.choice(population,
                                       2,
                                       replace=False,
                                       p=selProbalities)

                P1 = minor(aux[0], aux[1])

                aux = np.random.choice(population,
                                       2,
                                       replace=False,
                                       p=selProbalities)

                P2 = minor(aux[0], aux[1])

                # Crossover

                rand = np.random.random_sample()
                # print(rand)
                # print(P1)
                # print(P2)
                children = []

                if rand > 0.5:
                    children = cross.OBX1(copy.deepcopy(P1), copy.deepcopy(P2))
                else:
                    children = cross.PMX1(copy.deepcopy(P1), copy.deepcopy(P2))
                # print("children: \n")
                # print(children)
                # for a in range(2):
                #     for e1, c1 in enumerate(children[a].get_giantTour()):
                #         for e2, c2 in enumerate(children[a].get_giantTour()):
                #             if e1 != e2 and c1 == c2:
                #                 print("Elementos iguais")
                #                 exit(1)

                # Mutação

                # duas threads
                modChildren = []
                with concurrent.futures.ThreadPoolExecutor(
                        max_workers=2) as executor:
                    future_to_child = {
                        executor.submit(Mutation.mutation1, child, level):
                        child
                        for child in children
                    }
                    for future in concurrent.futures.as_completed(
                            future_to_child):
                        child = future_to_child[future]
                        try:
                            indiv = future.result()
                            modChildren.append(indiv)
                        except Exception as exc:
                            print('%s gerou uma exceção na busca local: %s' %
                                  (str(child), exc))

                # split
                # cluster = SplitDepots.splitByDepot(modChildren[0])
                # print(cluster)
                individual1 = split.splitLinear(modChildren[0], True)
                # individual1 = split.mountRoutes(cluster)
                # cluster = SplitDepots.splitByDepot(modChildren[1])
                # print(cluster)
                individual2 = split.splitLinear(modChildren[1], True)
                # individual2 = split.mountRoutes(cluster)

                individuals = [individual1, individual2]

                # print("individual: ")
                # print(individual1)
                # print(individual2)
                for a in range(2):
                    for ii, c1 in enumerate(individuals[a].get_giantTour()):
                        for jj, c2 in enumerate(
                                individuals[a].get_giantTour()):
                            if ii != jj and c1 == c2:
                                print("Elementos iguais na mutação")
                                exit(1)

                # Busca Local
                ILS = ils()
                # solutions = ILS.ils(individual1, 25)
                # for ii, c1 in enumerate(solutions.get_giantTour()):
                #     for jj, c2 in enumerate(solutions.get_giantTour()):
                #         if ii != jj and c1 == c2:
                #             print("Elementos iguais na ils")
                #             exit(1)

                # exit(1)
                # duas threads
                ini = time.time()
                modIndividuals = []
                LS = ls()
                individuals.append(P1)
                individuals.append(P2)
                # modIndividuals.append(LS.LS(individuals[0]))
                # modIndividuals.append(LS.LS(individuals[1]))
                with concurrent.futures.ThreadPoolExecutor(
                        max_workers=2) as executor:
                    # future_to_individual = {executor.submit(
                    #     LS.LS, ind, nMovimentations='random', where='ls', timeIni=tGenIni): ind for ind in individuals}
                    # future_to_individual = {executor.submit(
                    #     ILS.ils, ind, config.GEN_ILS, timeIni=tGenIni, timeMax=config.TIME_GEN): ind for ind in individuals}
                    future_to_individual = {
                        executor.submit(self.localSearch,
                                        ind,
                                        prob=config.PROB_LS,
                                        nMovimentations='random',
                                        timeIni=tGenIni): ind
                        for ind in individuals
                    }
                    for future in concurrent.futures.as_completed(
                            future_to_individual):
                        ind = future_to_individual[future]
                        try:
                            indiv = future.result()
                            modIndividuals.append(indiv)
                        except Exception as exc:
                            print('%s gerou uma exceção na busca local: %s' %
                                  (str(ind), exc))
                            traceback.print_exc()
                # print(future_to_individual)
                # print(individuals[0])
                # print(modIndividuals)
                tTotal = time.time() - ini
                tLS += tTotal
                for a in range(2):
                    for e1, c1 in enumerate(modIndividuals[a].get_giantTour()):
                        for e2, c2 in enumerate(
                                modIndividuals[a].get_giantTour()):
                            if e1 != e2 and c1 == c2:
                                print("Elementos iguais na busca local")
                                exit(1)

                # avalie a população

                for a in range(2):
                    # indivíduo diferente do resto da população
                    if self.is_different(modIndividuals[a], descendant):
                        descendant.append(modIndividuals[a])

            # inserir descendentes à população

            for desc in descendant:
                if pop.is_different(desc):
                    pop.addIndividual(desc)

            # inserir indivíduos da lista newIndividuals (se existir) à população

            # início seção crítica
            mutex.acquire()
            # print("verificar lista")
            # print(newIndividuals)
            if newIndividuals:
                # print("novo: "+ str(len(newIndividuals)))
                for ni in newIndividuals:
                    if pop.is_different(ni):
                        pop.addIndividual(ni)
                newIndividuals = []
            mutex.release()
            # fim seção crítica

            pop.sortPopulation()
            population = pop.get_population()

            # promoção - busca local first improvement de 10% da população
            ini = time.time()
            p = max(round(config.SIZE_POP * 0.1), 1)  # 10% da população
            LSBetter = lsb()

            modIndividuals = []
            individuals = []
            selProbalities = pop.get_selProbabilities(
            )  # probabilidade de seleção
            individuals = np.random.choice(population,
                                           p,
                                           replace=False,
                                           p=selProbalities)
            individuals = np.append(individuals, pop.showBestSolution())

            with concurrent.futures.ThreadPoolExecutor(
                    max_workers=4) as executor:
                # future_to_individual = {executor.submit(
                #     LSBetter.LS, ind, where='ls', timeIni=tGenIni): ind for ind in individuals}
                future_to_individual = {
                    executor.submit(self.localSearch,
                                    ind,
                                    prob=config.PROB_LS_BEST,
                                    nMovimentations='all',
                                    timeIni=tGenIni): ind
                    for ind in individuals
                }
                # future_to_individual = {executor.submit(
                #     ILS.ils, ind, config.N_REPETITIONS, timeIni=tGenIni, timeMax=config.TIME_GEN): ind for ind in individuals}
                for future in concurrent.futures.as_completed(
                        future_to_individual):
                    ind = future_to_individual[future]
                    try:
                        indiv = future.result()
                        modIndividuals.append(indiv)
                    except Exception as exc:
                        print(
                            '%s gerou uma exceção na busca local - promoção: %s'
                            % (str(ind), exc))
                        traceback.print_exc()

            # avalie a população

            for a in modIndividuals:

                # for e1, c1 in enumerate(a.get_giantTour()):
                #     for e2, c2 in enumerate(a.get_giantTour()):
                #         if e1 != e2 and c1 == c2:
                #             print("Elementos iguais na busca local - promoção")
                #             exit(1)

                # indivíduo diferente do resto da população
                if pop.is_different(a):
                    pop.addIndividual(a)

            tTotalP = time.time() - ini

            pop.sortPopulation()

            # defina a população sobrevivente

            best = pop.defineSurvivors(config.SIZE_POP)
            population = pop.get_population()

            # busca local exaustiva assícrona - best improvemment dos dois melhores indivíduos

            individuals = []
            selProbalities = pop.get_selProbabilities(
            )  # probabilidade de seleção
            individuals = np.random.choice(population, 1, p=selProbalities)
            individuals = np.append(individuals, pop.showBestSolution())
            individuals = np.append(individuals, pop.showSecondBestSolution())

            # cria threads
            for individual in individuals:
                if np.random.random_sample() < config.PROB_LS_BEST_P:
                    if th.active_count(
                    ) < 4:  # máximo 3 threads agindo de forma assíncrona
                        a = MyThread(individual, timeIni)  # inicializa thread
                        a.start()
                        threads.append(a)

            # verifica número de gerações sem melhoras

            if round(bestPrev, 9) == round(best, 9):
                cont += 1
                level += 1

                # config.SOFT_VEHICLES = True
            else:
                cont = 0
                level = 2
                # config.SOFT_VEHICLES = False

            if cont > config.GEN_NO_EVOL:
                mt = ils()
                individualM = mt.pertubation(
                    copy.deepcopy(pop.showBestSolution()), level)
                pop.addIndividual(individualM)
                pop.sortPopulation()
                aux = 0

                # verifica se há solutions na lista newIndividuos

                # início seção crítica
                mutex.acquire()
                if newIndividuals:
                    aux = 1
                    for ni in newIndividuals:
                        if pop.is_different(ni):
                            pop.addIndividual(ni)
                    pop.sortPopulation()
                newIndividuals = []
                mutex.release()
                # fim seção crítica

                if aux >= 0:
                    best = pop.defineSurvivors(config.SIZE_POP)
                    if round(bestPrev, 9) != round(best, 9):
                        cont = 0

                # print("ALERTA POPULAÇÃO PAROU DE EVOLUIR")
                # print(pop.get_population())
                # logging.debug("ALERTA POPULAÇÃO PAROU DE EVOLUIR")

            pop.sortPopulation()
            population = pop.get_population()
            tAll = time.time() - tAllIni  # tempo da geração
            timeControl = time.time() - timeIni  # tempo total

            # print("GERAÇÃO: {} - Custo: {} - Tempo LS: {} - Tempo LS Promotion: {} - Tempo Total: {}".format(i,
            #  pop.showBestSolution().get_cost(), tLS/60, tTotalP/60, tAll/60))
            # logging.debug("GERAÇÃO: {} - Custo: {} - Tempo LS: {} - Tempo LS Promotion: {} - Tempo Total: {}".format(i,
            #                                                                                                          pop.showBestSolution().get_cost(), tLS/60, tTotalP/60, tAll/60))
            i += 1

        # finalizar thread se ultrapassar o tempo limite.
        if (time.time() - timeIni) >= config.TIME_TOTAL:
            for t in threads:
                t.stop()
        else:
            for t in threads:
                t.join()

        # verificar se há indivíduos na lista newIndividuals
        if newIndividuals:
            for ni in newIndividuals:
                if pop.is_different(ni):
                    pop.addIndividual(ni)
        newIndividuals = []

        # ordena população
        pop.sortPopulation()
        # print(pop.showBestSolution().get_routes())
        # print(pop.showBestSolution().get_cost())
        # print(pop.showBestSolution().get_nRoutesByDepot())
        # self.test(pop.showBestSolution())

        # retorna melhor indivíduo
        return pop.showBestSolution()
Exemplo n.º 9
0
toolbox.register("individual", initIndividual, creator.Individual)
toolbox.register("population", tools.initRepeat, list, toolbox.individual)

# use multiple processors or GPU
if config.global_config["device"]["device_type"] == "CPU":
    n_cpus = config.global_config["device"]["n_cpus"]
    pool = multiprocessing.Pool(n_cpus)
    toolbox.register("map", pool.map)
    logging.info(f"Running on {n_cpus} CPUs")
else:
    logging.info(f"Running on GPU.")

# register operators
fit = Fitness(**config.global_config["dataset"])
mut = MutationConv() if use_conv_layers else Mutation()
cross = CrossoverConv() if use_conv_layers else Crossover()

toolbox.register("eval_batch", fit.evaluate_batch)
toolbox.register("evaluate", fit.evaluate)
toolbox.register("mate", cross.cxOnePoint)
toolbox.register("mutate", mut.mutate)
if nsga_number == 3:
    ref_points = tools.uniform_reference_points(2, 12)
    toolbox.register("select", tools.selNSGA3, ref_points=ref_points)
elif nsga_number == 2:
    # nsgaII - deap implementation
    toolbox.register("select", tools.selNSGA2)
elif nsga_number == 1:
    # stepan's version of nsga
    toolbox.register("select", selectNSGA)
elif nsga_number == 0:
Exemplo n.º 10
0
import random
import numpy as np

from math import sin, cos, pi

from population import Population
from selection import Selection
from crossover import Crossover
from mutation import Mutation
from toolkits import GAEngine

f = lambda x, y: y * sin(2 * pi * x) + x * cos(2 * pi * y)

population = Population(100, [-2, 2], [-2, 2]).init()
selection = Selection(f, 100)
crossover = Crossover(pe=0.5)
mutation = Mutation([-2, 2], [-2, 2], pm=0.5)

engine = GAEngine(population, selection, crossover, mutation)

if '__main__' == __name__:
    engine.run(200)
Exemplo n.º 11
0
    populacao = list(filter(lambda x: x != -1, populacao))
    valores_indv = list(filter(lambda x: x != -1, valores_indv))

    elite = Elitismo.escolher(populacao, valores_indv, elitismo)

    if (metd_sel == 'roleta'):
        aptos = Selecao.roleta(populacao, valores_indv)
    elif (metd_sel == 'torneio'):
        aptos = Selecao.torneio(populacao, valores_indv, 3)

    if aptos == None:
        break

    aptos.extend(elite)

    populacao = Crossover.crossover(aptos, corte_pos, tam_pop)
    Mutacao.mutar(populacao, tax_mut)
    valores_indv = funcAptidao(populacao)

    print('\nGeração:', geracao)
    f.write('\nGeração:')
    f.write(str(geracao))
    f.write('\n')

    for i in range(len(populacao)):
        print(populacao[i], valores_indv[i])
        f.write(str(populacao[i]))
        f.write(str(valores_indv[i]))
        f.write('\n')
Exemplo n.º 12
0
    def GA(self,seed):
        global mutex
        global newIndividuals
        np.random.seed(seed)
        # define população inicial
        pop = Population()
        population = pop.definePopulation(config.SIZE_POP)
        def minor(x, y): return x if x.get_cost() < y.get_cost() else y
        best = 0
        bestPrev = 0
        controlPop = True
        controlPopPrev = True
        sumControl = 0
        cont = 0
        timeControl = 0
        threads = []
        # avalie a população

        # critério de parada
        i = 0
        while i < config.GEN and cont <= config.GEN_NO_EVOL and timeControl < config.TIME_TOTAL :
            tAllIni = time.time()
            bestPrev = best
            controlPopPrev = controlPop
            tLS = 0

            #sizePopulation = len(population)
            descendant = []
            for j in range(round(config.SIZE_DESC/2)):
                controlPop = True
                selProbalities = pop.get_selProbabilities() # probabilidade de seleção
                # print("pop: "+str(len(population)))
                # print("prob: "+str(len(selProbalities)))
                # selecione os pais
                aux = np.random.choice(population,2,replace=False,p=selProbalities)

                # aux1 = population[np.random.randint(len(population))]
                # aux2 = population[np.random.randint(len(population))]

                P1 = minor(aux[0], aux[1])

                aux = np.random.choice(population,2,replace=False,p=selProbalities)
                # aux1 = population[np.random.randint(len(population))]
                # aux2 = population[np.random.randint(len(population))]
                P2 = minor(aux[0], aux[1])

                # Crossover

                rand = np.random.random()
                # print(rand)
                # print(P1)
                # print(P2)
                children = []
                if rand > 0.5:
                    children = cross.OBX(copy.deepcopy(P1), copy.deepcopy(P2))
                else:
                    children = cross.PMX(copy.deepcopy(P1), copy.deepcopy(P2))
                # print("child: \n")
                # print(child)
                # for a in range(2):
                #     for e1, c1 in enumerate(children[a]):
                #         for e2, c2 in enumerate(children[a]):
                #             if e1 != e2 and c1 == c2:
                #                 print("Elementos iguais")
                #                 exit(1)

                # Mutação

                # duas threads
                modChildren =  []
                with concurrent.futures.ThreadPoolExecutor(max_workers=2) as executor:
                    future_to_child = {executor.submit(Mutation.mutation,child): child for child in children}
                    for future in concurrent.futures.as_completed(future_to_child):
                        child = future_to_child[future]
                        try:
                            indiv = future.result()
                            modChildren.append(indiv)
                        except Exception as exc:
                            print('%s gerou uma exceção na busca local: %s' % (str(child), exc))

                # split
                cluster = SplitDepots.splitByDepot(modChildren[0])
                # print(cluster)
                individual1 = split.splitLinear(cluster)
                cluster = SplitDepots.splitByDepot(modChildren[1])
                # print(cluster)
                individual2 = split.splitLinear(cluster)

                individuals = [individual1, individual2]

                # print("individual: ")
                # print(individual1)
                # print(individual2)
                for a in range(2):
                    for ii, c1 in enumerate(individuals[a].get_giantTour()):
                        for jj, c2 in enumerate(individuals[a].get_giantTour()):
                            if ii != jj and c1 == c2:
                                print("Elementos iguais na mutação")
                                exit(1)

                # Busca Local
                
                # duas threads
                ini = time.time()
                modIndividuals =  []
                LS = ls()
                # modIndividuals.append(LS.LS(individuals[0]))
                # modIndividuals.append(LS.LS(individuals[1]))
                with concurrent.futures.ThreadPoolExecutor(max_workers=2) as executor:
                    future_to_individual = {executor.submit(LS.LS,ind,nMovimentations='random' ,where='ls'): ind for ind in individuals}
                    for future in concurrent.futures.as_completed(future_to_individual):
                        ind = future_to_individual[future]
                        try:
                            indiv = future.result()
                            modIndividuals.append(indiv)
                        except Exception as exc:
                            print('%s gerou uma exceção na busca local: %s' % (str(ind), exc))
                            traceback.print_exc()
                # print(future_to_individual)
                # print(individuals[0])
                # print(modIndividuals)
                # exit(1)
                tTotal = (time.time() - ini)/60
                tLS += tTotal
                for a in range(2):
                    for e1, c1 in enumerate(modIndividuals[a].get_giantTour()):
                        for e2, c2 in enumerate(modIndividuals[a].get_giantTour()):
                            if e1 != e2 and c1 == c2:
                                print("Elementos iguais na busca local")
                                exit(1)
                # exit(1)
                # avalie a população
                for a in range(2):
                    # indivíduo diferente do resto da população
                    if self.is_different(modIndividuals[a],descendant):
                        #pop.addIndividual(modIndividuals[a])
                        descendant.append(modIndividuals[a])

                # pop.sortPopulation()
                # population = pop.get_population()
            # inserir descendentes à população
            for desc in descendant:
                if pop.is_different(desc):
                    pop.addIndividual(desc)
            
            # inserir indivíduos da lista newIndividuals (se existir) à população

            #início seção crítica
            mutex.acquire()
            # print("verificar lista")
            # print(newIndividuals)
            if newIndividuals:
                # print("novo: "+ str(len(newIndividuals)))
                for ni in newIndividuals:
                    if pop.is_different(ni):
                        # print("achou assíncrona")
                        pop.addIndividual(ni)
                newIndividuals = []
            mutex.release()
            #fim seção crítica
            
            pop.sortPopulation()
            population = pop.get_population()
            # promoção

            p = max(round(config.SIZE_POP * 0.1),1) #10% da população
            LSBetter = ls()
         
            modIndividuals =  []
            individuals = []
            selProbalities = pop.get_selProbabilities() # probabilidade de seleção
            individuals = np.random.choice(population,p,replace=False,p=selProbalities)
            individuals = np.append(individuals, pop.showBestSolution())
            with concurrent.futures.ThreadPoolExecutor(max_workers=4) as executor:
                    future_to_individual = {executor.submit(LSBetter.LS,ind,where='ls'): ind for ind in individuals}
                    for future in concurrent.futures.as_completed(future_to_individual):
                        ind = future_to_individual[future]
                        try:
                            indiv = future.result()
                            modIndividuals.append(indiv)
                        except Exception as exc:
                            print('%s gerou uma exceção na busca local - promoção: %s' % (str(ind), exc))
                            traceback.print_exc()
            #exit(1)
            # avalie a população
            for a in modIndividuals:

                for e1, c1 in enumerate(a.get_giantTour()):
                        for e2, c2 in enumerate(a.get_giantTour()):
                            if e1 != e2 and c1 == c2:
                                print("Elementos iguais na busca local - promoção")
                                exit(1)

                # indivíduo diferente do resto da população
                if pop.is_different(a):
                    pop.addIndividual(a)

            tTotalP = (time.time() - ini)/60

            pop.sortPopulation()

            # defina a população sobrevivente
            best = pop.defineSurvivors(config.SIZE_POP)
            population = pop.get_population()
            
            #busca local exaustiva - best improvemment
            # p = 3 # 3 threads
            individuals = []
            # selProbalities = pop.get_selProbabilities() # probabilidade de seleção
            # individuals = np.random.choice(population,(p-1),replace=False,p=selProbalities)
            individuals = np.append(individuals, pop.showBestSolution())
            individuals = np.append(individuals, pop.showSecondBestSolution())
            
            # cria threads 
            for individual in individuals:
                if np.random.random() < config.PROB_LS_BEST:
                    if th.active_count()<4: # máximo 3 threads agindo de forma assíncrona
                        a = MyThread(individual) #inicializa thread
                        a.start()
                        threads.append(a)
            
            if round(bestPrev,9) == round(best,9):
                cont += 1
            else:
                cont = 0
            # if sumControl > config.CONT_METRIC:
            #     # idum = i * seed
            #     population = pop.changePopulation()
            #     sumControl = 0
            if cont > config.GEN_NO_EVOL:
                # population = pop.changePopulation()
                # cont = 0
                print("ALERTA POPULAÇÃO PAROU DE EVOLUIR")
            pop.sortPopulation()
            population = pop.get_population()
            tAll = (time.time() - tAllIni)/60
            timeControl += tAll

            print("GERAÇÃO: {} - Custo: {} - Tempo LS: {} - Tempo LS Promotion: {} - Tempo Total: {}".format(i,
                                                   pop.showBestSolution().get_cost(),tLS,tTotalP,tAll))

            i += 1


        print("th.active_count(): "+str(th.active_count()))
        for t in threads:
            t.join()
        if newIndividuals:
            for ni in newIndividuals:
                if pop.is_different(ni):
                    pop.addIndividual(ni)
        newIndividuals = []
        pop.sortPopulation()
        return pop.showBestSolution()
Exemplo n.º 13
0
constants = get_constants(lower=-10, upper=10, bit=True)
ppl.createPopulation(functions=functions,
                     constants=constants,
                     n_ind=n_ind,
                     n_gene=n_gene,
                     n_register=n_register)
eval_function = lambda x: x[0] ^ x[1]  # xor
ppl.excute_all(inputs, eval_function)

# revolution
p = ProgressBar(0, revolution)
for i in range(revolution):
    #print("revolution: ", i)
    p.update(i + 1)
    elite = Selection.elite(ppl, elite_size)
    new_p = copy.deepcopy(elite)
    for j in range(n_ind - elite_size):
        parent = Selection.tournament(ppl, tourn_size)
        elite.append(parent)
        child = Crossover.randomPoints(elite, cross_rate)
        child = Mutation.mutation(child, mutate_rate, n_register, functions,
                                  constants)
        new_p.append(child)
    ppl.setPopulation(new_p)
    ppl.excute_all(inputs, eval_function)
    if ((i % 100) == 0):
        ppl.result()
ppl.result()
ppl.write_result(path)
p.finish()
Exemplo n.º 14
0
    def GA(self):
        # define população inicial

        pop = Population()
        population = pop.definePopulation(config.MI)

        def minor(x, y):
            return x if x.get_cost() < y.get_cost() else y

        best = 0
        bestPrev = 0
        controlPop = True
        controlPopPrev = True
        sumControl = 0
        cont = 0
        # avalie a população

        # critério de parada
        i = 0
        while i < config.GEN and cont <= config.GEN_NO_EVOL:
            tAllIni = time.time()
            bestPrev = best
            controlPopPrev = controlPop
            tLS = 0

            #sizePopulation = len(population)
            for j in range(round(config.LAMBDA / 2)):
                selProbalities = pop.get_selProbabilities(
                )  # probabilidade de seleção
                # print("pop: "+str(len(population)))
                # print("prob: "+str(len(selProbalities)))
                # selecione os pais
                aux = np.random.choice(population,
                                       2,
                                       replace=False,
                                       p=selProbalities)

                # aux1 = population[np.random.randint(len(population))]
                # aux2 = population[np.random.randint(len(population))]

                P1 = minor(aux[0], aux[1])

                aux = np.random.choice(population,
                                       2,
                                       replace=False,
                                       p=selProbalities)
                # aux1 = population[np.random.randint(len(population))]
                # aux2 = population[np.random.randint(len(population))]
                P2 = minor(aux[0], aux[1])

                # Crossover

                rand = 0.5  #np.random.random()
                # print(rand)
                # print(P1)
                # print(P2)
                children = []
                if rand > 0.5:
                    children = cross.OBX(copy.deepcopy(P1), copy.deepcopy(P2))
                else:
                    children = cross.PMX(copy.deepcopy(P1), copy.deepcopy(P2))
                # print("child: \n")
                # print(child)
                # for a in range(2):
                #     for e1, c1 in enumerate(children[a]):
                #         for e2, c2 in enumerate(children[a]):
                #             if e1 != e2 and c1 == c2:
                #                 print("Elementos iguais")
                #                 exit(1)

                # Mutação

                # duas threads
                modChildren = []
                with concurrent.futures.ThreadPoolExecutor(
                        max_workers=2) as executor:
                    future_to_child = {
                        executor.submit(Mutation.mutation, child): child
                        for child in children
                    }
                    for future in concurrent.futures.as_completed(
                            future_to_child):
                        child = future_to_child[future]
                        try:
                            indiv = future.result()
                            modChildren.append(indiv)
                        except Exception as exc:
                            print('%s gerou uma exceção na busca local: %s' %
                                  (str(child), exc))

                # split
                cluster = SplitDepots.splitByDepot(modChildren[0])
                # print(cluster)
                individual1 = split.splitLinear(cluster)
                cluster = SplitDepots.splitByDepot(modChildren[1])
                # print(cluster)
                individual2 = split.splitLinear(cluster)

                individuals = [individual1, individual2]

                # print("individual: ")
                # print(individual1)
                # print(individual2)
                for a in range(2):
                    for ii, c1 in enumerate(individuals[a].get_giantTour()):
                        for jj, c2 in enumerate(
                                individuals[a].get_giantTour()):
                            if ii != jj and c1 == c2:
                                print("Elementos iguais na mutação")
                                exit(1)

                # Busca Local

                # duas threads
                ini = time.time()
                modIndividuals = []
                LS = ls()
                # modIndividuals.append(LS.LS(individuals[0]))
                # modIndividuals.append(LS.LS(individuals[1]))
                with concurrent.futures.ThreadPoolExecutor(
                        max_workers=2) as executor:
                    future_to_individual = {
                        executor.submit(LS.LS,
                                        ind,
                                        nMovimentations='random',
                                        where='ls'): ind
                        for ind in individuals
                    }
                    for future in concurrent.futures.as_completed(
                            future_to_individual):
                        ind = future_to_individual[future]
                        try:
                            indiv = future.result()
                            modIndividuals.append(indiv)
                        except Exception as exc:
                            print('%s gerou uma exceção na busca local: %s' %
                                  (str(ind), exc))
                # print(future_to_individual)
                # print(individuals[0])
                # print(modIndividuals)
                # exit(1)
                tTotal = (time.time() - ini) / 60
                tLS += tTotal
                for a in range(2):
                    for e1, c1 in enumerate(modIndividuals[a].get_giantTour()):
                        for e2, c2 in enumerate(
                                modIndividuals[a].get_giantTour()):
                            if e1 != e2 and c1 == c2:
                                print("Elementos iguais na busca local")
                                exit(1)
                # exit(1)
                # avalie a população
                for a in range(2):
                    # indivíduo diferente do resto da população
                    if pop.is_different(modIndividuals[a]):
                        pop.addIndividual(modIndividuals[a])

                pop.sortPopulation()
                population = pop.get_population()

            # promoção

            p = max(round(config.LAMBDA * 0.1), 2)  #10% da população
            ini = time.time()
            LSBest = ls()
            # if np.random.random() < config.PROB_LS:
            #     bestIndividual = LSBest.LS(population[0])
            #     if pop.is_different(bestIndividual):
            #         pop.addIndividual(bestIndividual)
            #         population = pop.get_population()
            modIndividuals = []
            individuals = []
            individuals = np.random.choice(population, p - 1, replace=False)
            individuals = np.append(individuals, pop.showBestSoution())
            with concurrent.futures.ThreadPoolExecutor(
                    max_workers=4) as executor:
                future_to_individual = {
                    executor.submit(LSBest.LS, ind, where='ls'): ind
                    for ind in individuals
                }
                for future in concurrent.futures.as_completed(
                        future_to_individual):
                    ind = future_to_individual[future]
                    try:
                        indiv = future.result()
                        modIndividuals.append(indiv)
                    except Exception as exc:
                        print('%s gerou uma exceção na busca local: %s' %
                              (str(ind), exc))

            # avalie a população
            for a in modIndividuals:

                for e1, c1 in enumerate(a.get_giantTour()):
                    for e2, c2 in enumerate(a.get_giantTour()):
                        if e1 != e2 and c1 == c2:
                            print("Elementos iguais na busca local - promoção")
                            exit(1)

                # indivíduo diferente do resto da população
                if pop.is_different(a):
                    pop.addIndividual(a)

            tTotalP = (time.time() - ini) / 60

            pop.sortPopulation()

            # defina a população sobrevivente
            best = pop.defineSurvivors(config.MI)

            # verifica se houve evolução na população
            # if not pop.verifyDiversity():
            #     #print("Baixa diversidade")

            #     controlPop = False
            # if not controlPop and controlPop == controlPopPrev:
            #     sumControl += 1
            # else:
            #     sumControl = 0
            if bestPrev == best:
                cont += 1
            else:
                cont = 0
            # if sumControl > config.CONT_METRIC:
            #     population = pop.changePopulation()
            #     sumControl = 0
            if cont > config.GEN_NO_EVOL:
                print("ALERTA POPULAÇÃO PAROU DE EVOLUIR")

            population = pop.get_population()
            tAll = (time.time() - tAllIni) / 60

            print(
                "GERAÇÃO: {} - Custo: {} - Tempo LS: {} - Tempo LS Promotion: {} - Tempo Total: {}"
                .format(i,
                        pop.showBestSoution().get_cost(), tLS, tTotalP, tAll))

            i += 1

        # liste os melhores indivíduos
        print(population)
        print(len(population))
Exemplo n.º 15
0
    from crossover import Crossover
    dataset = readDataset("./dataset/binary.txt")
    population = Population()
    for i in range(5):
        ind = Individual()
        ind.createGene(dataset, 10)
        population.addInd(ind)

    def evaluate(ind):
        fitness = sum(ind)
        return (fitness)

    population.calcFitness(evaluate)
    population.show()
    parents = Select.Tournament(population, 5, 3, "max")
    for ind in parents:
        ind.show()
    print("Onepoint")
    children = Crossover.onePoint(parents, 5, 10, 0.7)
    for ind in children:
        ind.show()
    print("Twopoints")
    children = Crossover.twoPoints(parents, 5, 10, 0.7)
    for ind in children:
        ind.show()
    print("Randompoints")
    children = Crossover.randomPoints(parents, 5, 10, 0.7)
    for ind in children:
        ind.show()
    Mutation.mutation(children, 0.7, dataset)
Exemplo n.º 16
0
        # score chromosomes in the population against fitness goal
        scored_population = []
        for chromosome in starting_population:
            fitness = Fitness(chromosome=chromosome, fitness_goal=fitness_goal)
            scored_chromosome = fitness.calculate_fitness()
            scored_population.append(scored_chromosome)

        # Select parents for offspring generation
        for ch in range(0, scored_population.__len__(), 1):
            # perform parent selection from scored population
            selection = Selection(population=scored_population)
            parents = selection.select()

            # perform crossover based on 50% probability
            crossover_prob = random.choice([True, False])
            crossover = Crossover(parents,
                                  crossover_probability=crossover_prob)
            offspring = crossover.perform_crossover()

            # perform mutation based on 50% probability
            mutation_prob = random.choice([True, False])
            mutation = Mutation(offspring, mutation_probability=mutation_prob)
            final_offspring = mutation.mutate()

            # add offspring to next generation
            next_gen_population.append(final_offspring)

        # Score next gen population
        scored_next_gen_population = []
        for chromosome in next_gen_population:
            fitness = Fitness(chromosome=chromosome, fitness_goal=fitness_goal)
            scored_next_gen_chromosome = fitness.calculate_fitness()
Exemplo n.º 17
0
    func = get_functions()
    constants = get_constants(bit=True)
    n_register = 10
    n_ind = 5
    n_gene = 5
    ppl.createPopulation(functions=func,
                         constants=constants,
                         n_ind=5,
                         n_gene=5,
                         n_register=n_register)

    eval_function = lambda x: x[0] ^ x[1]  # xor
    ppl.excute_all(inputs, eval_function)

    elite_size = 3
    parents = Selection.elite(ppl, elite_size)

    tourn_size = 3
    for i in range(n_ind):
        parent = Selection.tournament(ppl, tourn_size)
        parents.append(parent)

    cross_rate = 0.7
    child = Crossover.randomPoints(parents, cross_rate)

    mutate_rate = 0.7  # for debug (In generary, set up like 0.05)
    child.show()
    child = Mutation.mutation(child, mutate_rate)
    child.show()