def select_fittest(world, rho): X = world.scores Y = world.population.individuals parents = [x for (_, x) in sorted(zip(X, Y))][:rho] if isinstance(parents[0].gene[0], bool): population = BoolListPopulation(length=0) elif isinstance(parents[0].gene[0], int): population = IntListPopulation(length=0) for parent in parents: population.append(parent) return population
def test(): parents_bool = BoolListPopulation(length=0) parents_bool.append(Individual([True])) parents_bool.append(Individual([True])) children = crossover_mode(population=parents_bool) assert type(children[0].gene) == tuple assert type(children[0].gene[0]) == bool assert children[0].gene parents_chr = ChrListPopulation() parents_chr.append(Individual(gene=['a', 'b', 'c', 'd', 'e'])) parents_chr.append(Individual(gene=['e', 'd', 'c', 'b', 'a'])) children_chr = crossover_1_point(population=parents_chr) parents_chr = ChrListPopulation() parents_chr.append(Individual(gene=['a', 'b', 'c'])) parents_chr.append(Individual(gene=['c', 'b', 'a'])) children_chr = crossover_1_point(population=parents_chr) assert len(children_chr) == 2 parents_chr = ChrListPopulation() parents_chr.append(Individual(gene=['a', 'b', 'c'])) parents_chr.append(Individual(gene=['c', 'b', 'a'])) children_chr = crossover_n_point(population=parents_chr, n=3) assert len(children_chr) == 2 parents_chr = ChrListPopulation() parents_chr.append(Individual(gene=['a', 'b', 'c'])) parents_chr.append(Individual(gene=['c', 'b', 'a'])) children_chr = crossover_dominant(population=parents_chr) assert len(children_chr) == 1 parents_int = IntListPopulation() parents_int.append(Individual(gene=[1])) parents_int.append(Individual(gene=[3])) children_int = crossover_intermediate(population=parents_int) assert len(children_int) == 1 assert children_int[0].gene[0] == 2