Ejemplo n.º 1
0
    def move_gene_in_chromosome(self,
                                original_fitness: float) -> TSP_Chromosome:
        """
        Move a random gene to the point in the chromosome that will produce the best result.
        """
        (best_new_chrom, best_new_fitness) = (None, None)
        len_chrom = len(self)
        for i in sample(range(len_chrom), min(3, len_chrom)):
            gene_before = self[i - 1]
            removed_gene = self[i]
            i_p_1 = (i + 1) % len_chrom
            gene_after = self[i_p_1]
            fitness_after_removal = original_fitness - gene_before.distance_to(removed_gene) \
                                                     - removed_gene.distance_to(gene_after)  \
                                                     + gene_before.distance_to(gene_after)

            # noinspection PyArgumentList
            partial_chromosome: TSP_Chromosome = GA_World.chromosome_class(
                self[:i] + self[i + 1:])
            (new_chrom,
             new_fitness) = partial_chromosome.add_gene_to_chromosome(
                 fitness_after_removal, removed_gene)
            if best_new_fitness is None or new_fitness < best_new_fitness:
                (best_new_chrom, best_new_fitness) = (new_chrom, new_fitness)

        return GA_World.chromosome_class(best_new_chrom)
Ejemplo n.º 2
0
 def gen_individual():
     chromosome_list: List = sample(GA_World.gene_pool,
                                    Cycle_World.cycle_length)
     Cycle_World.individuals += 1
     individual = GA_World.individual_class(
         GA_World.chromosome_class(chromosome_list))
     return individual
Ejemplo n.º 3
0
 def gen_individual(self):
     # Use ceil to ensure we have enough genes.
     zeros = [0]*ceil(self.chromosome_length/2)
     ones = [1]*ceil(self.chromosome_length/2)
     mixture = sample(zeros + ones, self.chromosome_length)
     chromosome_tuple: Tuple[Gene] = GA_World.chromosome_class(Gene(id, val) for (id, val) in zip(count(), mixture))
     individual = GA_World.individual_class(chromosome_tuple)
     return individual
Ejemplo n.º 4
0
 def gen_individual():
     path_methods = [TSP_Chromosome.random_path]
     if gui_get('Greedy'):
         path_methods.append(TSP_Chromosome.greedy_path)
     if gui_get('Min spanning tree'):
         path_methods.append(TSP_Chromosome.spanning_tree_path)
     gen_path_method = choice(path_methods)
     chromosome_list: List = gen_path_method()
     chromo = GA_World.chromosome_class(chromosome_list)
     individual = GA_World.individual_class(chromo, generator=gen_path_method, original_sequence=chromosome_list)
     return individual
Ejemplo n.º 5
0
    def mutate(self) -> Individual:
        chromosome = self.chromosome
        satisfied = self.satisfied

        no_mutation = gui_get('no_mutation')
        move_unsatisfied = gui_get('move_unsatisfied_gene')
        exchange_unsatisfied_genes = gui_get('exchange_unsatisfied_genes')
        reverse_subseq = gui_get('reverse_subseq')

        mutations_options = move_unsatisfied + exchange_unsatisfied_genes + reverse_subseq + no_mutation
        mutation_choice = randint(0, mutations_options)

        if mutation_choice <= move_unsatisfied:
            unsatisfied_indices = [
                i for i in range(len(satisfied)) if not satisfied[i]
            ]
            if not unsatisfied_indices:
                return self
            new_chromosome = chromosome.move_unsatisfied_gene(
                unsatisfied_indices)

        elif mutation_choice <= move_unsatisfied + exchange_unsatisfied_genes:
            new_chromosome = chromosome.exchange_unsatisfied_genes(satisfied)

        elif mutation_choice <= move_unsatisfied + exchange_unsatisfied_genes + reverse_subseq:
            new_chromosome = chromosome.reverse_subseq()

        else:
            return self

        new_individual = GA_World.individual_class(new_chromosome)
        return new_individual
Ejemplo n.º 6
0
    def mutate(self) -> Individual:

        if randint(0, 100) <= gui_get('invert selection'):
            new_chromosome = self.chromosome.invert_a_gene()
            new_individual = GA_World.individual_class(new_chromosome)
            return new_individual
        else:
            return self
Ejemplo n.º 7
0
    def mutate(self) -> Individual:
        chromosome = self.chromosome
        if randint(0, 100) <= SimEngine.gui_get('replace_gene'):
            (chromosome, self.fitness,
             _) = chromosome.replace_gene_in_chromosome(self.fitness)

        elif randint(0, 100) <= SimEngine.gui_get('reverse_subseq'):
            chromosome = chromosome.reverse_subseq()
            self.fitness = self.compute_fitness()

        self.chromosome: Chromosome = GA_World.chromosome_class(chromosome)
        return self
