예제 #1
0
    def main(self):
        alpha = 0.2
        S0 = self.arquivo.getMatrizArquivo(self.path)
        self.imprimirMatrizInicial(S0)
        S = 0
        T0 = self.temperaturaInicial()
        T = T0
        j = 1
        while True:
            i = 1
            while True:
                S0 = Tabuleiro()
                fitness = Fitness(S0)
                novaTemperatura = fitness.getFitness()
                delta = novaTemperatura - T
                if self.aceitacaoNovaSolucao(T, delta) == True:
                    S = S0
                    T = novaTemperatura
                i += 1
                if i == 10000 or T == 0:
                    break
            T = T * alpha
            j += 1
            if T <= 0:
                break

        print("Simulated Annealing Resultado:")
        S.imprimirTabuleiro()
예제 #2
0
def RC():
    Configuration = firstFit()
    e = Fitness(Configuration)
    bestFitness = max(Configuration)
    bestConf = Configuration
    T_ = T
    Configurations = []
    proba_acceptation = []
    for k in range(nb_iteration):
        voisinConfiguration = voisin(Configuration)
        en = Fitness(voisinConfiguration)
        # Configurations.append(max(voisinConfiguration))
        # if( np.exp((en-e)/T_) < 1) : proba_acceptation.append( np.exp((en-e)/T_))
        if (en > e) or random() < np.exp((en - e) / T_):
            Configuration = voisinConfiguration
            e = en
            if (max(Configuration) < bestFitness):
                bestFitness = max(Configuration)
                bestConf = Configuration
        T_ *= 0.99
    """plt.plot(range(nb_iteration),Configurations,'b')
    plt.savefig('fig/evolution.png')
    plt.close()
    plt.plot(range(len(proba_acceptation)),proba_acceptation)
    plt.xlabel('iterations')
    plt.ylabel('probabilité')
    plt.title('évolution de la probabilité d\'acceptation')
    plt.savefig('fig/acceptation.png')
    plt.close()"""
    return max(bestConf)
예제 #3
0
 def __init__(self, dimension, weight_limit, number_ind, number_players,
              crossover_point, prob_mutation):
     self.fitness = Fitness(dimension, weight_limit)
     self.x = self.initialise(number_ind, dimension)
     self.number_players = number_players
     self.crossover_point = crossover_point
     self.prob_mutation = prob_mutation
예제 #4
0
def selection_tournament(population):
    selected_individuals = []
    selected_indexes = []

    # take all individuals if population is too small
    if ap.TOURNAMENT_N*len(population.individuals) >= len(population.individuals):
        selected_individuals = population.individuals
    else:
        while len(selected_individuals) < ap.TOURNAMENT_N*len(population.individuals):

            # get random index which wasn't used
            while True:
                random_index = random.randint(0, len(population.individuals) - 1)
                if random_index not in selected_indexes:
                    break

            # add reference to chosen individual and it's index
            selected_individuals.append(population.individuals[random_index])
            selected_indexes.append(random_index)

    # fitness for every individual
    fitness = []
    for ind in selected_individuals:
        fit = Fitness(ind)
        fitness.append(fit.count_fitness())

    # get index of smallest fitness
    index_min = min(range(len(fitness)), key=fitness.__getitem__)
    fit = Fitness(selected_individuals[index_min])
    #print("Tournament - selected fitness:", fit.count_fitness())

    return selected_individuals[index_min]
예제 #5
0
def selection_roulette(population):
    # weight/100 for each individual
    weights = []
    for ind in population.individuals:
        fit = Fitness(ind)
        weights.append(1 / fit.count_fitness())

    weights_sum = sum(weights)

    # odds for being chosen, oddds = weight/sum
    odds = []
    for x in range(len(population.individuals)):
        odds.append(weights[x] / weights_sum)

    random_number = random.random()

    # finding individual related to random number
    roulette_sum = 0
    #print("SUM", sum(odds))
    for x in range(len(odds)):
        roulette_sum += odds[x]
        #print("sum", roulette_sum)
        if random_number <= roulette_sum:
            #print("random", random_number)
            fit = Fitness(population.individuals[x])
            #print("Roulette - selected fitness:", fit.count_fitness())
            return population.individuals[x]
