def crossover(self, parent_1, parent_2):
        children = []

        # 1-point crossover
        max_string = len(parent_1.chrom_a)
        pcross_a = random.randint(0, max_string)
        pcross_b = random.randint(0, max_string)

        # Chromosomes for child 1
        chrom_1a = parent_1.chrom_a[:pcross_a] + parent_2.chrom_a[pcross_a:]
        chrom_1b = parent_1.chrom_b[:pcross_b] + parent_2.chrom_b[pcross_b:]

        chrom_2a = parent_2.chrom_a[:pcross_a] + parent_1.chrom_a[pcross_a:]
        chrom_2b = parent_2.chrom_b[:pcross_b] + parent_1.chrom_b[pcross_b:]

        child_1 = ind.Individual(chrom_1a, chrom_1b)
        child_2 = ind.Individual(chrom_2a, chrom_2b)

        child_1.mutate()
        child_2.mutate()

        children.append(child_1)
        children.append(child_2)

        return children
Beispiel #2
0
    def crossover(self, ratio):
        # crossover_point = np.random.randint(50, 100)
        crossover_point = ratio % self.amount
        new = self.amount // 10

        son = individual.Individual(self.start)
        son.gene_phi = self.pops.individuals[0].gene_phi.copy(
        )[:crossover_point] + self.pops.individuals[1].gene_phi.copy(
        )[crossover_point:]
        daughter = individual.Individual(self.start)
        daughter.genes = self.pops.individuals[1].gene_phi.copy(
        )[:crossover_point] + self.pops.individuals[0].gene_phi.copy(
        )[crossover_point:]

        self.pops.individuals.append(son)
        self.pops.individuals.append(daughter)

        for i in range((self.amount - self.survival) - new - 2):
            pos_dad = np.random.randint(0, self.survival)
            pos_mom = np.random.randint(0, self.survival)

            offspring = individual.Individual(self.start)
            offspring.gene_phi = self.pops.individuals[pos_dad].gene_phi.copy(
            )[:crossover_point] + self.pops.individuals[pos_mom].gene_phi.copy(
            )[crossover_point:]

            self.pops.individuals.append(offspring)
Beispiel #3
0
    def test_domination(self):
        g = genotype.Genotype(data_manager.dm.city_ids)
        i1 = individual.Individual(g)
        i2 = individual.Individual(g)

        i1.tour_distance = 500
        i2.tour_distance = 450

        i1.calculate_tour_cost = 40
        i2.calculate_tour_cost = 35

        self.assertTrue(i2.dominates(i1))
        self.assertFalse(i1.dominates(i2))
Beispiel #4
0
    def test_crossover_has_all_cities(self):
        g_1 = genotype.Genotype.get_random_genotype()
        parent_1 = individual.Individual(g_1)

        g_2 = genotype.Genotype.get_random_genotype()
        parent_2 = individual.Individual(g_2)

        new_g = parent_1.genotype.crossover(parent_2.genotype)

        print new_g
        for i in range(len(new_g)):
            print i
            self.assertTrue(i in new_g)
 def Crossover(self, parent1, parent2):
     childList = []
     a = r.randint(0, self.pop_dimension)
     gen_child1 = parent1.chromosome[:a]
     gen_child1.extend(parent2.chromosome[a:])
     gen_child2 = parent2.chromosome[:a]
     gen_child2.extend(parent1.chromosome[a:])
     child1 = idv.Individual(gen_child1, len(self.listTask))
     child2 = idv.Individual(gen_child2, len(self.listTask))
     # phân vân giữa chọn hay không chọn các yếu tố
     childList.append(child1)
     childList.append(child2)
     return childList