Ejemplo n.º 8
0
 def create_node(self):
     new_point = self.create_random_agent(color=Color('white'), shape_name='node', scale=1)
     new_point.set_velocity(TSP_World.random_velocity())
     # If the same individual is in the population
     # multiple times, don't process it more than once.
     updated_chromos = set()
     for ind in self.population:
         old_chromo = ind.chromosome
         if old_chromo not in updated_chromos:
             # noinspection PyUnresolvedReferences
             (new_chromo, ind.fitness) = old_chromo.add_gene_to_chromosome(ind.fitness, new_point)
             # noinspection PyArgumentList
             ind.chromosome = GA_World.chromosome_class(new_chromo)
             updated_chromos.add(new_chromo)
Ejemplo n.º 9
0
 def delete_node(self):
     # Can't use choice with a set.
     node = sample(World.agents, 1)[0]
     # If the same individual is in the population
     # multiple times, don't process it more than once.
     updated_chromos = set()
     for ind in self.population:
         old_chromo = ind.chromosome
         if old_chromo not in updated_chromos:
             new_chromo_list = list(old_chromo)
             new_chromo_list.remove(node)
             new_chromo = GA_World.chromosome_class(new_chromo_list)
             ind.chromosome = new_chromo
             updated_chromos.add(new_chromo)
     node.delete()
Ejemplo n.º 10
0
    def update_cycle_lengths(self, cycle_length):
        for ind in self.population:
            # To keep PyCharm's type checker happy
            assert isinstance(ind.chromosome, Loop_Chromosome)
            chromosome: Loop_Chromosome = ind.chromosome
            if cycle_length < len(chromosome):
                new_chromosome = chromosome[:cycle_length]
                ind.fitness = ind.compute_fitness()
            else:
                available_genes = GA_World.agents - set(chromosome)
                new_genes = sample(available_genes,
                                   cycle_length - len(chromosome))
                new_chromosome = chromosome
                for gene in new_genes:
                    (new_chromosome, ind.fitness, _) = \
                        chromosome.add_gene_to_chromosome(ind.fitness, gene)

            ind.chromosome = GA_World.chromosome_class(new_chromosome)
Ejemplo n.º 11
0
    def mutate(self) -> Individual:

        mutation_operations = []
        chromo = self.chromosome
        assert isinstance(chromo, TSP_Chromosome)
        if gui_get('Move element'):
            mutation_operations.append(chromo.move_gene_in_chromosome)
        if gui_get('2-Opt'):
            mutation_operations.append(chromo.two_opt)

        # If no mutation operations have been selected, return the individual unchnged.
        if not mutation_operations:
            return self
        else:
            # Otherwise, apply one of the selected mutation operation.
            operation = choice(mutation_operations)
            # Both of the current mutation operations require self.fitness as their argument.
            new_chromosome = operation(self.fitness)
            new_individual = GA_World.individual_class(new_chromosome)
            return new_individual
Ejemplo n.º 12
0
    def mutate(self) -> Individual:
        chromosome = self.chromosome
        if randint(0, 100) <= SimEngine.gui_get('exchange_genes'):
            assert isinstance(self.chromosome, Segregation_Chromosome)
            chromosome = chromosome.exchange_genes(self.satisfactions)

        elif randint(0, 100) <= SimEngine.gui_get('move_unhappy_gene'):
            candidate_indices = Segregation_Individual.unhappy_gene_value_indices(self.satisfactions)
            if not candidate_indices:
                return self
            chromosome = chromosome.move_unhappy_gene(candidate_indices)

        elif randint(0, 100) <= SimEngine.gui_get('move_gene'):
            chromosome = chromosome.move_gene()

        elif randint(0, 100) <= SimEngine.gui_get('reverse_subseq'):
            chromosome = chromosome.reverse_subseq()

        self.chromosome = GA_World.chromosome_class(chromosome)

        (self.satisfactions, self.fitness) = self.chromosome.compute_chromosome_fitness()
        return self
Ejemplo n.º 13
0
 def gen_individual():
     chromosome_tuple: Tuple[Gene] = GA_World.chromosome_class(
         Gene(id, val) for (id, val) in zip(count(), GA_World.gene_pool))
     individual = GA_World.individual_class(chromosome_tuple)
     return individual
Ejemplo n.º 14
0
 def gen_individual(self):
     chromosome_list: List = sample(World.agents, self.cycle_length)
     individual = GA_World.individual_class(
         GA_World.chromosome_class(chromosome_list))
     return individual
Ejemplo n.º 15
0
 def mutate(self) -> Individual:
     new_chromosome = (self.chromosome).replace_gene_in_chromosome(
         self.fitness)
     new_individual = GA_World.individual_class(new_chromosome)
     return new_individual