예제 #6
0
def SelectBestConfiguration(Configurations):
    minConf = Configurations[0]
    minFitness = Fitness(minConf)
    for Configuration in Configurations[1:]:
        if Fitness(Configuration) < minFitness:
            minConf = Configuration
            minFitness = Fitness(minConf)
    return minConf
예제 #7
0
 def __init__(self, arr_solution, populationSize):
     self.crossoverRate = 0.5
     self.mutationRate = 0.05
     self.uniformRate = 0.5
     self.elitism = True
     self.MAX_GENERATIONS = 3
     self.m_fitness = Fitness(arr_solution)
     self.m_population = Population(populationSize)
     self.Solution_Index = 0
예제 #8
0
    def best_worst_fitness_in_population(self):
        fitness = []
        for ind in self.individuals:
            fit = Fitness(ind)
            fitness.append(fit.count_fitness())
        #print("AVERAGE: " + str(np.average(fitness)))

        return min(fitness), max(fitness), self.individuals[min(
            range(len(fitness)),
            key=fitness.__getitem__)], self.individuals[min(
                range(len(fitness)), key=fitness.__getitem__)]
예제 #9
0
    def __init__(self, n, g, genes, connections, costs):
        self.n = n
        self.g = g
        self.connections = connections

        self.fitness = Fitness(genes, costs)
        self.operation = Operation(self.fitness, connections)
        self.replace = Replace()

        self.individual = Individual(genes, self.fitness.get_fitness(genes))
        self.population = self.initial_population()
        self.generations()
예제 #10
0
    def clonar(self, vetor_celulas, quantidade_de_clones, matriz_dist):
        novo_vetor = []

        for celula in vetor_celulas:
            novo_vetor.append(celula)
            clones_bonus = int(quantidade_de_clones * celula.get_afinidade())
            total_clones = clones_bonus + quantidade_de_clones

            for contador in range(total_clones):
                rota_mutacionada = self.mutacionar(list(celula.get_rota()))
                fit = Fitness(rota_mutacionada, matriz_dist)
                fitness = fit.calcular()
                celula_clone = Celula(rota_mutacionada, fitness, 0, 0, 0)
                novo_vetor.append(celula_clone)

        return novo_vetor
예제 #11
0
def rankRoutes(population):
    fitnessResults = {}
    for i in range(0, len(population)):
        fitnessResults[i] = Fitness(population[i]).routeFitness()
    return sorted(fitnessResults.items(),
                  key=operator.itemgetter(1),
                  reverse=True)
def rank_paths(population):
    fitness_results = dict()
    for i in range(0, len(population)):
        fitness_results[i] = Fitness(population[i]).path_fitness()
    return sorted(fitness_results.items(),
                  key=operator.itemgetter(1),
                  reverse=True)
예제 #13
0
    def gerar_populacao(self):
        populacao = []

        for i in range(self.__num_celulas):
            rota = [cidade for cidade in range(len(self.__cidades))]
            random.shuffle(rota)
            fitness = Fitness(rota, self.__cidades)
            id = str(self.__geracao) + '_x' + '_' + str(i)

            celula = Celula(id, fitness.calcular(), self.__validade, 0, rota)
            populacao.append(celula.get_celula())

        populacao = pd.DataFrame(populacao)

        populacao = calcular_afinidade(populacao)

        return populacao
예제 #14
0
def rankRoutes(population):
    fitnessResults = {}
    # calcula o valor de Fitness de cada rota
    for i in range(0, len(population)):
        fitnessResults[i] = Fitness(population[i]).routeFitness()
    # retorna esses valores ordenados, com index e valor
    return sorted(fitnessResults.items(),
                  key=operator.itemgetter(1),
                  reverse=True)
