From 112f40d00f45a479cdb41b569e6b2972950c8441 Mon Sep 17 00:00:00 2001 From: coolneng Date: Mon, 21 Jun 2021 21:41:00 +0200 Subject: [PATCH] Replace the population after the local search --- src/memetic_algorithm.py | 29 +++++++++++++++++++++-------- 1 file changed, 21 insertions(+), 8 deletions(-) diff --git a/src/memetic_algorithm.py b/src/memetic_algorithm.py index 2f25fcc..9a07df0 100644 --- a/src/memetic_algorithm.py +++ b/src/memetic_algorithm.py @@ -13,21 +13,34 @@ def get_best_indices(n, population): return best_elements +def replace_elements(current_population, new_population, indices): + for item in indices: + current_population[item] = new_population[item] + return current_population + + def run_local_search(n, data, population, mode, probability=0.1): - new_population = [] + neighbourhood = [] if mode == "all": for individual in population: - new_population.append(local_search(individual, n, data)) + neighbourhood.append(local_search(individual, n, data)) + new_population = neighbourhood elif mode == "random": expected_individuals = len(population) * probability + indices = [] for _ in range(expected_individuals): - random_individual = population[randint(len(population))] - new_population.append(local_search(random_individual, n, data)) + random_index = randint(len(population)) + random_individual = population[random_index] + neighbourhood.append(local_search(random_individual, n, data)) + indices.append(random_index) + new_population = replace_elements(population, neighbourhood, indices) else: expected_individuals = len(population) * probability - best_indexes = get_best_indices(n=expected_individuals, population=population) - for element in best_indexes: - new_population.append(local_search(population[element], n, data)) + best_indices = get_best_indices(n=expected_individuals, population=population) + for element in best_indices: + neighbourhood.append(local_search(population[element], n, data)) + new_population = replace_elements(population, neighbourhood, best_indices) + return new_population def memetic_algorithm(n, m, data, hybridation, max_iterations=100000): @@ -36,7 +49,7 @@ def memetic_algorithm(n, m, data, hybridation, max_iterations=100000): for i in range(max_iterations): if i % 10 == 0: best_index, _ = get_best_elements(population) - run_local_search(n, data, population, mode=hybridation) + population = run_local_search(n, data, population, mode=hybridation) i += 5 parents = select_parents(population, n, mode="stationary") offspring = crossover(mode="position", parents=parents, m=m)