From c450d658700af0a2babbc2c9e3b21d145ddf39ac Mon Sep 17 00:00:00 2001 From: coolneng Date: Fri, 18 Jun 2021 18:54:34 +0200 Subject: [PATCH] Add population evaluation with multiprocessing --- src/genetic_algorithm.py | 23 +++++++++++++++++++++-- 1 file changed, 21 insertions(+), 2 deletions(-) diff --git a/src/genetic_algorithm.py b/src/genetic_algorithm.py index 6ce7ffd..fe0dd47 100644 --- a/src/genetic_algorithm.py +++ b/src/genetic_algorithm.py @@ -2,6 +2,10 @@ from numpy import sum, append, arange, delete, where from numpy.random import randint, choice, shuffle from pandas import DataFrame from math import ceil +from functools import partial +from multiprocessing import Pool + +from preprocessing import parse_file def get_row_distance(source, destination, data): @@ -40,7 +44,8 @@ def evaluate_individual(individual, data): max_distance = element_df["distance"].astype(float).max() fitness = append(arr=fitness, values=max_distance) distances = distances.query(f"source != {item} and destination != {item}") - return sum(fitness) + individual["fitness"] = sum(fitness) + return individual def select_distinct_genes(matching_genes, parents, m): @@ -188,5 +193,19 @@ def replace_population(prev_population, current_population, mode): return stationary_replacement(prev_population, current_population) -def genetic_algorithm(n, m, data, mode): +def evaluate_population(population, data, cores=4): + fitness_func = partial(evaluate_individual, data=data) + with Pool(cores) as pool: + evaluated_population = pool.map(fitness_func, population) + return evaluated_population + + +def genetic_algorithm(n, m, data, mode, max_iterations=100000): population = [generate_individual(n, m, data) for _ in range(n)] + population = evaluate_population(population, data) + for _ in range(max_iterations): + pass + + +n, m, data = parse_file("data/GKD-c_11_n500_m50.txt") +genetic_algorithm(n=10, m=5, data=data, mode="")