def aco(graph): """Ant Colony Optimisation Algorithm Tests out multiple configurations for ACO parameters""" configs = [ #rho, q, alpha, beta, limit [.03, 1, 1, 3, 500], [.03, 5, 1, 3, 500], [.03, 10, 1, 3, 500], [.03, 25, 1, 3, 500], [.06, 1, 1, 3, 500], [.06, 5, 1, 3, 500], [.06, 10, 1, 3, 500], [.06, 25, 1, 3, 500] ] for index, config in enumerate(configs): print("Test:", index + 1) solver = acopy.Solver(rho=config[0], q=config[1]) timer = acopy.plugins.Timer() solver.add_plugin(timer) colony = acopy.Colony(alpha=config[2], beta=config[3]) tour = solver.solve(graph, colony, limit=config[4]) print("Total time taken:", timer.duration) print("Time per iteration:", timer.time_per_iter) print("Cost of tour:", tour.cost) print("Tour:", tour.path) print("")
def ant_colony_tour(G, start): solver = aco.Solver(rho=0.01, q=1) colony = aco.Colony(alpha=1, beta=5) tour = solver.solve(G, colony, limit=500, gen_size=1000) tour_list = tour.nodes start_index = tour_list.index(int(start)) tour_list = tour_list[start_index:] + tour_list[:start_index] + [ int(start) ] return tour_list
def solve_aco_tsp(resPath): print(resPath) solver = acopy.Solver(rho=.03, q=.5) colony = acopy.Colony(alpha=1, beta=3) problem = tsplib95.load_problem(resPath) G = problem.get_graph() tour = solver.solve(G, colony, limit=100) return tour
def run(self): for i in range(self.numExecution): solver = acopy.Solver(rho=.03, q=1) time = acopy.plugins.Timer() solver.add_plugin(time) colony = acopy.Colony(alpha=1, beta=3) tour = solver.solve(self.nodes, colony, limit=100) self.bestSolutions.append(tour.nodes) self.bestDistances.append(tour.cost) self.executionTimes.append(time.duration) if self.debug: print( f"[{i}] Execution Time: {time.duration}; Distance: {tour.cost}; ", end=" ") print(tour.nodes)
def solve(self, options: dict): solver = aco.Solver(rho=options.get("rho", 0.03), q=options.get("q", 1)) timeLimit_plugin = aco.plugins.TimeLimit(options.get("timeLimit", 10)) solver.add_plugin(timeLimit_plugin) colony = aco.Colony(alpha=options.get("alpha", 1), beta=options.get("beta", 3)) problem = self.instance.to_tsplib95() G = problem.get_graph() tour = solver.solve(G, colony, limit=100) solution = TupList( dict(pos=pos, node=el) for pos, el in enumerate(tour.nodes)) self.solution = Solution(dict(route=solution)) return dict(status_sol=SOLUTION_STATUS_FEASIBLE, status=STATUS_UNDEFINED)
def Ant_Colony_solver(self, G_prime, start_index, cluster_center_drop_off): # alpha = how much pheromone matters # beta = how much distance matters colony = acopy.Colony(alpha=0.6, beta=6) solver = acopy.Solver(rho=.6, q=1) ant_tour = solver.solve(G_prime, colony, limit=10) ant_tour_nodes = ant_tour.nodes cost = ant_tour.cost if (ant_tour_nodes.count(start_index) == 1): ant_start = ant_tour_nodes.index(start_index) ant_tour_nodes = ant_tour_nodes[ ant_start:] + ant_tour_nodes[:ant_start] + [start_index] tour_ant = [(ant_tour_nodes[i], ant_tour_nodes[i + 1]) for i in range(len(ant_tour_nodes) - 1)] rao_tour_2 = compute_tour_paths(self.G, tour_ant) rao_tour_2 = [ rao_tour_2[i] for i in range(len(rao_tour_2) - 1) if rao_tour_2[i] != rao_tour_2[i + 1] ] + [start_index] cost = self.faster_cost_solution(rao_tour_2, cluster_center_drop_off) return rao_tour_2, cost
import tsplib95 import acopy # setting up the environment solver = acopy.Solver(rho=.03, q=1) colony = acopy.Colony(alpha=1, beta=3) # adding a timer to record the total time to find the best path timer = acopy.plugins.Timer() solver.add_plugin(timer) # setting it up so that is prints out each iteration printout = acopy.plugins.Printout() solver.add_plugin(printout) problem = tsplib95.load('problems/pr124.tsp.txt') # loading in the dataset G = problem.get_graph() # changing the dataset so that it can be used by the algorithm tour = solver.solve(G, colony, limit=100) #running the algorithm # printing out relevant information print("Shortest tour: ", tour.cost) print("Best tour: ", tour.nodes) print("Time to complete: ", timer.duration)
import acopy import kiacopy import tsplib95 from kiacopy.parameter import Parameter logger = getLogger() logger.addHandler(StreamHandler()) logger.setLevel(DEBUG) graph_name: str = 'gr17.tsp' problem = tsplib95.load_problem(graph_name) G = problem.get_graph() solver = acopy.Solver() colony = acopy.Colony() solver.solve(G, colony, limit=300) config_path = os.path.join(os.path.dirname(__file__), 'config', 'normal.yaml') parameter: Parameter = Parameter.create(config_path) solver = kiacopy.Solver(parameter=parameter) recorder = kiacopy.plugins.StatsRecorder('results') plotter = kiacopy.utils.plot.Plotter(stats=recorder.stats) # drawer = kiacopy.plugins.DrawGraph(problem=problem, is_each=True, is_label=True, is_consecutive=True) converter = kiacopy.plugins.ConvertStateToJson(save_path='results') solver.add_plugins(recorder, converter) colony = kiacopy.Colony()
def run_algorithm_with_options(program_options: Options, problem_data_array, problem: tsplib95.Problem): program_start_time = timeit.default_timer() # key is the node location and the value is the node id node_location_to_id_dict = dict() # Key is the node id and the value is the node location node_id_to_location_dict = dict() counter = 0 for node in problem_data_array: node_location_to_id_dict[repr(node)] = counter node_id_to_location_dict[counter] = node counter += 1 colors = cycle('bgrcmybgrcmybgrcmybgrcmy') clustered_data = None if program_options.SHOULD_CLUSTER: if program_options.CLUSTER_TYPE is ClusterAlgorithmType.K_MEANS: clustered_data = perform_k_means_clustering( problem_data_array, program_options) if program_options.CLUSTER_TYPE is ClusterAlgorithmType.AFFINITY_PROPAGATION: clustered_data = perform_affinity_propagation( problem_data_array, program_options) if program_options.CLUSTER_TYPE is ClusterAlgorithmType.BIRCH: clustered_data = perform_birch_clustering(problem_data_array, program_options) if program_options.CLUSTER_TYPE is ClusterAlgorithmType.DBSCAN: clustered_data = perform_dbscan_clustering(problem_data_array, program_options) if program_options.CLUSTER_TYPE is ClusterAlgorithmType.OPTICS: clustered_data = perform_optics_clustering(problem_data_array, program_options) else: clustered_data = ClusteredData(nodes=problem_data_array, clusters=list(), program_options=program_options) for node in problem_data_array: cluster = Cluster( cluster_centre=node, nodes=[node], cluster_type=ClusterType.UNCLASSIFIED_NODE_CLUSTER, program_options=program_options) clustered_data.add_unclassified_node(cluster) # Set the overall node dicts onto the clustering object clustered_data.node_location_to_id_dict = node_location_to_id_dict clustered_data.node_id_to_location_dict = node_id_to_location_dict cluster_nodes_dict = clustered_data.get_dict_node_id_location_mapping_aco() logging.debug("%s nodes after clustering", len(cluster_nodes_dict)) # Raise an error if only 1 cluster has come out of this because ACO needs more than 1 cluster to run over if len(cluster_nodes_dict) <= 1: raise ValueError( "Need more than one cluster from the clustering algorithm") aco_tour_improvement_plotter: TourImprovementAnimator = TourImprovementAnimator( cluster_nodes_dict, problem_type="aco", program_options=program_options) before = timeit.default_timer() if program_options.ACO_TYPE is ACOType.ACO_MULTITHREADED: colony = AntColony( nodes=cluster_nodes_dict, distance_callback=aco_distance_callback, alpha=program_options.ACO_ALPHA_VALUE, beta=program_options.ACO_BETA_VALUE, pheromone_evaporation_coefficient=program_options.ACO_RHO_VALUE, pheromone_constant=program_options.ACO_Q_VALUE, ant_count=program_options.ACO_ANT_COUNT, tour_improvement_animator=aco_tour_improvement_plotter, iterations=program_options.ACO_ITERATIONS) answer = colony.mainloop() elif program_options.ACO_TYPE is ACOType.ACO_PY: solver = acopy.Solver(rho=program_options.ACO_RHO_VALUE, q=program_options.ACO_Q_VALUE) colony = acopy.Colony(alpha=program_options.ACO_ALPHA_VALUE, beta=program_options.ACO_BETA_VALUE) logger_plugin = LoggerPlugin() iteration_plotter_plugin = IterationPlotterPlugin( tour_improvement_animator=aco_tour_improvement_plotter) solver.add_plugin(logger_plugin) solver.add_plugin(iteration_plotter_plugin) graph = clustered_data.turn_clusters_into_nx_graph(problem) solution = solver.solve(graph, colony, limit=program_options.ACO_ITERATIONS, gen_size=program_options.ACO_ANT_COUNT) answer = solution.nodes else: raise NotImplementedError() after = timeit.default_timer() dif = after - before logging.debug("Time taken for initial global %s aco %s", program_options.ACO_TYPE, dif) clustered_data.aco_cluster_tour = answer clustered_data.find_nodes_to_move_between_clusters() if program_options.CLUSTER_TOUR_TYPE is InternalClusterPathFinderType.ACO: if program_options.ACO_TYPE is ACOType.ACO_MULTITHREADED: clustered_data.find_tours_within_clusters_using_multithreaded_aco() elif program_options.ACO_TYPE is ACOType.ACO_PY: clustered_data.find_tours_within_clusters_using_acopy() else: raise NotImplementedError() elif program_options.CLUSTER_TOUR_TYPE is InternalClusterPathFinderType.GREEDY_NEAREST_NODE: clustered_data.find_tours_within_clusters_using_greedy_closest_nodes() else: raise NotImplementedError() tour_node_coordinates = clustered_data.get_ordered_nodes_for_all_clusters() # Tour as node ids instead of node locations tour_node_id = [] for node in tour_node_coordinates: tour_node_id.append(node_location_to_id_dict[repr(node)]) clustered_data.node_level_tour = tour_node_id tour_node_id_set = set(tour_node_id) valid = len(tour_node_id) == len(tour_node_id_set) == len( problem_data_array) logging.debug("Tour is valid %s", valid) length_before = calculate_distance_for_tour(tour_node_id, node_id_to_location_dict) logging.debug("Length before 2-opt is %s", length_before) # If the option to run 2opt is set then process 2-opt if program_options.SHOULD_RUN_2_OPT: tsp_2_opt_graph_animator = TourImprovementAnimator( node_id_to_location_dict, problem_type="2-opt", program_options=program_options) before = timeit.default_timer() final_route = run_2_opt( existing_route=tour_node_id, node_id_to_location_dict=node_id_to_location_dict, distance_calculator_callback=calculate_distance_for_tour, tsp_2_opt_animator=tsp_2_opt_graph_animator) after = timeit.default_timer() dif = after - before logging.debug("Time taken for 2-opt %s", dif) length_after = calculate_distance_for_tour(final_route, node_id_to_location_dict) logging.debug("Length after 2-opt is %s", length_after) logging.debug("Final route after 2-opt is %s", final_route) program_end_time = timeit.default_timer() dif = program_end_time - program_start_time logging.debug("Time taken for entire program %s", dif) # These are the tour plotters so should be ignored for time calculations logging.debug("Starting tour plotters") # plot the tours for each cluster clustered_data.plot_all_cluster_tours() # This is the graph that shows all the clusters plot_clustered_graph(colors, cluster_data=clustered_data, program_options=program_options) # Plot all the nodes in the problem, no tour plot_nodes(problem_data_array, program_options=program_options) # Plot the ACO tour of the clusters plot_aco_clustered_tour(answer, clustered_data, program_options=program_options) # Plot the tour pre 2-opt plot_complete_tsp_tour(tour_node_id, node_id_to_location_dict, title="TSP Tour Before 2-opt. Length: " + str(length_before), program_options=program_options) # If 2opt was ran then you can safely print out all the 2-opt related graphs if program_options.SHOULD_RUN_2_OPT: # Plot the tour post 2-opt plot_complete_tsp_tour(final_route, node_id_to_location_dict, title="TSP Tour After 2-opt. Length: " + str(length_after), program_options=program_options) # Plot the tour post 2-opt with node ids printed plot_complete_tsp_tour(final_route, node_id_to_location_dict, title="Final TSP Tour With Node ID", node_id_shown=True, program_options=program_options) if program_options.ANIMATE_IMPROVEMENTS: # Create an animation of the 2-opt incremental improvement tsp_2_opt_graph_animator.animate( output_directory_animation_graphs=program_options. OUTPUT_DIRECTORY_2_OPT_ANIMATION) if program_options.ANIMATE_IMPROVEMENTS: # Create an animation of the aco incremental improvement aco_tour_improvement_plotter.animate( output_directory_animation_graphs=program_options. OUTPUT_DIRECTORY_ACO_ANIMATION) logging.debug("Finished tour plotters")
import acopy import tsplib95 a = 20 coste = [] it_alpha = [] #for i in range (30): # it_alpha.append(a) solver = acopy.Solver(rho=0.55, q=0.7) colony = acopy.Colony(alpha=0.7, beta=4) threshold = acopy.plugins.Threshold(threshold=95345) problem = tsplib95.load_problem( 'C://Users//Vicente//PycharmProjects//TSPproblem//venv//datasetcorto') G = problem.get_graph() tour = solver.solve(G, colony, limit=90) # a = a + 10 print(tour.cost) print(tour.nodes) #coste.append(tour.cost) '''import matplotlib.pyplot as plt plt.plot(it_alpha, coste) plt.show()'''