Change CLI using argparse

This commit is contained in:
coolneng 2021-06-21 03:46:35 +02:00
parent f4dd4700c7
commit 924e4c9638
Signed by: coolneng
GPG Key ID: 9893DA236405AF57
1 changed files with 23 additions and 12 deletions

View File

@ -4,16 +4,16 @@ 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(choice, n, m, data):
if choice == "genetic":
return genetic_algorithm(n, m, data)
elif choice == "memetic":
return memetic_algorithm(m, data)
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:
print("The valid algorithm choices are 'genetic' and 'memetic'")
exit(1)
return memetic_algorithm(n, m, data, hybridation=args.hybridation)
def get_row_distance(source, destination, data):
@ -47,19 +47,30 @@ def show_results(solutions, fitness, time_delta):
def usage(argv):
print(f"Usage: python {argv[0]} <file> <algorithm choice>")
print(f"Usage: python {argv[0]} <file> <algorithm choice> <")
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():
if len(argv) != 3:
usage(argv)
n, m, data = parse_file(argv[1])
args = parse_arguments()
n, m, data = parse_file(args.file)
start_time = time()
solutions = execute_algorithm(choice=argv[2], n=n, m=m, data=data)
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)