예제 #15
0
def clonar(populacao, num_clones, geracao, validade, cidades):
    for index, celula_mae in populacao.iterrows():
        id_clones = []
        fit_clones = []
        val_clones = []
        af_clones = []
        rt_clones = []

        bonus = num_clones * celula_mae.afinidade
        total_clones = num_clones + bonus

        for contador in range(int(total_clones)):
            id = celula_mae["id"].split("_")
            id[0] = str(geracao)
            id[1] = id[2]
            id[2] = str(contador)
            id = id[0] + "_" + id[1] + "_" + id[2]
            id_clones.append(id)

            rota = mutacionar(celula_mae["rota"])
            rt_clones.append(rota)

            fit = Fitness(rota, cidades)
            fit_clones.append(fit.calcular())

            val_clones.append(validade)

            af_clones.append(0)

        clones = {
            'id': id_clones,
            'fitness': fit_clones,
            'validade': val_clones,
            'afinidade': af_clones,
            'rota': rt_clones
        }
        clones = pd.DataFrame(clones)

        populacao = populacao.append(clones)

    populacao = calcular_afinidade(populacao)
    populacao.index = range(populacao.shape[0])

    return populacao
예제 #16
0
    def draw_plot(self, individual):
        plt.clf()
        # FRAME
        x_frame = np.array([0, 0, self.pcb.width, self.pcb.width, 0])
        y_frame = np.array([0, self.pcb.height, self.pcb.height, 0, 0])
        plt.plot(x_frame, y_frame, linestyle='dashed')

        # TITLE
        title_font = {'family': 'serif', 'size': 16}
        plt.title("BEST INDIVIDUAL", fontdict=title_font)

        for path in individual.paths:

            rand_color = "#%06x" % random.randint(0, 0xFFFFFF)

            # START & END POINT
            start = path.link.start_point
            end = path.link.end_point
            plt.plot([start.x], [start.y], marker='o', color=rand_color, ms=10)
            plt.plot([end.x], [end.y], marker='x', color=rand_color, ms=10)

            # SEGMENTS
            x_segments = [path.segments[0].start_point.x]
            y_segments = [path.segments[0].start_point.y]

            for segment in path.segments:
                x_segments.append(segment.end_point.x)
                y_segments.append(segment.end_point.y)

            plt.plot(x_segments, y_segments, color=rand_color)

        fit = Fitness(individual)
        fitness = fit.count_fitness()
        ind_info = fit.get_info()

        plt.figtext(
            0.2, 0, 'Length: ' + str(ind_info[0]) + '   Segments: ' +
            str(ind_info[1]) + '   Crosses: ' + str(ind_info[2]) +
            '   Fitness: ' + str(fitness) + '\nPaths out of board: ' +
            str(ind_info[3]) + '   Length out of board: ' + str(ind_info[4]))

        plt.grid()
        plt.draw()
        plt.waitforbuttonpress(0)
예제 #17
0
def route_fitness(population):
    """
    This function returns the sorted dictionary of cities over the fitness function.
    :param population: Population generated
    :return: Record or dictionary of cities sorted on fitness value
    """
    fitness_record = dict()
    for pop in range(len(population)):
        fitness_record[pop] = Fitness(population[pop]).fitness_evaluator()
    return sorted(fitness_record.items(), key=operator.itemgetter(1), reverse=True)
예제 #18
0
    def calculate_fitness(self, chromosomes_list, condition):
        for i in range(0, self.no_of_chromosomes):
            # Creating object from Fitness class
            fitness = Fitness(chromosomes_list[i], condition)
            # Calculating the fitness of each chromosome
            fitness.calculate_fitness()
            # Adding each chromosome and its fitness to the fitness list
            self.fitness_list[i][0] = chromosomes_list[i]
            self.fitness_list[i][1] = fitness.get_fitness()

        # Sorting the chromosomes according to their fitness
        self.fitness_sorted = sorted(self.fitness_list,
                                     key=lambda x: x[1],
                                     reverse=True)

        # Creating a list of the most two fittest chromosome
        self.fittest_list = [
            self.fitness_sorted[0][0], self.fitness_sorted[1][0]
        ]
