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 from argparse import ArgumentParser def execute_algorithm(args, n, m, data): if args.algorithm == "genetic": return genetic_algorithm( n, m, data, select_mode=args.selection, crossover_mode=args.crossover ) else: return memetic_algorithm(n, m, data, hybridation=args.hybridation) 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]} <") print("algorithm choices:") print("genetic: genetic algorithm") print("memetic: memetic algorithm") exit(1) def parse_arguments(): parser = ArgumentParser() parser.add_argument("file", help="dataset of choice") subparsers = parser.add_subparsers(dest="algorithm") parser_genetic = subparsers.add_parser("genetic") parser_memetic = subparsers.add_parser("memetic") parser_genetic.add_argument("crossover", choices=["uniform", "position"]) parser_genetic.add_argument("selection", choices=["generational", "stationary"]) parser_memetic.add_argument("hybridation", choices=["all", "random", "best"]) return parser.parse_args() def main(): args = parse_arguments() n, m, data = parse_file(args.file) start_time = time() solutions = execute_algorithm(args, n, m, data) end_time = time() fitness = get_fitness(solutions, data) show_results(solutions, fitness, time_delta=end_time - start_time) if __name__ == "__main__": main()