MH-P2/src/main.py
2021-05-19 20:43:57 +02:00

70 lines
1.9 KiB
Python
Executable File

from preprocessing import parse_file
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):
if choice == "genetic":
return genetic_algorithm(n, m, data)
elif choice == "memetic":
return memetic_algorithm(m, data)
else:
print("The valid algorithm choices are 'genetic' and 'memetic'")
exit(1)
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(f"Total distance: {fitness}")
if not duplicates:
print("No duplicates found")
print(f"Execution time: {time_delta}")
def usage(argv):
print(f"Usage: python {argv[0]} <file> <algorithm choice>")
print("algorithm choices:")
print("genetic: genetic algorithm")
print("memetic: memetic algorithm")
exit(1)
def main():
if len(argv) != 3:
usage(argv)
n, m, data = parse_file(argv[1])
start_time = time()
solutions = execute_algorithm(choice=argv[2], n=n, m=m, data=data)
end_time = time()
fitness = get_fitness(solutions, data)
show_results(solutions, fitness, time_delta=end_time - start_time)
if __name__ == "__main__":
main()