From d88603729ac78cc28cd8d820da2817ddf6730d78 Mon Sep 17 00:00:00 2001 From: coolneng Date: Wed, 19 May 2021 20:03:04 +0200 Subject: [PATCH] Add fitness calculation --- src/main.py | 32 +++++++++++++++++++++++++++----- 1 file changed, 27 insertions(+), 5 deletions(-) diff --git a/src/main.py b/src/main.py index 9286f13..a56e594 100755 --- a/src/main.py +++ b/src/main.py @@ -3,6 +3,7 @@ from genetic_algorithm import genetic_algorithm from memetic_algorithm import memetic_algorithm from sys import argv from time import time +from itertools import combinations def execute_algorithm(choice, n, m, data): @@ -15,14 +16,34 @@ def execute_algorithm(choice, n, m, data): exit(1) -def show_results(solutions, time_delta): - distance_sum = solutions["distance"].sum() +def get_row_distance(source, destination, data): + row = data.query( + """(source == @source and destination == @destination) or \ + (source == @destination and destination == @source)""" + ) + return row["distance"].values[0] + + +def get_fitness(solutions, data): + counter = 0 + comb = combinations(solutions.index, r=2) + for index in list(comb): + elements = solutions.loc[index, :] + counter += get_row_distance( + source=elements["point"].head(n=1).values[0], + destination=elements["point"].tail(n=1).values[0], + data=data, + ) + return counter + + +def show_results(solutions, fitness, time_delta): duplicates = solutions.duplicated().any() print(solutions) - print("Total distance: " + str(distance_sum)) + print(f"Total distance: {fitness}") if not duplicates: print("No duplicates found") - print("Execution time: " + str(time_delta)) + print(f"Execution time: {time_delta}") def usage(argv): @@ -40,7 +61,8 @@ def main(): start_time = time() solutions = execute_algorithm(choice=argv[2], n=n, m=m, data=data) end_time = time() - show_results(solutions, time_delta=end_time - start_time) + fitness = get_fitness(solutions, data) + show_results(solutions, fitness, time_delta=end_time - start_time) if __name__ == "__main__":