Beispiel #6
0
    def test_calculate_all_crowding_distances_edge_case(self):
        g1 = genotype.Genotype.get_random_genotype()
        i1 = individual.Individual(g1)
        i2 = individual.Individual(g1.clone())
        i3 = individual.Individual(g1.clone())

        p = population.Population(population_size=2,
                                  crossover_rate=0.5,
                                  mutation_rate=0.5,
                                  individuals=[i1, i2, i3])
        fronts = p.fast_non_dominated_sort()
        for rank in fronts:
            front = fronts[rank]
            population.Population.calculate_all_crowding_distances(front)
    def crossOver(self, a, b):
        children = []
        factorial_rank = []
        for i in range(len(self.tasks)):
            factorial_rank.append(self.population.nIndi + 1)

        child_a = []
        child_b = []
        t = r.randint(0, len(a.chromosome))

        child_a.extend(a.chromosome[0:t])
        child_b.extend(b.chromosome[0:t])
        for gen in a.chromosome:
            if gen not in child_b:
                child_b.append(gen)
        for gen in b.chromosome:
            if gen not in child_a:
                child_a.append(gen)

        ind_a = indi.Individual(child_a, [])
        if r.random() > 0.5:
            ind_a.skillFactor = a.skillFactor
        else:
            ind_a.skillFactor = b.skillFactor
        fitnessTa = [0 for x in range(len(self.tasks))]
        for i in range(len(self.tasks)):
            if i != ind_a.skillFactor:
                fitnessTa[i] = 100000000
            else:
                fitnessTa[i] = self.tasks[i].computeFitness(ind_a.chromosome)
        ind_a.fitnessTask = fitnessTa
        ind_a.factorialRank = factorial_rank
        children.append(ind_a)

        ind_b = indi.Individual(child_b, [])
        if r.random() > 0.5:
            ind_b.skillFactor = a.skillFactor
        else:
            ind_b.skillFactor = b.skillFactor
        fitnessTa = [0 for x in range(len(self.tasks))]
        for i in range(len(self.tasks)):
            if i != ind_b.skillFactor:
                fitnessTa[i] = 100000000
            else:
                fitnessTa[i] = self.tasks[i].computeFitness(ind_b.chromosome)
        ind_b.fitnessTask = fitnessTa
        ind_b.factorialRank = factorial_rank
        children.append(ind_b)

        return children
Beispiel #8
0
    def test_crossover_no_double_elements(self):
        g_1 = genotype.Genotype.get_random_genotype()
        parent_1 = individual.Individual(g_1)

        g_2 = genotype.Genotype.get_random_genotype()
        parent_2 = individual.Individual(g_2)

        new_g = parent_1.genotype.crossover(parent_2.genotype)
        for i in range(len(new_g)):
            count = 0
            for j in range(len(new_g)):
                if j != i and new_g[j] == new_g[i]:
                    if new_g[j] is not None:
                        count += 1
            self.assertTrue(count == 0)
def main():
    result_list = np.zeros(cf.get_iteration())
    for trial in range(cf.get_trial()):
        np.random.seed(trial)

        pos_list = []
        v_list = []
        pbest_list = []
        gbest = None
        

        """Generate Initial Population"""
        gbest = id.Individual()
        for p in range(cf.get_population_size()):
            pbest_list.append(id.Individual())
            pos_list.append(id.Individual())
            v_list.append(id.Individual())

        """ Main Loop """
        for iteration in range(cf.get_iteration()):
            """ Update Partical position """
            for i in range(cf.get_population_size()):
                # move to new position
                v_list[i].get_velocity(pos_list[i], pbest_list[i], gbest)
                pos_list[i].get_newPos(v_list[i])

                # update fitness
                fitness = fn.calculation(pos_list[i].get_position(), 0)
                pos_list[i].set_fitness(fitness)

                # update pbest & gbest
                if pos_list[i].get_fitness() < pbest_list[i].get_fitness():
                    pbest_list[i].set_position(pos_list[i].get_position())
                    pbest_list[i].set_fitness(pos_list[i].get_fitness())

                if pos_list[i].get_fitness() < gbest.get_fitness():
                    gbest.set_position(pos_list[i].get_position())
                    gbest.set_fitness(pos_list[i].get_fitness())
                
            # print([x.get_fitness() for x in pbest_list])
            # print(gbest.get_fitness())
            # sys.stdout.write("\r Trial:%3d , Iteration:%7d, BestFitness:%.10f" % (trial , iteration, gbest.get_fitness()))
            result_list[iteration] += gbest.get_fitness()
    
    """ export avg result"""
    result_list /= cf.get_trial()
    for iteration in range(cf.get_iteration()):
        result.write('{} {}\n'.format(iteration, result_list[iteration]))