예제 #19
0
    def gerar_populacao(self):
        populacao = []

        for contador in range(self.__quantidade):
            rota = [pos for pos in range(len(self.__matriz_dist))
                    ]  # rota = [0, 1, 2, 3, ..., 99]
            random.shuffle(rota)  # embaralha a rota
            fit = Fitness(rota, self.__matriz_dist
                          )  # calcula a distância total da rota definida
            fitiness = fit.calcular(
            )  # define o fitness de acordo com a rota total
            celula = Celula(rota, fitiness, 0, 0,
                            0)  # instancia uma nova celula
            populacao.append(celula)  # adiciona a celula nova à população

        if self.__e:
            populacao = calcular_afinidade(populacao)

        return populacao
예제 #20
0
    def order_routes(self, population):

        fitness_results = {}
        for i in range(
                0,
                len(population)):  # calculo das distancias de todas as rotas
            fitness_results[i] = Fitness(population[i].posicao).route_fitness()

        return sorted(
            fitness_results.items(), key=operator.itemgetter(1),
            reverse=True)  # ordenando as rotas de acordo com as distancias
예제 #21
0
    def runPso(self):

        print("Distância Inicial: " +
              str(1 / self.order_routes(self.population)[0][1]))
        progress = []
        progress.append(1 / self.order_routes(self.population)[0][1])
        for i in range(0, self.iteracoes):
            print("Iteração : {} \n".format(i))
            for particula in self.population:

                self.gbest = deepcopy(
                    particula.move(self.w, self.c1, self.c2, self.gbest))
                # print("posicao: {} , gbest: {}, tam: {}".format(particula.fitness,1/Fitness(self.gbest.posicao).route_fitness(), len(particula.posicao)))

            progress.append(1 / Fitness(self.gbest.posicao).route_fitness())

        print("Distância Final: " +
              str(1 / Fitness(self.gbest.posicao).route_fitness()))
        # print(progress)
        print("Melhor rota:", self.gbest.posicao)
        bestRoute = self.gbest.posicao

        x = []
        y = []
        for r in bestRoute:
            x.append(r.x)
            y.append(r.y)
        x.append(bestRoute[0].x)
        y.append(bestRoute[0].y)

        plt.figure(1)
        plt.subplot(211)
        plt.plot(x, y, 'o')
        plt.plot(x, y, 'k-', color='red')  # linha pontilha red

        plt.subplot(212)
        plt.plot(progress)
        plt.ylabel('Distância')
        plt.xlabel('Geração')

        plt.show()
예제 #22
0
  def calculoPbest(self,cpy,gbest):
     
   
     ft = Fitness(deepcopy(cpy)).route_fitness()
    #  self.fitness = ft
     if  ft > self.pbest.fitness: # achou um melhor 
        self.pbest.posicao = deepcopy(cpy)
        self.fitness = deepcopy(ft)

     if(ft > gbest.fitness):
       gbest.posicao = deepcopy(cpy)
       gbest.fitness = deepcopy(ft)

     return gbest
예제 #23
0
def AG():
    Population = np.array(GenerateConfigurations(PopulationBegin))
    BestConf = SelectBestConfiguration(Population)
    BestFitness = Fitness(BestConf)
    Configurations = []
    #print([Fitness(c) for c in Population])
    for i in range(nb_iteration):
        fitness = calculFitnessForConfigurations(Population)
        index = SelectionParent(fitness)
        parents = Population[index].tolist()
        childs = CrossOverPopulation(parents)
        #print([Fitness(c) for c in childs])
        Population = parents + childs
        Population = np.array(
            MutatePopulation(Population)
        )  # il faut transformé en np array pour pouvoir faire Parents = Populaiton[index]
        BestConfItration = SelectBestConfiguration2(Population)
        #Configurations.append(Fitness(BestConfItration))
        if (Fitness(BestConfItration) < BestFitness):
            BestConf = BestConfItration.copy()
            BestFitness = Fitness(BestConf)
    #plt.plot(range(nb_iteration),Configurations,'b')
    #plt.savefig('fig/evolution.png')
    return BestFitness
