MH-P2/src/main.py

70 lines
1.9 KiB
Python
Raw Normal View History

2021-04-29 12:33:46 +02:00
from preprocessing import parse_file
2021-05-10 19:25:06 +02:00
from genetic_algorithm import genetic_algorithm
from memetic_algorithm import memetic_algorithm
2021-04-29 12:33:46 +02:00
from sys import argv
from time import time
2021-05-19 20:03:04 +02:00
from itertools import combinations
2021-04-29 12:33:46 +02:00
def execute_algorithm(choice, n, m, data):
2021-05-10 19:25:06 +02:00
if choice == "genetic":
return genetic_algorithm(n, m, data)
elif choice == "memetic":
return memetic_algorithm(m, data)
2021-04-29 12:33:46 +02:00
else:
2021-05-10 19:25:06 +02:00
print("The valid algorithm choices are 'genetic' and 'memetic'")
2021-04-29 12:33:46 +02:00
exit(1)
2021-05-19 20:03:04 +02:00
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):
2021-04-29 12:33:46 +02:00
duplicates = solutions.duplicated().any()
print(solutions)
2021-05-19 20:03:04 +02:00
print(f"Total distance: {fitness}")
2021-04-29 12:33:46 +02:00
if not duplicates:
print("No duplicates found")
2021-05-19 20:03:04 +02:00
print(f"Execution time: {time_delta}")
2021-04-29 12:33:46 +02:00
def usage(argv):
print(f"Usage: python {argv[0]} <file> <algorithm choice>")
print("algorithm choices:")
2021-05-10 19:25:06 +02:00
print("genetic: genetic algorithm")
print("memetic: memetic algorithm")
2021-04-29 12:33:46 +02:00
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()
2021-05-19 20:03:04 +02:00
fitness = get_fitness(solutions, data)
show_results(solutions, fitness, time_delta=end_time - start_time)
2021-04-29 12:33:46 +02:00
if __name__ == "__main__":
main()