def tournament_selection(population): offspring = [] select_parent = lambda x: random.randrange(x) population_size = len(population) for i in range(population_size): parent_one = population[select_parent(population_size)] parent_two = population[select_parent(population_size)] parent_one = Individual(_id=parent_one.uid, chromosome=parent_one.chromosome.copy(), fitness=parent_one.fitness) parent_two = Individual(_id=parent_two.uid, chromosome=parent_two.chromosome.copy(), fitness=parent_two.fitness) if (parent_one.fitness > parent_two.fitness): offspring.insert(i, parent_one) elif (parent_one.fitness < parent_two.fitness): offspring.insert(i, parent_two) else: choice = random.randint(0, 1) if (choice): offspring.insert(i, parent_one) else: offspring.insert(i, parent_two) return offspring
def floating_point_boundary_mutate(individual: Individual, mutation_probability: float, rule_size: int): idx = -1 for gene in individual.chromosome: idx += 1 bound_idx = 0 chance = random.uniform(0, 1) mutate = (chance <= mutation_probability) if (not isinstance(gene, tuple)): if (mutate): gene ^= 1 individual.chromosome[idx] = gene continue bounds = [] for bound in gene: chance = random.uniform(0, 1) mutate = (chance <= mutation_probability) bounds.append(bound) if (mutate): operator = -1 if random.randint(0, 1) else 1 mutation = random.uniform(0.01, 0.15) * operator bounds[bound_idx] = mutate_bound(bound, mutation) bound_idx += 1 individual.chromosome[idx] = (min(bounds), max(bounds))
def create_some_individuals(pg): if pg.connection: individuals = [] fake = Faker() for i in range(0, random.randint(150, 400)): aux = Individual(fake.name(), fake.address(), random.randint(1, 75), round(random.uniform(1, 2.2), 2)) individuals.append(aux) pg.insert_individuals(individuals)
def bit_flip_mutate(individual: Individual, mutation_probabilty: float): idx = -1 for cell in individual.chromosome: idx += 1 chance = random.uniform(0, 1) mutate = (chance <= mutation_probabilty) if (mutate): cell ^= 1 individual.chromosome[idx] = cell else: continue
def rule_based_mutate(individual: Individual, mutation_probability: float, rule_size: int): idx = -1 for cell in individual.chromosome: idx += 1 chance = random.uniform(0, 1) mutate = (chance <= mutation_probability) if (mutate): possibilities = [0, 1, '#'] if ((idx + 1) % rule_size == 0): possibilities = [0, 1] possibilities.remove(cell) cell = random.choice(possibilities) individual.chromosome[idx] = cell
def __initialise_population(self): for i in range(self._population_size): chromosome = self._generate_chromosome() individual = Individual(i, chromosome=chromosome, fitness=0) self._population.insert(i, individual) self._generation = 1
def _initialise_population(self): for i in range(0, self._population_size): chromosome = self._generate_chromosome() self._population.insert( i, Individual(uuid.uuid1().hex, chromosome, 0))