예제 #24
0
        if self._showTotalFitness:
            plt.plot(self._totalFitnessHistory, label="total_fitness")
            plt.savefig(os.path.join(path, 'totalFitness_%s.png' % time.strftime("%H%M", time.localtime(time.time()))))
        plt.legend()
        plt.show()

    # 参数设置
    def parameters(self):
        return 'populationSize=%d, binaryEncode=%s, geneLength=%d, boundaryList=%s,\n delta=%f,' \
               'fitnessClass=%s, crossoverRate=%f, crossoverOneRate=%f, crossoverTwoRate=%f,' \
               'mutationRate=%f, mutationLocationRate=%f, mutationRotateRate=%f, fitnessThreshold=%f,' \
               'similarityThreshold=%f, CF=%d, punish=%f, showBestFitness=%s, showTotalFitness=%s' \
               % (self._populationSize, self._binaryEncode, self._geneLength, self._boundaryList, self._delta,
                  self._fitnessClass, self._crossoverRate, self._crossoverOneRate, self._crossoverTwoRate,
                  self._mutationRate, self._mutationLocationRate, self._mutationRotateRate, self._fitnessThreshold,
                  self._similarityThresholdThreshold, self._CF, self._punish, self._showBestFitness,
                  self._showTotalFitness)


if __name__ == "__main__":
    # 适应函数度量
    fitnessClass = Fitness()
    ga = GA(crossoverRate=0.7, mutationRate=0.05, populationSize=100, boundaryList=[[0.5, 1.5]] * 2, delta=0.1,
            fitnessClass=fitnessClass)
    ga.plotHistory()
    for i in range(3):
        print(ga._population[0]._gene)
        gene = ga.mutation(ga._population[0]._gene)
        print(gene)
        print('\n')
예제 #25
0
 def __init__(self, city_list):
 
   self.posicao  = random.sample(city_list, len(city_list)) # rota aleatório 
   self.fitness = Fitness(self.posicao).route_fitness()
   self.pbest = deepcopy(self)
예제 #26
0
class Population:
    def __init__(self, n, g, genes, connections, costs):
        self.n = n
        self.g = g
        self.connections = connections

        self.fitness = Fitness(genes, costs)
        self.operation = Operation(self.fitness, connections)
        self.replace = Replace()

        self.individual = Individual(genes, self.fitness.get_fitness(genes))
        self.population = self.initial_population()
        self.generations()

    def initial_population(self):
        individuals = []
        for i in range(self.n):
            genes = [[], self.individual.genes[1]]

            for j in range(0, len(self.individual.genes[0])):
                #if self.individual.genes[1][j] == 1:
                #genes[0].append(self.individual.genes[0][j])
                #else:
                connection = self.connections[self.individual.genes[0][j]] + [
                    self.individual.genes[0][j]
                ]
                genes[0].append(connection[random.randint(
                    0,
                    len(connection) - 1)])

            individuals.append(
                Individual(genes, self.fitness.get_fitness(genes)))
        return individuals

    def generations(self):
        number_generations = []

        if self.g > 1:
            for i in range(2, self.g + 1):
                self.population = self.new_generation(self.population)
                number_generations.append(self.the_best().fitness)

        text_generations = ''
        for i in number_generations:
            text_generations += str(i) + ','

        print('\nGeneraciones')
        print(text_generations)

        self.best = self.the_best()
        self.optimized = True

        self.fitness.get_fitness(self.best.genes)
        print('\n')
        print(self.fitness.info)

        # print('BEST')
        # print('Fitness: ' + str(self.best.fitness))
        # print('')
        # print(self.best.genes)

        # SI NO ES MEJOR, DEJA EL INICIAL
        if self.best.fitness >= self.individual.fitness:
            self.best = self.individual
            self.optimized = False

    def new_generation(self, last_generation):
        new_generation = []
        for i in range(int(len(last_generation) / 2)):
            parents = self.selection(last_generation)

            # = self.operate(parents[0], parents[1])
            childrens = self.operation.operate(parents[0], parents[1])
            new_individuals = self.replace.replace(parents, childrens)

            new_generation.append(new_individuals[0])
            new_generation.append(new_individuals[1])

        return new_generation

    def selection(self, population):
        if len(population) > 4:
            selection = []
            parents = []

            for i in range(
                    3
            ):  ### CAMBIE SOLO POR PROBAR PASANDO EL MEJOR Y OTROS 3, ESTABA EN 4.
                selector = random.randint(0, len(population) - 1)
                selection.append(population[selector])

            selection.append(self.the_best())

            for i in range(2):
                parents.append(self.compete(selection[0], selection[1]))

                selection.pop(1)
                selection.pop(0)

            return parents

    def compete(self, individual_1, individual_2):
        fitness_total = individual_1.fitness + individual_2.fitness

        if (fitness_total == 0): return individual_1

        percentage_1 = (individual_1.fitness / fitness_total)

        return (individual_2
                if random.random() > percentage_1 else individual_1)

    def the_best(self):
        best = self.population[0]

        for i in range(1, len(self.population)):
            temp_fitness = self.population[i].fitness
            if (self.population[i].fitness < best.fitness):
                best = self.population[i]

        return best