Beispiel #10
0
def get_highest_fitness(fed_population):
    highest = individual.Individual()

    for ind in fed_population:
        if ind.fitness > highest.fitness:
            highest = ind
    return highest.fitness
Beispiel #11
0
Datei: ga.py Projekt: Alex9702/AG
    def crossoverPopulation(self, pop):
        # Create new population
        newpop = population.Population(pop.size())

        # Loop over current population by fitness
        for popIndex in range(pop.size()):
            parent1 = pop.getFittest(popIndex)
            # Apply crossover to this individual?
            if self.crossoverRate > random.random(
            ):  # and popIndex >= self.elitismCount:
                # Initialize offspring
                offspring = individual.Individual(
                    parent1.getChromosomeLength())

                # Find second parent
                parent2 = self.selectParent(pop)

                # Loop over genome
                for geneIndex in range(parent1.getChromosomeLength()):
                    # Use half of parent1's genes and half of parent2's genes
                    if 0.5 > random.random():
                        offspring.setGene(geneIndex,
                                          parent1.getGene(geneIndex))
                    else:
                        offspring.setGene(geneIndex,
                                          parent2.getGene(geneIndex))
                # Add offspring to new population
                newpop.setIndividual(popIndex, offspring)

            else:
                # Add individual to new population without applying crossover
                newpop.setIndividual(popIndex, parent1)

        return newpop
    def __init__(self,
                 population_size,
                 elitism=True,
                 elitismFraction=0.10,
                 deathFraction=0.10,
                 mutationProb=0.001):

        self.population_size = population_size
        self.elitism = elitism
        self.mutationProb = mutationProb
        self.elistismFraction = elitismFraction
        self.infantMortality = deathFraction

        file = open("boxes.txt")
        fileinput = file.readlines()
        file.close()

        rawboxes = []
        for index in range(len(fileinput)):
            rawboxes.append(fileinput[index].replace("\n", "").split("\t"))
            for index2 in range(len(rawboxes[index])):
                rawboxes[index][index2] = int(rawboxes[index][index2])

        objectBoxes = []
        for item in rawboxes:
            placing_box = box.Box(item[0], item[1], item[2], item[3], item[4])
            objectBoxes.append(placing_box)

        self.population = []
        for iteration in range(self.population_size):
            self.population.append(individual.Individual(
                "random", objectBoxes))
Beispiel #13
0
    def test_crossover_distinct_count(self):
        g_1 = genotype.Genotype.get_random_genotype()
        parent_1 = individual.Individual(g_1)

        g_2 = genotype.Genotype.get_random_genotype()
        parent_2 = individual.Individual(g_2)

        new_g = parent_1.genotype.crossover(parent_2.genotype)
        key_map = {}
        for i in range(len(new_g)):
            if new_g[i] not in key_map:
                key_map[new_g[i]] = 1
            else:
                key_map[new_g[i]] += 1

        for k, v in key_map.iteritems():
            self.assertTrue(v == 1)
Beispiel #14
0
 def __init__(self, n, t):
     self.population = n  #群中の個体数
     self.individual_array = []  #個体を入れる配列
     for i in range(n):  #各個体の挿入
         self.individual_array.append(individual.Individual(dim, t))
     self.individual_array.sort(key=operator.attrgetter('fitness'))
     self.best_fitness = self.individual_array[0].fitness  #群の中の最大評価値
     self.best_fitness_position = self.individual_array[0].position
def selection(population):
    offspring = []
    while len(offspring) < individual.population_number:
        new_offspring = individual.Individual()
        winner = tournament_selection(population)
        for gene in winner.genes:
            new_offspring.genes.append(gene)
        offspring.append(new_offspring)
    return offspring
