def test_tour_length(): coords=[(0,0),(0,1),(1,0),(1,1)] matrix=tsp.cartesian_matrix(coords) assert 2 == tsp.tour_length(matrix,[0,1]) assert 2 == tsp.tour_length(matrix,[0,2]) assert (1+sqrt(2)+1) == tsp.tour_length(matrix,[0,1,2]) assert (1+sqrt(2)+1+sqrt(2)) == tsp.tour_length(matrix,[0,1,2,3])
def main(): size = 100 coords = tsp.random_coordinates(size) distances = tsp.euclid_distances(coords) evaluation = lambda t: tsp.tour_length(distances, t) init_func = lambda: tsp.random_tour(len(coords)) result = tsp.tsp_hillclimb_restart_overall_iterations(init_func,evaluation,tsp.swapped_cities_generator,\ max_iterations=100000,restart_limit=None,verbose=0) print("Best evaluation:", result['best_eval']) print("Is local optimum:", result['local_optimum']) print("Num of evaluations:", result['num_of_evaluations']) print("Num of restarts:", result['num_of_restarts']) tsp.draw_tour(coords, result["best_tour"], img_file="tour_best_swapping_cities.png") size = 100 coords = tsp.random_coordinates(size) distances = tsp.euclid_distances(coords) evaluation = lambda t: tsp.tour_length(distances, t) init_func = lambda: tsp.random_tour(len(coords)) result = tsp.tsp_hillclimb_restart_overall_iterations(init_func,evaluation,tsp.reversed_sections_generator,\ max_iterations=100000,restart_limit=None,verbose=0) print("Best evaluation:", result['best_eval']) print("Is local optimum:", result['local_optimum']) print("Num of evaluations:", result['num_of_evaluations']) print("Num of restarts:", result['num_of_restarts']) tsp.draw_tour(coords, result["best_tour"], img_file="tour_best_reversing_sections.png")
def main(): size = 50 coords = tsp.random_coordinates(size) distances = tsp.euclid_distances(coords) evaluation = lambda t: tsp.tour_length(distances, t) init_func = lambda: tsp.random_tour(len(coords)) result = tsp_sa.tsp_hillclimb_simulated_annealing_restart(init_func, evaluation, tsp.swapped_cities_generator,\ max_iterations=10000000, annealing_prob=tsp_sa.prob, annealing_temp=1.0, annealing_temp_decrease=0.95,\ restart_limit=10, verbose=1) print("Best evaluation:", result['best_eval']) print("Is local optimum:", result['local_optimum']) print("Num of evaluations:", result['num_of_evaluations']) print("Num of restarts:", result['num_of_restarts']) tsp.draw_tour(coords,result["best_tour"],img_file="tour_best_sa_swapping_cities.png") size = 50 coords = tsp.random_coordinates(size) distances = tsp.euclid_distances(coords) evaluation = lambda t: tsp.tour_length(distances, t) init_func = lambda: tsp.random_tour(len(coords)) result = tsp_sa.tsp_hillclimb_simulated_annealing_restart(init_func, evaluation, tsp.reversed_sections_generator,\ max_iterations=10000000, annealing_prob=tsp_sa.prob, annealing_temp=1.0, annealing_temp_decrease=0.95,\ restart_limit=10, verbose=1) print("Best evaluation:", result['best_eval']) print("Is local optimum:", result['local_optimum']) print("Num of evaluations:", result['num_of_evaluations']) print("Num of restarts:", result['num_of_restarts']) tsp.draw_tour(coords,result["best_tour"],img_file="tour_best_sa_reversing_sections.png")
def get_parameters(): global build_dict_thread, polyline_dict cycles = int(request.form['cycles']) algorithm = request.form['algorithm'] start_temp = float(request.form['start_temp']) alpha = float(request.form['alpha']) move_operator = request.form['move_operator'] start_city = int(request.form['start']) mode = request.form['mode'] selected_cities = request.form['selected_cities'] return_list = selected_cities.split(',') id_list = [] current_score=[] animation_coords = [] nodes2 = [] animation_steps = [] #Extract city ids and names into lists then look up coordinates and build #a dictionary with id as the key and a tuple of coordinates as the value for i in range(len(return_list)): if i%2 == 0: id_list.append(int(return_list[i])) for id in id_list: nodes2.append(model.session.query(model.City).filter_by(id = id).one()) coords = tsp.read_coords_db(nodes2) i=0 coord_dict = {} for id in id_list: coord_dict[id]=coords[i] i+= 1 #Build the distance matrix. The distance matrix is of the form #{(i, j): dist, ... (i,j): dist} if mode == "as_the_crow_flies": matrix = tsp.distance_matrix2(coords, id_list) elif mode == "roads": matrix = tsp.road_matrix(polyline_dict, id_list) elif mode == "airline": matrix = tsp.air_matrix(coords, id_list) else: return "Error" #Choose our algorithm init_function =lambda: tsp.init_random_tour(id_list)#returns shuffled objective_function=lambda tour: -tsp.tour_length(matrix,tour) #note negation move_dict={"swapped_cities": tsp.swapped_cities, "reversed_sections": tsp.reversed_sections} if algorithm == "hillclimb": result = tsp.hillclimb(init_function, move_dict[move_operator], objective_function, cycles) num_evaluations, best_score, best, animation_steps, current_score = result elif algorithm == "hill_restart": result = tsp.hillclimb_and_restart(init_function, move_dict[move_operator], objective_function, cycles) num_evaluations, best_score, best, animation_steps, current_score = result elif algorithm == "nearest": result = tsp.greedy(matrix, start_city) num_evaluations, best_score, best = result elif algorithm == "annealing": result = tsp.anneal(init_function, move_dict[move_operator], objective_function, cycles,start_temp,alpha) num_evaluations, best_score, best, animation_steps, current_score = result else: print "error" return "error" tour_coords = tsp.drawtour_on_map2(coord_dict, best) #coordinates for each step for i in range(len(animation_steps)): animation_coords.append(tsp.drawtour_on_map2(coord_dict, animation_steps[i])) tour_cities = convert_tour_to_city(best) if mode == "roads" and not build_dict_thread.isAlive(): poly_list, data = poly_line_tour2(best) poly_animation_steps = polyline_animation_steps2(animation_steps) else: poly_list = [] poly_animation_steps = [] results = {"iterations" : num_evaluations, "best_score" : best_score, "route" : best, "tour_coords": tour_coords, "tour_cities": tour_cities, "animation_coords": animation_coords, "current_score": current_score, "poly_list": poly_list, "poly_animation_steps": poly_animation_steps} data = json.dumps(results) return data
import tsp import profile coords=tsp.read_coords(file('city500.txt')) init_function=lambda: tsp.init_random_tour(len(coords)) matrix=tsp.cartesian_matrix(coords) objective_function=lambda tour: -tsp.tour_length(matrix,tour) move_operator=tsp.reversed_sections max_iterations=1000 #profile.run('tsp.run_hillclimb(init_function,move_operator,objective_function,max_iterations)') profile.run('tsp.run_evolve(init_function,move_operator,objective_function,max_iterations)')
def length_ratio(cities): #The ratio of the tour lengths for nn_tsp and alltours_tsp algorithms return tsp.tour_length(nn_tsp(cities)) / tsp.tour_length(tsp.alltours_tsp(cities))
def length_ratio(cities): #The ratio of the tour lengths for nn_tsp and alltours_tsp algorithms return tsp.tour_length(nn_tsp(cities)) / tsp.tour_length( tsp.alltours_tsp(cities))
x = ch[t][0] y = ch[t][1] if xOld: imd.line((xOld, yOld, x, y), fill = (0, 0, 0), width = 4) xOld = x yOld = y imd.line((xOld, yOld, ch[first][0], ch[first][1]), fill = (0, 0, 0), \ width = 4) def plotCities(imd, ch, s = 5): """For a given city hash, draws the points onto a img draw object. """ for x,y in ch.values(): imd.ellipse((x - s, y - s, x + s, y + s), \ fill = (0, 0, 0)) if __name__ == "__main__": cl = loadCityFile("./files/cityPixels.txt") tour = loadTour("tour.txt") cities = fileio.readCities("./files/cities.txt") tourNum = loadTourNum(tour, cities) dist = fileio.readDistances("./files/distMiles.txt") plotTour(tour, cl) print "Tour length:" + str(tsp.tour_length(dist,tourNum))
def get_parameters(): global build_dict_thread, polyline_dict cycles = int(request.form['cycles']) algorithm = request.form['algorithm'] start_temp = float(request.form['start_temp']) alpha = float(request.form['alpha']) move_operator = request.form['move_operator'] start_city = int(request.form['start']) mode = request.form['mode'] selected_cities = request.form['selected_cities'] return_list = selected_cities.split(',') id_list = [] current_score = [] animation_coords = [] nodes2 = [] animation_steps = [] #Extract city ids and names into lists then look up coordinates and build #a dictionary with id as the key and a tuple of coordinates as the value for i in range(len(return_list)): if i % 2 == 0: id_list.append(int(return_list[i])) for id in id_list: nodes2.append(model.session.query(model.City).filter_by(id=id).one()) coords = tsp.read_coords_db(nodes2) i = 0 coord_dict = {} for id in id_list: coord_dict[id] = coords[i] i += 1 #Build the distance matrix. The distance matrix is of the form #{(i, j): dist, ... (i,j): dist} if mode == "as_the_crow_flies": matrix = tsp.distance_matrix2(coords, id_list) elif mode == "roads": matrix = tsp.road_matrix(polyline_dict, id_list) elif mode == "airline": matrix = tsp.air_matrix(coords, id_list) else: return "Error" #Choose our algorithm init_function = lambda: tsp.init_random_tour(id_list) #returns shuffled objective_function = lambda tour: -tsp.tour_length(matrix, tour ) #note negation move_dict = { "swapped_cities": tsp.swapped_cities, "reversed_sections": tsp.reversed_sections } if algorithm == "hillclimb": result = tsp.hillclimb(init_function, move_dict[move_operator], objective_function, cycles) num_evaluations, best_score, best, animation_steps, current_score = result elif algorithm == "hill_restart": result = tsp.hillclimb_and_restart(init_function, move_dict[move_operator], objective_function, cycles) num_evaluations, best_score, best, animation_steps, current_score = result elif algorithm == "nearest": result = tsp.greedy(matrix, start_city) num_evaluations, best_score, best = result elif algorithm == "annealing": result = tsp.anneal(init_function, move_dict[move_operator], objective_function, cycles, start_temp, alpha) num_evaluations, best_score, best, animation_steps, current_score = result else: print "error" return "error" tour_coords = tsp.drawtour_on_map2(coord_dict, best) #coordinates for each step for i in range(len(animation_steps)): animation_coords.append( tsp.drawtour_on_map2(coord_dict, animation_steps[i])) tour_cities = convert_tour_to_city(best) if mode == "roads" and not build_dict_thread.isAlive(): poly_list, data = poly_line_tour2(best) poly_animation_steps = polyline_animation_steps2(animation_steps) else: poly_list = [] poly_animation_steps = [] results = { "iterations": num_evaluations, "best_score": best_score, "route": best, "tour_coords": tour_coords, "tour_cities": tour_cities, "animation_coords": animation_coords, "current_score": current_score, "poly_list": poly_list, "poly_animation_steps": poly_animation_steps } data = json.dumps(results) return data