def from_x_y(xys): cost_matrix = torch.zeros(len(xys), len(xys), dtype=torch.float) forbidden = torch.zeros(len(xys), len(xys), dtype=torch.float) for index1, (x1, y1) in enumerate(xys): for index2, (x2, y2) in enumerate(xys): cost_matrix[index1, index2] = dist(x1, y1, x2, y2) if index1 == index2: forbidden[index1, index2] = 1 return tsp.TSP(cost_matrix, forbidden)
def calculate_evo(self): import tsp if not self.points: return t = tsp.TSP(self.points) p, x, m, g = int(self.pop_size.get()), float( self.x_chance.get()), float(self.m_chance.get()), int( self.generations.get()) t.evaluate(p, x, m, g)
def calculate_random(self): import tsp if not self.points: return t = tsp.TSP(self.points) p, x, m, g = int(self.pop_size.get()), float( self.x_chance.get()), float(self.m_chance.get()), int( self.generations.get()) #t.evaluate(p, x, m, g) t.alternative_method(int((p * x + p) * g))
def main(): parser = argparse.ArgumentParser() parser.add_argument("dataset", help="Path to graph dataset (.gml format)") parser.add_argument("-n", "--number", type=int, help="Number of solutions to generate", required=True) parser.add_argument("-v", "--verbose", action='store_true', help="Show all vertices value") parser.add_argument("-t", "--timeit", action='store_true', help="Print execution time of chosen method") parser.add_argument("-p", "--plot", action='store_true', help="Plot the graphs generated") args = parser.parse_args() graph = tsp.TSP(args.dataset) if (args.plot): tsp.plot(graph.graph, 0, "Graph") for i in range(args.number): t = process_time() (hamiltonian_graph, hamiltonian_path) = graph.twice_around() elapsed_time = process_time() - t print("TSP solution #%d: %d" % (i + 1, tsp.sum_weights(hamiltonian_graph))) if args.verbose: print("Path: ", end="") for j in range(len(hamiltonian_path)): if j != 0: print(" -> ", end="") print(hamiltonian_path[j], end="") print() if (args.timeit): print("Time: %.5f seconds" % elapsed_time) if (args.plot): tsp.plot(hamiltonian_graph, i + 1, "Hamiltonian Graph #" + str(i + 1)) print() if args.plot: plt.show()
def main(domain_type=2): """ main function to call search code """ # 1) Instantiate Specific Domain if domain_type == 2: my_domain = route.Route() else: my_domain = tsp.TSP() # 2) Instantiate the General Search Class my_search = Search(my_domain) # 3) Search my_search.run_search()
def TestTSP(): tsp_test = tsp.TSP() curr_time = time.time() tsp_test.OptimizeRoute() print(f"Test 1 passed.\nElapsed time: {time.time() - curr_time} seconds\n") cities_file = open("cities.txt", "r") tsp_test = tsp.TSP(cities_file) curr_time = time.time() tsp_test.OptimizeRoute() print(f"Test 2 passed.\nElapsed time: {time.time() - curr_time} seconds\n") cities_file.close() cities_list = [[1.5, 7.2, 5.2, 9.9], [2.28, 6.66, 8.34, 4.04]] tsp_test = tsp.TSP(cities_list) curr_time = time.time() tsp_test.OptimizeRoute() print(f"Test 3 passed.\nElapsed time: {time.time() - curr_time} seconds\n") cities_array = np.array([[2.28, 6.66, 8.34, 4.04], [1.5, 7.2, 5.2, 9.9]]) tsp_test = tsp.TSP(cities_array) curr_time = time.time() tsp_test.OptimizeRoute() print(f"Test 4 passed.\nElapsed time: {time.time() - curr_time} seconds\n")
def __init__(self, master=None): super().__init__(master) self.pack() self.master.title('Traveling Salesman Problem - Examples') self.tsp = tsp.TSP() self.step_counter = 0 self.step_total = 0 self.callback = None self.algo_stepfunction = self.tsp.step_bruteforce self.figure = Figure(figsize=(7, 5), dpi=100, tight_layout=True) self.axes = self.figure.add_subplot(111) self.axes.set_axis_off() self.create_widgets() self.randomize()
self.least_fitted.append(fittest) def get_avg(self, individuals): rating_sum = sum(indiv.rating for indiv in individuals) self.avg.append(rating_sum / len(individuals)) def get_most_fitted(self, individual): self.most_fitted.append(individual) if __name__ == "__main__": from random import shuffle v = [0, 1, 2, 3, 4] #1843 indvs = [] import tsp t = tsp.TSP([(11, 26), (41, 9), (73, 28), (58, 46), (29, 42), (0, 0)]) for i in range(100): c = v[:] shuffle(c) indiv = Individual(v, c) indiv.rating = t.rate_solution(c) indvs.append(indiv) indvs.sort(key=lambda x: x.rating) from matplotlib import pyplot as plt lol = [] r = Tournament(indvs, delete=False) for i in range(100): lol.append(r.next()) import collections occ = collections.Counter(lol) ll = [(k, occ[k]) for k in occ if k is not None or k.rating is not None]
from tsp_solver.greedy import solve_tsp from mcts_solver import MST_node, mcts_solver, root_node, full_permutation import tsp import numpy as np node_lis = [0, 1, 2, 3, 4] tsp1 = tsp.TSP(20, 2) root1 = root_node(tsp1) best_tour1, mcts_score1 = mcts_solver(tsp1, root1, computation_power=3000) tour_len1 = tsp1.tour_length(best_tour1) D = tsp1.dist_mat() # D = [ # [], # [10], # [15, 35], # [20, 25, 30] # ] path = solve_tsp(D) path.append(path[0]) print('The tour length found by mcts is:') print(tour_len1) print('The best tour found by mcts is:') print((np.array([best_tour1]) + 1)[0]) print('The tour length found by optimal solver is:') print(tsp1.tour_length(path)) print('The best tour found by optimal solver is:') print((np.array([path]) + 1)[0])
import sys import tsp import drawing import tspstep as step import sa import tspstep as steps print('running on {}'.format(sys.platform)) t = tsp.TSP(8, True) steps.createnew(t) d = t.clone drawing.draw(d, 1, False) SA = sa.SimulatedAnnealing(t, 50, 1500, 50, 50) SA.runAlgorithm() drawing.draw(SA.globalBest, 2, True)
def createReportJson(self): c3dValObj = c3dValidation.c3dValidation(self.workingDirectory) self.measurementNames = c3dValObj.getValidC3dList(True) fileNames = c3dValObj.getValidC3dList(False) self.null = None if fileNames != []: # empty list means c3d does not contain Plugin-Gait created 'LAnkleAngles' or there are no events self.frameRate, self.analogRate = getFrameAndAnalogRateFromC3D( fileNames[0]) ts = self.getTimeseriesResults() print "--------------------Timeseries OK--------------------------------" mapProfile = map2.MAP(self.workingDirectory) gvs = self.getGVSResults(mapProfile) print "--------------------GVS OK--------------------------------" gps = self.getGPSResults(mapProfile) print "--------------------GPS OK--------------------------------" emgExp = self.getEMGResults() print "--------------------EMG--------------------------------" # Events ev = self.getEvents() print "--------------------events OK--------------------------------" # #MetaData metaDataObj = metadata.Metadata(self.workingDirectory, self.modelledC3dfilenames, self.subjectMetadata, self.creationDate) md = metaDataObj.medatadaInfo() print "--------------------metadata OK--------------------------------" # Subject sub = metaDataObj.subjectInfo() print "--------------------subjectInfo OK--------------------------------" # Project proj = metaDataObj.projectInfo() print "--------------------proj OK--------------------------------" # TSP tspObj = tsp.TSP(self.workingDirectory) tsparams = tspObj.export() print "--------------------TSP OK--------------------------------" # Measurements measObj = measurements.Measurements(self.workingDirectory) mea = measObj.measurementInfo(self.extra_settings) print "--------------------Measurements OK--------------------------------" # Create json root = { "results": ts + gvs + gps + emgExp + tsparams, "events": ev, "metadata": md, "measurements": mea, "clientId": self.clientId, "subject": sub, "project": proj } return root else: root = {} return root
b.hovered = True else: b.hovered = False def loop(self): clock = pygame.time.Clock() while self.gamestate: clock.tick(60) self.checkMenu() self.draw() for event in pygame.event.get(): if event.type == QUIT or (event.type == KEYDOWN and event.key == K_ESCAPE): self.gamestate = False elif event.type == MOUSEBUTTONUP: if not self.bounding_box.collidepoint(event.pos): self.set_circle(event.pos) else: self.check_clicked( ) #tu jeszcze sprawdzenie nacisniecia przycisku if __name__ == "__main__": #points = [(117, 262), (418, 93), (733, 287), (583, 460), (299, 423)]#1001 m = MapCreator2000() import tsp if m.points: t = tsp.TSP(m.points) t.evaluate()