Beispiel #16
0
def main():
    for trial in range(cf.get_trial()):
        np.random.seed(trial)

        results_list = []  # fitness list
        de_list = []
        """Generate Initial Population"""
        for p in range(cf.get_population_size()):
            de_list.append(id.Individual())
        """Sort Array"""
        de_list = sorted(de_list, key=lambda ID: ID.get_fitness())
        """Find Initial Best"""
        BestPosition = de_list[0].get_position()  # Best Solution
        BestFitness = fn.calculation(BestPosition, 0)
        """↓↓↓Main Loop↓↓↓"""
        for iteration in range(cf.get_iteration()):
            """list copy"""
            candidate_de_list = copy.deepcopy(de_list)
            """Generate New Solutions"""
            for i in range(len(de_list)):

                candidate = copy.deepcopy(de_list[i])
                """select three points (a, b, c)"""
                a = np.random.randint(0, cf.get_population_size())
                while (a == i):
                    a = np.random.randint(0, cf.get_population_size())
                b = np.random.randint(0, cf.get_population_size())
                while (b == i or a == b):
                    b = np.random.randint(0, cf.get_population_size())
                c = np.random.randint(0, cf.get_population_size())
                while (c == i or c == a or c == b):
                    c = np.random.randint(0, cf.get_population_size())
                """Select Random Index (R)"""
                R = np.random.randint(0, cf.get_dimension())

                candidate.generate(a=de_list[a],
                                   b=de_list[b],
                                   c=de_list[c],
                                   R=R)
                candidate.set_fitness(
                    fn.calculation(candidate.get_position(), iteration))

                if candidate.get_fitness() < de_list[i].get_fitness():
                    candidate_de_list[i] = copy.deepcopy(candidate)
            """Sort Array"""
            de_list = sorted(candidate_de_list,
                             key=lambda ID: ID.get_fitness())
            """Rank and Find the Current Best"""
            if de_list[0].get_fitness() < BestFitness:
                BestPosition = de_list[0].get_position()
                BestFitness = fn.calculation(BestPosition, iteration)

            sys.stdout.write("\r Trial:%3d , Iteration:%7d, BestFitness:%.4f" %
                             (trial, iteration, BestFitness))
            results_list.append(str(BestFitness))

        results_writer.writerow(results_list)
Beispiel #17
0
    def __init__(self, populationSize, initialise):

        self.individuals = [None] * populationSize
        self.__populationSize = populationSize

        if initialise:
            for i in range(self.size()):
                newIndividual = individual.Individual()
                newIndividual.generateIndividual()
                self.saveIndividual(i, newIndividual)
Beispiel #18
0
def initpop():
    a = []
    for i in range(Config.get_population_num()):
        tmp = [
            np.random.randint(50, 200),
            np.random.randint(1, 50),
            np.random.randint(50, 200)
        ]
        a.append(individual.Individual(tmp))
    return a
def main():
    result_list = np.zeros(cf.get_iteration())
    for trial in range(cf.get_trial()):
        # np.random.seed(trial)
        np.random.seed()

        cs_list = []
        """Generate Initial Population"""
        for p in range(cf.get_population_size()):
            cs_list.append(id.Individual())
        """Sort List"""
        cs_list = sorted(cs_list, key=lambda ID: ID.get_fitness())
        """Find Initial Best"""
        BestPosition = cs_list[0].get_position()
        BestFitness = fn.calculation(cs_list[0].get_position(), 0)
        """↓↓↓Main Loop↓↓↓"""
        for iteration in range(cf.get_iteration()):
            """Generate New Solutions"""
            for i in range(len(cs_list)):
                cs_list[i].get_cuckoo_dynamic_adaptive(iteration)
                cs_list[i].set_fitness(
                    fn.calculation(cs_list[i].get_position(), iteration))
                """random choice (say j)"""
                j = np.random.randint(low=0, high=cf.get_population_size())
                while j == i:  #random id[say j] ≠ i
                    j = np.random.randint(0, cf.get_population_size())

                # for minimize problem
                if (cs_list[i].get_fitness() < cs_list[j].get_fitness()):
                    cs_list[j].set_position(cs_list[i].get_position())
                    cs_list[j].set_fitness(cs_list[i].get_fitness())
            """Sort (to Keep Best)"""
            cs_list = sorted(cs_list, key=lambda ID: ID.get_fitness())
            """Abandon Solutions (exclude the best)"""
            for a in range(1, len(cs_list)):
                r = np.random.rand()
                if (r < cf.get_Pa()):
                    cs_list[a].abandon_dynamic(iteration)
                    cs_list[a].set_fitness(
                        fn.calculation(cs_list[a].get_position(), iteration))
            """Sort to Find the Best"""
            cs_list = sorted(cs_list, key=lambda ID: ID.get_fitness())

            if cs_list[0].get_fitness() < BestFitness:
                BestFitness = cs_list[0].get_fitness()
                BestPosition = cs_list[0].get_position()

            sys.stdout.write(
                "\r Trial:%3d , Iteration:%7d, BestFitness:%.10f" %
                (trial, iteration, BestFitness))
            result_list[iteration] += BestFitness
    """ export avg result"""
    result_list /= cf.get_trial()
    for iteration in range(cf.get_iteration()):
        result.write('{} {}\n'.format(iteration, result_list[iteration]))
