from genetic_algorithm import * from local_search import local_search from copy import deepcopy def get_best_indices(n, population): select_population = deepcopy(population) best_elements = [] for _ in range(n): best_index, _ = get_best_elements(select_population) best_elements.append(best_index) select_population.pop(best_index) 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): neighbourhood = [] if mode == "all": for individual in population: 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_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_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): population = [generate_individual(n, m, data) for _ in range(n)] population = evaluate_population(population, data) for i in range(max_iterations): if i % 10 == 0: 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) offspring = mutate(offspring, n, data) population = replace_population(population, offspring, mode="stationary") population = evaluate_population(population, data) best_index, _ = get_best_elements(population) return population[best_index]