Fix populate offspring

This commit is contained in:
coolneng 2021-06-20 19:48:04 +02:00
parent 5f89731f77
commit efd511e070
Signed by: coolneng
GPG Key ID: 9893DA236405AF57
1 changed files with 20 additions and 17 deletions

View File

@ -59,12 +59,14 @@ def select_distinct_genes(matching_genes, parents, m):
return first_parent_genes, second_parent_genes return first_parent_genes, second_parent_genes
def select_random_genes(matching_genes, parents, m): def select_random_genes(matching_genes, parents):
random_parent = parents[randint(len(parents))] first_parent = parents[0].query("point not in @matching_genes")
distinct_indexes = delete(arange(m), matching_genes) second_parent = parents[1].query("point not in @matching_genes")
genes = random_parent.point.iloc[distinct_indexes].values first_genes = first_parent.point.values
shuffle(genes) second_genes = second_parent.point.values
return genes shuffle(first_genes)
shuffle(second_genes)
return first_genes, second_genes
def select_random_parent(parents): def select_random_parent(parents):
@ -110,7 +112,6 @@ def populate_offspring(values):
offspring = offspring.append(aux) offspring = offspring.append(aux)
offspring["distance"] = 0 offspring["distance"] = 0
offspring["fitness"] = 0 offspring["fitness"] = 0
offspring = offspring[1:]
return offspring return offspring
@ -122,24 +123,26 @@ def uniform_crossover(parents, m):
return viable_offspring return viable_offspring
def position_crossover(parents, m): def position_crossover(parents):
matching_genes = get_matching_genes(parents) matching_genes = get_matching_genes(parents)
shuffled_genes = select_random_genes(matching_genes, parents, m) first_genes, second_genes = select_random_genes(matching_genes, parents)
first_offspring = populate_offspring(values=[matching_genes, shuffled_genes]) first_offspring = populate_offspring(values=[matching_genes, first_genes])
second_offspring = populate_offspring(values=[matching_genes, shuffled_genes]) second_offspring = populate_offspring(values=[matching_genes, second_genes])
return [first_offspring, second_offspring] return first_offspring, second_offspring
def crossover(mode, parents, m): def crossover(mode, parents, m):
split_parents = list(zip(*[iter(parents)] * 2)) split_parents = list(zip(*[iter(parents)] * 2))
offspring = [] offspring = []
if mode == "uniform": if mode == "uniform":
for i in range(len(split_parents)): for element in split_parents:
offspring.append(uniform_crossover(split_parents[i], m)) offspring.append(uniform_crossover(element, m))
offspring.append(uniform_crossover(split_parents[i], m)) offspring.append(uniform_crossover(element, m))
else: else:
crossover_func = partial(position_crossover, m=m) for element in split_parents:
offspring = [*map(crossover_func, split_parents)] first_offspring, second_offspring = position_crossover(element)
offspring.append(first_offspring)
offspring.append(second_offspring)
return offspring return offspring