Beispiel #20
0
def newPopulation(offspring, ori_data, m, shape, ori_full_table, obj, weight,
                  size):
    candidates = []
    for syn_data in offspring:
        candidates.append(
            individual.Individual(syn_data, ori_data, m, shape, ori_full_table,
                                  obj, weight))

    new_population = population.Population(ori_data, size, candidates)
    new_population.populationFitness()
    return new_population
Beispiel #21
0
 def crossover(self, parent1, parent2, to):
     ran = rd.randint(1, 100)
     childChromosome = []
     childChromosome.extend(parent1.chromosome[:ran])
     childChromosome.extend(parent2.chromosome[ran:])
     sum_gen = 0
     for i in childChromosome:
         sum_gen += i
     x = [gen / sum_gen for gen in childChromosome]
     child = indi.Individual(x, self.bestWay, to)
     return child
 def init_pop(
         self,
         set_of_city):  #set of city là tập các thành phố có thể làm gen
     for i in range(self.nIndividual):
         set_of_gens = r.sample(set_of_city, self.pop_dimension)
         indi = idv.Individual(set_of_gens, self.nTask)
         a = []
         for j in self.listTask:
             a.append(j.fitness(indi))
         indi.setFactorialCost(a)
         self.pop.append(indi)
Beispiel #23
0
    def crossover(individual1, individual2):

        newSol = individual.Individual()

        for i in range(individual1.size()):
            if random.random() <= Algorithm._uniformRate:
                newSol.setGene(i, individual1.getGene(i))
            else:
                newSol.setGene(i, individual2.getGene(i))

        return newSol
Beispiel #24
0
 def mutation(self, parent, to):
     ran = rd.randint(1, 99)
     ranVal = rd.random()
     childChromosome = []
     childChromosome.extend(parent.chromosome)
     childChromosome[ran] = ranVal
     sum_gen = 0
     for i in childChromosome:
         sum_gen += i
     x = [gen / sum_gen for gen in childChromosome]
     child = indi.Individual(x, self.bestWay, to)
     return child
Beispiel #25
0
def initialise(lambda_, h):
    logging.debug('Initialise population with lambda=%s, h=%s', lambda_, h)

    population = np.empty(lambda_, dtype=object)
    for i in range(lambda_):
        logging.debug('Individual %s', i)
        population[i] = individual.Individual(_random_strategy(h))

    logging.debug('Generated pop:\n%s\n', population)
    assert population.size == lambda_

    return population
