Replace the population after the local search

This commit is contained in:
coolneng 2021-06-21 21:41:00 +02:00
parent 32eac42e7b
commit 112f40d00f
Signed by: coolneng
GPG Key ID: 9893DA236405AF57
1 changed files with 21 additions and 8 deletions

View File

@ -13,21 +13,34 @@ def get_best_indices(n, population):
return best_elements 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): def run_local_search(n, data, population, mode, probability=0.1):
new_population = [] neighbourhood = []
if mode == "all": if mode == "all":
for individual in population: 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": elif mode == "random":
expected_individuals = len(population) * probability expected_individuals = len(population) * probability
indices = []
for _ in range(expected_individuals): for _ in range(expected_individuals):
random_individual = population[randint(len(population))] random_index = randint(len(population))
new_population.append(local_search(random_individual, n, data)) 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: else:
expected_individuals = len(population) * probability expected_individuals = len(population) * probability
best_indexes = get_best_indices(n=expected_individuals, population=population) best_indices = get_best_indices(n=expected_individuals, population=population)
for element in best_indexes: for element in best_indices:
new_population.append(local_search(population[element], n, data)) 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): 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): for i in range(max_iterations):
if i % 10 == 0: if i % 10 == 0:
best_index, _ = get_best_elements(population) 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 i += 5
parents = select_parents(population, n, mode="stationary") parents = select_parents(population, n, mode="stationary")
offspring = crossover(mode="position", parents=parents, m=m) offspring = crossover(mode="position", parents=parents, m=m)