예제 #27
0
from ImportFormCSV import importCSV
from Fitness import Fitness
from Genetic import Genetic
import datetime
people = importCSV()
fitness = Fitness(people)
bigs, littles = fitness.bigs, fitness.littles
genetic = Genetic(bigs, littles, fitness)

# IMPORT CSV
# print('PEOPLE', people)
#
# # CREATE FITNESS
# print('BIGS:', bigs)
# print('LITTLES: ', littles)
# print('AUTO MATCHED', fitness.get_automatches())
#
#
# # GENERATE A SAMPLE
# print(genetic.generate_sample(5))
#
#
# CROSSOVER
# a = ['a', 'b', 'f', 'e', 'd', 'c']
# b = ['c', 'b', 'e', 'a', 'd', 'f']
# print('BEFORE')
# print(a)
# print(b)
# print('AFTER')
# crossed = genetic.crossover(a, b)
# for cross in crossed:
예제 #28
0
class GA:
    def __init__(self, arr_solution, populationSize):
        self.crossoverRate = 0.5
        self.mutationRate = 0.05
        self.uniformRate = 0.5
        self.elitism = True
        self.MAX_GENERATIONS = 3
        self.m_fitness = Fitness(arr_solution)
        self.m_population = Population(populationSize)
        self.Solution_Index = 0

    def initializePopulation(self, population):
        fitPopulation = self.m_fitness.calculateFitness(population)
        self.m_population.initializePopulation(fitPopulation)

    def evolvePopulation(self):

        child = None
        for i in range(self.MAX_GENERATIONS):

            parent1 = self.rankSelection(self.m_population)
            parent2 = self.rankSelection(self.m_population)
            child = self.crossover(parent1, parent2)
            self.m_population.updateChromosome(child)
            if (child.getSolutionId() == -1
                    and i == (self.MAX_GENERATIONS - 1)):
                child.setSolutionId(self.Solution_Index)
                self.m_population.updateChromosome(child)
                break
            elif child.getSolutionId() != -1:
                break
            fittestChromosomes = self.m_population.getFittestChromoCount()
            for j in range(len(fittestChromosomes)):  #Check
                self.m_population.updateChromosome(
                    self.mutate(fittestChromosomes[j]))

        self.m_fitness.incrementSolutionIndex()
        self.Solution_Index += 1

        return self.m_population

    def crossover(self, parent1, parent2):
        child = Chromosome()
        if (parent1.getFitness() < parent2.getFitness()):
            child = parent1
        else:
            child = parent2

        solution = self.m_fitness.getSolution()
        r = child.getGene(0)
        g = child.getGene(1)
        b = child.getGene(2)
        dr = abs(solution - r)
        dg = abs(solution - g)
        db = abs(solution - b)

        minz = dr
        chosen = 1
        if (dg < minz):
            minz = dg
            chosen = 2
        if (db < minz):
            minz = db
            chosen = 3
        if chosen == 1:
            if r > solution:
                r = r - int(dr * self.crossoverRate)
            elif r < solution:
                r = r + int(dr * self.crossoverRate)
            else:
                child.setSolutionId(self.Solution_Index)
            child.setGene(0, r)

        elif chosen == 2:
            if g > solution:
                g = g - int(dg * self.crossoverRate)

            elif g < solution:
                g = g + int(dg * self.crossoverRate)
            else:
                child.setSolutionId(self.Solution_Index)
            child.setGene(1, g)

        elif chosen == 3:
            if b > solution:
                b = b - int(db * self.crossoverRate)
            elif b < solution:
                b = b + int(db * self.crossoverRate)
            else:
                child.setSolutionId(self.Solution_Index)
            child.setGene(2, b)

        return child

    def mutate(self, c):
        gene_count = 3
        SUBRACT = 1
        ADD = 2
        operation = random.randint(1, 2)

        for index in range(gene_count):
            value = c.getGene(index)
            if (operation == SUBRACT):
                value -= int(value * self.mutationRate)
                if (value < 0):
                    value += int(value * self.mutationRate)

            elif (operation == ADD):
                value += int(value * self.mutationRate)
                if (value > 254):
                    value -= int(value * self.mutationRate)

            c.setGene(index, value)
        return c

    def rankSelection(self, pop):

        randomFromRank = random.randint(0, 2)
        fittestChromosomes = pop.getFittestChromoCount()
        abc = fittestChromosomes[0]

        return fittestChromosomes[randomFromRank]
