def invasive_weed(self, iteration, iter_max, e, sigma_init, sigma_fin, N_min, N_max, member, **kwargs): """Add new individuals to the population via methods of invasive weed algorithm.""" seeds = [] sigma = ((iter_max - iteration) / iter_max) sigma = pow(sigma, e) sigma = sigma * (sigma_init - sigma_fin) + sigma_fin fitness_max = self.current_population[-1].fitness fitness_min = self.current_population[0].fitness ratio = (fitness_max - member.fitness) / (fitness_max - fitness_min) N = int(N_min + (N_max - N_min) * ratio) for _ in range(N): seed = Chromosome(self.chromosome_size, self.fitness_function) for i in range(self.chromosome_size): random_value = random.uniform(member.genes[i] - sigma, member.genes[i] + sigma) seed.genes[i] = random_value seed.resize_invalid_genes() seed.calculate_fitness(**kwargs) seeds.append(seed) return seeds
def create_initial_population(self): """Create members of the first population randomly.""" for _ in range(self.pop_size): individual = Chromosome(self.chromosome_size, self.fitness_function) if not self.pool: individual.calculate_fitness() self.add_individual_to_pop(individual) if self.pool: p = Pool(self.pool_size) manager = Manager() lock = manager.Lock() counter = manager.Value('i', 0) def pool_function(inside_lock, inside_counter, inside_member): inside_lock.acquire() inside_counter.value += 1 inside_lock.release() fitness_value = inside_member.calculate_fitness( gpu=inside_counter.value % 4) return fitness_value func = partial(pool_function, lock, counter) fitness_values = p.map(func, self.current_population[:]) for value, member in zip(fitness_values, self.current_population[:]): member.fitness = value p.terminate()
def add_new_individual(self, *args, **kwargs): """Add new individual with fitness value to the current population.""" individual = Chromosome(self.chromosome_size, self.fitness_function) individual.calculate_fitness(**kwargs) return individual
def __init__(self, pop_size, chromosome_size, fitness_function, pool, pool_size): super().__init__(pop_size, chromosome_size, fitness_function, pool, pool_size) self.global_best_individual = Chromosome(self.chromosome_size, self.fitness_function)
def crossover(self, selection_function, *args, **kwargs): """Add new individuals to the population with crossover.""" child_1 = Chromosome(self.chromosome_size, self.fitness_function) child_2 = Chromosome(self.chromosome_size, self.fitness_function) parent_1 = selection_function(self) parent_2 = selection_function(self) crossover_index = random.randrange(1, self.chromosome_size - 1) child_1.genes = np.concatenate((parent_1.genes[:crossover_index], parent_2.genes[crossover_index:]), axis=None) child_2.genes = np.concatenate((parent_2.genes[:crossover_index], parent_1.genes[crossover_index:]), axis=None) child_1.calculate_fitness(**kwargs) child_2.calculate_fitness(**kwargs) return [child_1, child_2]