def main(): args = parse_args() echo_args(args) vrp = VRP(*read_file(os.path.abspath(args.input))) game = GameFactory.create_game(args.game) cost, routes, dist = ga_social_interaction_vrp( vrp, game, population_size=args.pop_size, num_generations=args.num_gens, mutation_rate=args.mut_rate, crossover_rate=args.cro_rate, wgt_solution=1 - args.wgt_social, wgt_social=args.wgt_social, debug=args.debug) solution = { 'input': os.path.basename(args.input), 'total distance': cost, 'routes': [{ f'route {i+1}': [l + 1 for l in r] } for i, r in enumerate(routes)] } if args.debug: print(json.dumps(solution)) if args.output: with open(args.output, 'w') as outfile: json.dump(solution, outfile)
def update_fitness(population: List[Individual], vrp: VRP, game: Game, wgt_solution: float, wgt_social: float): max_solution_fitness = -999999 max_social_fitness = -999999 for idv_1, idv_2 in random_pairs(population): main_chromosome_1, strategy_chromosome_1 = idv_1.chromosomes() main_chromosome_2, strategy_chromosome_2 = idv_2.chromosomes() # solution fitness (route costs) solution_fitness_1 = vrp.total_distance(main_chromosome_1) solution_fitness_2 = vrp.total_distance(main_chromosome_2) # social interaction fitness (payoffs from games) social_fitness_1, social_fitness_2 = game.play(strategy_chromosome_1, strategy_chromosome_2) # set solution and social fitness idv_1.update_fitness_parts(solution_fitness_1, social_fitness_1) idv_2.update_fitness_parts(solution_fitness_2, social_fitness_2) # update max solution and social fitness (used for normalization) max_solution_fitness = max(max_solution_fitness, max(solution_fitness_1, solution_fitness_2)) max_social_fitness = max(max_social_fitness, max(social_fitness_1, social_fitness_2)) # update total fitness using weights and max fitness terms for idv in population: idv.update_total_fitness(max_solution_fitness, max_social_fitness, wgt_solution, wgt_social)
def vrp(): mat, capacity, cities_nb, vehicules_nb, demand_matrix, coords = get_mat() #VRP vrp = VRP(vehicules_nb,cities_nb) if mat is None: vrp.create_data_model() else: vrp.pass_matrix(mat) print(vrp.data) vrp_solve(vrp)
def call_stats_dev(arg1): print('VRP ou CVRP : ', end='') vrp_type = input() if vrp_type.upper() != 'VRP' and vrp_type.upper() != 'CVRP': raise Exception("Type de VRP non reconnu") dataset_name = None print('Chemin vers le fichier contenant les path : ', end='') path = input() if(os.path.isfile(path) == False): raise Exception("Chemin invalide") allPath = get_all_path(path) for line in allPath: dataset_name = os.path.basename(line[0]) mat, capacity, cities_nb, vehicules_nb, demand_matrix, coords = from_file_to_adj_matr(line[0]) if vrp_type.upper() == 'VRP': # VRP vrp = VRP(vehicules_nb,cities_nb) vrp.pass_matrix(mat) elif vrp_type.upper() == 'CVRP': # CVRP vrp = CVRP(vehicules_nb,cities_nb) vrp.pass_matrix(mat, demand_matrix,capacity) path_cost = line[1] if(os.path.isfile(path_cost) == False): raise Exception("Chemin invalide") cost = get_particular_info(path_cost, 'cost') print(line[0], line[1]) execution_quality_cities(algos_metaheuristic, vrp, cities_nb, dataset_name, cost)
def ga_social_interaction_vrp(vrp: VRP, game: Game, population_size: int, num_generations: int, mutation_rate=0.7, crossover_rate=0.7, wgt_solution=0.5, wgt_social=0, debug=False): population = random_population(vrp, game, population_size) for gen in range(num_generations): update_fitness(population, vrp, game, wgt_solution, wgt_social) offspring = [] for i in range(population_size // 2): p1 = tournament_select(population) p2 = tournament_select(population) if random.random( ) < crossover_rate and p1._main_chromosome != p2._main_chromosome: c1, c2 = reproduce(p1, p2) c1 = mutate(c1, mutation_rate) c2 = mutate(c2, mutation_rate) offspring.append(c1) offspring.append(c2) update_fitness(offspring, vrp, game, wgt_solution, wgt_social) population = replace(population, offspring) if debug and gen % 100 == 0: print(fittest_solution(population)) fittest_stn = fittest_solution(population) return (fittest_stn._solution_fitness, [ route for route in vrp.decode_routes(fittest_stn._main_chromosome) ], list(map(lambda x: x._strategy_chromosome, population)))
#from ..vrp import VRP import sys sys.path.append("..") from vrp import VRP k = 5 # number of vehicles ############# DFJ ############### vrp_dfj = VRP() vrp_dfj.setup_preset_data(file_name="../validation_data_A/A-n32-k5.vrp", number_of_vehicles=k) vrp_dfj.gap_goal = 0.1 vrp_dfj.subtour_type = 'DFJ' vrp_dfj.setup() # vrp_dfj.model.Params.TimeLimit = 5*60 vrp_dfj.model.Params.Threads = 2 vrp_dfj.optimize() vrp_dfj.visualize() if input("continue? ").lower() not in ['y', 'yes']: sys.exit() ############## MTZ ############### vrp_mtz = VRP() vrp_mtz.setup_preset_data(file_name="../validation_data_A/A-n32-k5.vrp", number_of_vehicles=k) vrp_mtz.gap_goal = 0.1
#from ..vrp import VRP import sys sys.path.append("..") import numpy as np from vrp import VRP n = 5 # number of customers k = 1 # number of vehicles Q = 32 ############## DFJ ############### vrp_dfj = VRP() vrp_dfj.setup_random_data(number_of_customers=n, number_of_vehicles=k, vehicle_capacity=Q, demand_lower=1, demand_higher=10, seed=420) vrp_dfj.gap_goal = 0.1 vrp_dfj.subtour_type = 'DFJ' vrp_dfj.setup() vrp_dfj.optimize() vrp_dfj.visualize() if input("continue?").lower() not in ['y', 'yes']: sys.exit()
def call_stats(arg1): print('VRP ou CVRP : ', end='') vrp_type = input() if vrp_type.upper() != 'VRP' and vrp_type.upper() != 'CVRP': raise Exception("Type de VRP non reconnu") dataset_name = None if arg1.upper()== "TIMECITIESQ": random = False else: random = query_yes_no("Générer une matrice aléatoirement ?") if not random: print('Chemin vers le fichier : ', end='') path = input() if(os.path.isfile(path) == False): raise Exception("Chemin invalide") dataset_name = os.path.basename(path) mat, capacity, cities_nb, vehicules_nb, demand_matrix, coords = from_file_to_adj_matr(path) else: print('Entrez le nombre de villes : ', end='') cities_nb = int(input()) print('Entrez le nombre de véhicules : ', end='') vehicules_nb = int(input()) dataset_name = "random-k" + str(vehicules_nb) + "-n" + str(cities_nb) if vrp_type.upper() == 'VRP': # VRP vrp = VRP(vehicules_nb,cities_nb) if random: vrp.create_data_model() else: vrp.pass_matrix(mat) elif vrp_type.upper() == 'CVRP': # CVRP vrp = CVRP(vehicules_nb,cities_nb) if random: vrp.create_data_model() else: vrp.pass_matrix(mat, demand_matrix,capacity) if arg1.upper()== "TIMESOLUTIONS": solutionsLimitArray = [] while True: print('Appuyez sur enter pour arreter l ajout de solution... ') print('Entrez un nombre dans le tableau de solutions locales max : ', end='') tempLimit = input() if tempLimit.isnumeric(): solutionsLimitArray.append(int(tempLimit)) else: print("Fin de l'entrée, tableau : " , solutionsLimitArray) break execution_time_solutions(algos_metaheuristic, vrp, solutionsLimitArray, dataset_name) elif arg1.upper()== "TIMEVEHICULES": for i in tqdm(range(vehicules_nb)): execution_time_vehicules(algos_metaheuristic, vrp, i, dataset_name) elif arg1.upper()== "TIMECITIES": for i in tqdm(range(cities_nb)): execution_time_cities(algos_metaheuristic, vrp, i, dataset_name) elif arg1.upper()== "TIMECITIESQ": print('Chemin vers le fichier de la solution: ', end='') path_cost = input() if(os.path.isfile(path_cost) == False): raise Exception("Chemin invalide") cost = get_particular_info(path_cost, 'cost') execution_quality_cities(algos_metaheuristic, vrp, cities_nb, dataset_name, cost) print('Appuyez sur entrée pour continuer...') input()
from vrp import VRP from cvrp import CVRP filename = 'PL' if __name__ == '__main__': print("\nVRP: ") vrp = VRP(filename) vrp.calculate_best_base_location() print("\nCVRP: ") cvrp = CVRP(filename) cvrp.calculate_best_base_location()
from vrp import VRP vrp = VRP() random = True formulation = ["capacitated", "timed"][1] subtour_type = ['DFJ', 'MTZ'][0] n = 15 # number of customers k = 5 # number of vehicles Q = 50 goal_gap = 0.0 plot_all_nodes = False vrp.gap_goal = goal_gap if formulation is "capacitated": if random: vrp.subtour_type = subtour_type vrp.setup_random_data(number_of_customers=n, number_of_vehicles=k, vehicle_capacity=Q, x_range=20, y_range=20, demand_lower=1, demand_higher=10, seed=420) else: vrp.setup_preset_data(file_name="validation_data_A/A-n32-k5.vrp",