예제 #29
0
class Genetic_Algorithm:
    def __init__(self, dimension, weight_limit, number_ind, number_players,
                 crossover_point, prob_mutation):
        self.fitness = Fitness(dimension, weight_limit)
        self.x = self.initialise(number_ind, dimension)
        self.number_players = number_players
        self.crossover_point = crossover_point
        self.prob_mutation = prob_mutation

    def initialise(self, number_ind, dimension):
        return np.random.randint(2, size=(number_ind, dimension + 1))

    def select(self):
        (ro, col) = self.x.shape
        x_new = np.zeros((ro, col))
        for ind1 in range(ro):
            indices = np.random.choice(ro, self.number_players, replace=False)
            fitness_local = np.zeros(self.number_players)
            for ind2 in range(self.number_players):
                fitness_local[ind2] = self.x[indices[ind2], col - 1]

            ind_win = np.argmax(fitness_local)
            x_new[ind1, :] = self.x[indices[ind_win], :]

        return x_new

    def crossover(self):
        (ro, col) = self.x.shape
        x_new = self.x
        for ind in range(0, ro - 1, 2):
            x_new[ind, self.crossover_point:col -
                  2] = self.x[ind + 1, self.crossover_point:col - 2]
            x_new[ind + 1, self.crossover_point:col -
                  2] = self.x[ind, self.crossover_point:col - 2]

        return x_new

    def mutate(self):
        (ro, col) = self.x.shape
        x_new = self.x
        for ind1 in range(ro):
            for ind2 in range(col - 1):
                if np.random.rand() < self.prob_mutation:
                    if x_new[ind1, ind2] == 1:
                        x_new[ind1, ind2] = 0
                    else:
                        x_new[ind1, ind2] = 1
        return x_new

    def evaluate(self):
        return self.fitness.evaluate(self.x)

    def get_fitness(self):
        (ro, col) = self.x.shape
        fitness = np.zeros(ro)
        for ind in range(ro):
            fitness[ind] = self.x[ind, col - 1]

        fitness_max = np.max(fitness)
        fitness_mean = np.mean(fitness)

        return fitness_max, fitness_mean

    def iteration(self):
        self.x = self.evaluate()
        self.x = self.select()
        self.x = self.crossover()
        self.x = self.mutate()
예제 #30
0
def rankRoutes(population):
    fitnessResults = {}
    for i in range(0,len(population)):
        fitnessResults[i] = Fitness(population[i]).calFitness() # Transform each city into Fitness and compute calFitness
    return sorted(fitnessResults.items(), key = operator.itemgetter(1), reverse = True) # sorted for choosing the top 1 route (highest fitness score)