From 7056534872917f07670da8218409684c0f26c56d Mon Sep 17 00:00:00 2001 From: coolneng Date: Thu, 17 Jun 2021 22:45:59 +0200 Subject: [PATCH] Implement the generational replacement operator --- src/genetic_algorithm.py | 24 ++++++++++++++++++++++-- 1 file changed, 22 insertions(+), 2 deletions(-) diff --git a/src/genetic_algorithm.py b/src/genetic_algorithm.py index 5221cf0..ae587b6 100644 --- a/src/genetic_algorithm.py +++ b/src/genetic_algorithm.py @@ -149,5 +149,25 @@ def tournament_selection(population): return individuals.iloc[best_index] -def genetic_algorithm(n, m, data): - first_solution = generate_first_solution(n, m, data) +def generational_replacement(previous_population, current_population): + new_population = current_population + best_previous_individual = max(previous_population, key=lambda x: x.fitness) + if best_previous_individual not in new_population: + worst_index = new_population.index(min(new_population, key=lambda x: x.fitness)) + new_population[worst_index] = best_previous_individual + return new_population + + +def stationary_replacement(previous_population, current_population): + new_population = previous_population + return new_population + + +def replace_population(previous_population, current_population, mode): + if mode == "generational": + return generational_replacement(previous_population, current_population) + return stationary_replacement(previous_population, current_population) + + +def genetic_algorithm(n, m, data, mode): + population = [generate_individual(n, m, data) for _ in range(n)]