Beispiel #26
0
def main():
    for trial in range(cf.get_trial()):
        np.random.seed(trial)

        results_list = []  # fitness list
        cs_list = []
        """Generate Initial Population"""
        for p in range(cf.get_population_size()):
            cs_list.append(id.Individual())
        """Sort List"""
        cs_list = sorted(cs_list, key=lambda ID: ID.get_fitness())
        """Find Initial Best"""
        BestPosition = cs_list[0].get_position()
        BestFitness = fn.calculation(cs_list[0].get_position(), 0)
        """↓↓↓Main Loop↓↓↓"""
        for iteration in range(cf.get_iteration()):
            """Generate New Solutions"""
            for i in range(len(cs_list)):
                cs_list[i].get_cuckoo()
                cs_list[i].set_fitness(
                    fn.calculation(cs_list[i].get_position(), iteration))
                """random choice (say j)"""
                j = np.random.randint(low=0, high=cf.get_population_size())
                while j == i:  # random id[say j] ≠ i
                    j = np.random.randint(0, cf.get_population_size())

                # for minimize problem
                if cs_list[i].get_fitness() < cs_list[j].get_fitness():
                    cs_list[j].set_position(cs_list[i].get_position())
                    cs_list[j].set_fitness(cs_list[i].get_fitness())
            """Sort (to Keep Best)"""
            cs_list = sorted(cs_list, key=lambda ID: ID.get_fitness())
            """Abandon Solutions (exclude the best)"""
            for a in range(1, len(cs_list)):
                r = np.random.rand()
                if r < cf.get_Pa():
                    cs_list[a].abandon()
                    cs_list[a].set_fitness(
                        fn.calculation(cs_list[a].get_position(), iteration))
            """Sort to Find the Best"""
            cs_list = sorted(cs_list, key=lambda ID: ID.get_fitness())

            if cs_list[0].get_fitness() < BestFitness:
                BestFitness = cs_list[0].get_fitness()
                BestPosition = cs_list[0].get_position()

            sys.stdout.write("\r Trial:%3d , Iteration:%7d, BestFitness:%.4f" %
                             (trial, iteration, BestFitness))

            results_list.append(str(BestFitness))

        results_writer.writerow(results_list)
Beispiel #27
0
 def initial(self):
     individuals=[]
     
     for i in range(self.nIndi):
        new_chromosome=[r.random() for i in range(self.lenGen)]
        new_indi=indiv.Individual(new_chromosome,[])
        fitnessTa=[]
        for task in self.tasks:
            fitnessTa.append(task.computeFitness(new_indi))
        new_indi.fitnessTask=fitnessTa
        individuals.append(new_indi)
     self.individuals=individuals
     self.updateRankPopulation()
Beispiel #28
0
    def test_fitness(self):
        drums = sound_file.SoundFile('drums.wav')
        synth = sound_file.SoundFile('synth.wav')

        ind1 = individual.Individual(genotype=None,
                                     neural_mode=None,
                                     effect=None)
        ind1.set_output_sound(drums)
        ind2 = individual.Individual(genotype=None,
                                     neural_mode=None,
                                     effect=None)
        ind2.set_output_sound(synth)

        # make sure sound files are analyzed
        project.Project([ind1.output_sound, ind2.output_sound])

        # mock
        ind1.set_fitness = lambda x: None
        ind2.set_fitness = lambda x: None

        fitness_evaluator = fitness.LocalSimilarityFitness(target_sound=drums)
        fitness_evaluator.evaluate_multiple([ind1, ind2])
Beispiel #29
0
    def initial(self, set_of_city):
        individuals = []

        for i in range(self.nIndi):
            new_chromosome = r.sample(set_of_city, self.lenGen)
            fitnessTa = []
            for task in self.tasks:
                fitnessTa.append(task.computeFitness(new_chromosome))
            new_indi = indiv.Individual(new_chromosome, fitnessTa)

            individuals.append(new_indi)
        self.individuals = individuals
        self.updateRankPopulation()
Beispiel #30
0
def gen_population(size=POP_SIZE):
    half_size = int(size / 2)
    population = []

    #Gen first half: GROW method
    for i in range(0, half_size):
        new_ind = individual.Individual(max_depth=INDIVIDUAL_MAX_DEPTH,
                                        min_depth=INDIVIDUAL_MIN_DEPTH,
                                        size_vars=NUM_VARS)
        population.append(new_ind)

    if size % 2 != 0:
        half_size += 1

    #Gen second half: FULL method
    for i in range(0, half_size):
        new_ind = individual.Individual(max_depth=INDIVIDUAL_MAX_DEPTH,
                                        size_vars=NUM_VARS,
                                        full=True)
        population.append(new_ind)

    return population