Add fitness calculation

This commit is contained in:
coolneng 2021-05-19 20:03:04 +02:00
parent 9aff3e3e06
commit d88603729a
Signed by: coolneng
GPG Key ID: 9893DA236405AF57
1 changed files with 27 additions and 5 deletions

View File

@ -3,6 +3,7 @@ from genetic_algorithm import genetic_algorithm
from memetic_algorithm import memetic_algorithm from memetic_algorithm import memetic_algorithm
from sys import argv from sys import argv
from time import time from time import time
from itertools import combinations
def execute_algorithm(choice, n, m, data): def execute_algorithm(choice, n, m, data):
@ -15,14 +16,34 @@ def execute_algorithm(choice, n, m, data):
exit(1) exit(1)
def show_results(solutions, time_delta): def get_row_distance(source, destination, data):
distance_sum = solutions["distance"].sum() 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() duplicates = solutions.duplicated().any()
print(solutions) print(solutions)
print("Total distance: " + str(distance_sum)) print(f"Total distance: {fitness}")
if not duplicates: if not duplicates:
print("No duplicates found") print("No duplicates found")
print("Execution time: " + str(time_delta)) print(f"Execution time: {time_delta}")
def usage(argv): def usage(argv):
@ -40,7 +61,8 @@ def main():
start_time = time() start_time = time()
solutions = execute_algorithm(choice=argv[2], n=n, m=m, data=data) solutions = execute_algorithm(choice=argv[2], n=n, m=m, data=data)
end_time = time() 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__": if __name__ == "__main__":