def main(fname): fname = "../test.tsp" dist = TSP.get_dist_tsp(fname) nc = TSP.ncities(dist) sol = np.arange(nc) print(dist) best = TSP.fitness(sol, dist) print("Sequential: {}".format(best))
def bestOf(neighbors, p): ### best = neighbors.pop() bestValue = TSP.evaluate(best, p) for neighbor in neighbors: nValue = TSP.evaluate(neighbor, p) if nValue < bestValue: best = neighbor bestValue = nValue return best, bestValue
def calculate(self, instance): if method_of_calculating == 1: TSP.TSP_brute_force("addresses.txt") elif method_of_calculating == 2: TSP.TSP_rnn("addresses.txt") elif method_of_calculating == 3: TSP.TSP_held_karp("addresses.txt") if os.path.isfile("addresses.txt"): with open("addresses.txt", "w") as f: f.truncate() ScrollableLabel.update(self.scroll) salesman.screen_manager.current = "Results"
def steepestAscent(p): current = TSP.randomInit(p) # 'current' is a list of city ids valueC = TSP.evaluate(current, p) while True: neighbors = mutants(current, p) (successor, valueS) = bestOf(neighbors, p) if valueS >= valueC: break else: current = successor valueC = valueS return current, valueC
def firstChoice(p): current = TSP.randomInit(p) # 'current' is a list of city ids valueC = TSP.evaluate(current, p) i = 0 while i < LIMIT_STUCK: successor = randomMutant(current, p) valueS = TSP.evaluate(successor, p) if valueS < valueC: current = successor valueC = valueS i = 0 # Reset stuck counter else: i += 1 return current, valueC
def new_population(problem_type: str, old_population: list, mutated_children: list, evaluator): """ Genereaza o populatie noua dupa urmatoarele reguli: -se pastreaza toti copiii obtinuti dupa mutatii(acestia se repara in cazul problemei de tip knapsack) -locurile libere din populatie se vor umple cu parintii ramasi :param problem_type: poate avea valorile "knapsack" sau "tsp" :param old_population: populatia precedenta :param mutated_children: copiii obtinuti dupa mutatie :param evaluator: in cazul unei probleme de tip Kanpsack va avea contine o lista de obiecte si capacitatea maxima in cazul uneil probleme de tip TSP va contine matricea de distante :return population: noua popullatie obtinuta """ population = [] mc = mutated_children[:] if problem_type == "knapsack": for i in range(len(mc)): if not Knapsack.is_valid(evaluator[0], mc[i], evaluator[1]): mc[i] = Knapsack.make_it_valid(evaluator[0], mc[i], evaluator[1]) population = old_population + mc population = sorted( population, key=lambda x: Knapsack.fitness(evaluator[0], x, evaluator[1]), reverse=True) elif problem_type == "tsp": population = old_population + mc population = sorted(population, key=lambda x: TSP.fitness_TSP(x, evaluator), reverse=False) population = population[:len(old_population)] return population
def best_permutation(spectrogram, norm=1): similarities = get_relative_similarities(spectrogram, norm) TSPpb = TSP.TSP(points=spectrogram, distances=-similarities) solution, _ = TSP_MIP_solving.solveIterativeSubtourEliminationGurobi(TSPpb) permutation = [] #for i in range(len(solution)) : #print(solution[i]) for j in range(len(solution[0])): if solution[0][j] == 1: permutation.append(j) break while len(permutation) < len(solution): #print(permutation) i = permutation[-1] for j in range(len(solution[i])): if solution[i][j] == 1: permutation.append(j) break best_starting_point = permutation[0] worst_similarity = similarities[permutation[-1]][permutation[0]] for i in range(len(permutation) - 1): if similarities[permutation[i]][permutation[i + 1]] < worst_similarity: best_starting_point = i + 1 worst_similarity = similarities[permutation[i]][permutation[i + 1]] permutation = permutation[ best_starting_point:] + permutation[:best_starting_point] return permutation
def setPath(graph, shortestPathtoNodes, PathCost, bot, inputSchedule): global client ''' if any errors occur, check if the path is correctly assigned to bots''' print((bot.ID,0)) #OptPath = tsp.travellingSalesmanProblem(graph, (bot.ID, 0), inputSchedule["{}".format(bot.ID)], shortestPathtoNodes) # calculates the optimum path from src to racks with concurrent.futures.ThreadPoolExecutor() as executor: future = executor.submit(tsp.travellingSalesmanProblem, graph, (bot.ID, 0), inputSchedule["{}".format(bot.ID)], shortestPathtoNodes) OptPath = future.result() # delete the entry from input schedule del inputSchedule["{}".format(bot.ID)] #print(OptPath) # adds the path to bot bot.path = tsp.getPath(graph, (bot.ID, 0), shortestPathtoNodes, OptPath) client.publish("AGV_send", json.dumps(bot.path), qos=2) # MQTT send # set the order complete status to false bot.OrderComplete = False
def randomMutant(current, p): # Apply inversion while True: i, j = sorted([random.randrange(p[0]) for _ in range(2)]) if i < j: curCopy = TSP.inversion(current, i, j) break return curCopy
def main(): filePath = os.path.join(os.getcwd(), "hard.txt") data = Datas.fileData(filePath) popSize = 100 generations = 500 tsp = TSP.TSP(data, popSize) tsp.createPop() globalC = None localC = None generatonCount = 1 while generatonCount < generations: generatonCount += 1 tsp.newGeneration() localC = tsp.best() if globalC is None: globalC = localC elif globalC.fitness > localC.fitness: globalC = localC print("<------------------->") print(generatonCount) print(globalC.fitness) print(localC.fitness) Datas.save(globalC)
def main(): print("hello home") tsp = TSP(0) tsp.readFromFile() globalBest = 5000 globalAvg = 0 N = 10 M = 50 for i in range(10): best, avg = tsp.run(N, M) if (best < globalBest): globalBest = best globalAvg = globalAvg + avg print("results: ", globalBest, " ", globalAvg / 10)
def __calculate_fitness(self, route_class, generation): individual_number = route_class.number route = route_class.route t = tsp.TSP(route, individual_number, generation) result = t.cal_total_distanse() return result
def findShortestPath(markers, robotID): tsp = TSP() # <-- Write a function for calculating the shortest path using the TSP library. # Use the robotID given to the function to determine which point is the start # of the path return path
def initiate_genetic_algorithm(): data = TSP.generateTSP(8) # create a new TSP population = [] for i in range(0,8): population.append(random_soln(data)) analyze_pop(data, population) finalpop = genetic_algorithm(population, data) analyze_pop(data, finalpop)
def __init__(self, gamma=0.99): super(TSPSolver_SA, self).__init__() self.tsp = TSP.TSP() self.cur_state = None # state = [1,3,5,2,4], that is the traveling node order. self.cur_score = None self.temperature = 1.0 self.stop_temperature = 0.0001 self.gamma = gamma self.iter_per_temp = 100 return
def optimize(TSPInstance: TSP, maxIterations): # Initial best solution is simply [0,1,2,...] bestSolution = [i for i in range(TSPInstance.dim)] bestDistance = TSPInstance.tourLength(bestSolution) # Optimize for _ in range(maxIterations): newSolution = bestSolution.copy() if random.random() >= 1 / 2: #TSPInstance.dim: # Switch two cities city1, city2 = 1, 1 while city1 == city2: city1 = random.randint(0, TSPInstance.dim - 1) city2 = random.randint(0, TSPInstance.dim - 1) newSolution[city1] = bestSolution[city2] newSolution[city2] = bestSolution[city1] else: # Switch random number of cities allCities = [i for i in range(TSPInstance.dim)] citiesToSwitch = [] for _ in range(random.randint(2, TSPInstance.dim - 1)): citiesToSwitch.append( allCities.pop(random.randrange(len(allCities)))) for cityIndex in range(len(citiesToSwitch) - 1): newSolution[citiesToSwitch[cityIndex]] = bestSolution[ citiesToSwitch[cityIndex + 1]] newSolution[citiesToSwitch[len(citiesToSwitch) - 1]] = bestSolution[citiesToSwitch[0]] # Get tour distance newDistance = TSPInstance.tourLength(newSolution) # Update best if newDistance < bestDistance: bestDistance = newDistance bestSolution = newSolution.copy() return (bestSolution), bestDistance
def main(): # Create an instance of TSP p = TSP.createProblem() # 'p': (numCities, locations, distanceTable) # Call the search algorithm solution, minimum = firstChoice(p) # Show the problem and algorithm settings TSP.describeProblem(p) TSP.displaySetting("First-Choice") # Report results TSP.displayResult(solution, minimum)
def main(): # Create an instance of TSP p = TSP.createProblem() # 'p': (numCities, locations, table) # Call the search algorithm solution, minimum = steepestAscent(p) # Show the problem and algorithm settings TSP.describeProblem(p) TSP.displaySetting("Steepst-Ascent") # Report results TSP.displayResult(solution, minimum)
def Solve(self, e): self.matPlotInit(self.plotParent, [],[]) startTime = time.time() try: fileRead = tsp.consoleFileHandle(self.fileName) TSPtour = tsp.generateCities(fileRead) TSPtour = tsp.greedySearch(TSPtour) except: TSPtour = self.initialNodes solveTime = int(self.solveTimeBox.GetValue()) while time.time() < (startTime + int(solveTime)): TSPtour = tsp.greedyTwoOptSolver(TSPtour) ''' threading to handle unresponsive window t = threading.Thread(target = self.solverThread, args=(TSPtour, startTime, solveTime)) self.threads.append(t) t.start() t.join() ''' self.coordGenerate(TSPtour) self.matPlotInit(self.plotParent, self.xs, self.ys) self.tourDistance = tsp.totalDistance(TSPtour) self.lengthText.SetLabel("Length: " + str(self.tourDistance)) self.tourString = tsp.TourToString(TSPtour)
def main(): m = v.Model() m.createNodes() m.createDistanceMatrix() m.createTimeMatrix() m.sortNodes() sol = v.Solution() print() #print("******Solution******") b.BestFitTime(sol, m.allNodes, m.time_matrix) sol.CalculateMaxTravelTime(m) #sol.ReportSolution() #print("******TSP Improvement******") for i in range(0, len(sol.trucks)): if len(sol.trucks[i].nodesOnRoute) < 2: continue sol.trucks[i] = t.MinimumInsertions(sol.trucks[i], m.time_matrix) sol.CalculateMaxTravelTime(m) #sol.ReportSolution() #print("******Improved Fleet Utilization******") im.improveFleetUtilization(sol, m) sol.CalculateMaxTravelTime(m) #sol.ReportSolution() bestSol = cloneSolution(sol) while timeit.default_timer() - start_time <= 300.0: #print("******VND classic******") solv = Solver2(m, sol) sol = solv.solve(start_time) sol.CalculateMaxTravelTime(m) #sol.ReportSolution() if sol.max_travel_time < bestSol.max_travel_time: bestSol = cloneSolution(sol) #print("******VND modified******") solv = Solver(m, sol) sol = solv.solve(start_time) sol.CalculateMaxTravelTime(m) #sol.ReportSolution() if sol.max_travel_time < bestSol.max_travel_time: bestSol = cloneSolution(sol) print("******Best Solution******") bestSol.ReportSolution() extractSolution(bestSol)
def find_tour_clever(self, lambdas_remaining, robot, distances_from_robot): weights = deepcopy(self.distances) weights[robot] = distances_from_robot for point in lambdas_remaining + [self.lift]: weights[point][robot] = distances_from_robot[point] tour = TSP.solve_TSP(lambdas_remaining + [self.lift, robot], weights, robot, self.lift) tour_length = 0 point = tour[0] for next_point in tour[1:]: tour_length += weights[point][next_point] point = next_point return (tour_length, tour)
def main(): parser = argparse.ArgumentParser(description="run a genetic algorithm to solve the travelling salesman problem") req = parser.add_argument_group("required arguments") req.add_argument("-i", "--input_file", help="the input .tsp file", required=True) parser.add_argument("-o", "--output_file", help="optional output file for the bests and averages", default=None) parser.add_argument("-mx", "--max_gen", help="the maximum number of generations to run for (default=1000)", type=int, default=1000) parser.add_argument("-ps", "--pop_size", help="the population size (default=50)", default=50, type=int) parser.add_argument("-cr", "--cross_rate", help="the crossover rate (default=1.0)", type=float, default=1.0) parser.add_argument("-mr", "--mut_rate", help="the mutation rate (default=0.1)", type=float, default=0.1) parser.add_argument("-cm", "--cross_mode", help="the mode of crossover, 0 for uox, 1 for pmx (default=0)", choices=[0, 1], type=int, default=0) args = parser.parse_args() try: fh = GraphHandler(args.input_file) except IOError as err: print(err) sys.exit(0) tsp = TSP(fh, args.output_file, args.max_gen, args.pop_size, args.cross_rate, args.mut_rate, args.cross_mode) tsp.genetic_algorithm()
def mutants(current, p): # Apply inversion n = p[0] neighbors = [] count = 0 triedPairs = [] while count <= n: # Pick two random loci for inversion i, j = sorted([random.randrange(n) for _ in range(2)]) if i < j and [i, j] not in triedPairs: triedPairs.append([i, j]) curCopy = TSP.inversion(current, i, j) count += 1 neighbors.append(curCopy) return neighbors
def main(): tsp = TSP.TSP() # Creat a list of cities cities = [ City.City("1", "20833.3333", "17100.0000"), City.City("2", "20900.0000", "17066.6667"), City.City("3", "21300.0000", "13016.6667") ] tsp.plot_cities(cities) pdb.set_trace()
def evaluate_population(problem_type: str, population: list, population_size: int, evaluator): """ Evaluarea populatiei pentru a obtine best, average si worst :param problem_type: poate avea valorile "knapsack" sau "tsp" :param population: populatia evaluata :param population_size: marimea populatiei :param evaluator: in cazul unei probleme de tip Kanpsack va avea contine o lista de obiecte si capacitatea maxima in cazul uneil probleme de tip TSP va contine matricea de distante :return best: cel mai bun fitness din populatie :return avg: valoare medie pentru fitness-ul populatie :return worst: cel mai slab fitness din populatie """ best, avg, worst = 0, 0, 0 if problem_type == "knapsack": eval_population = sorted( population, key=lambda x: Knapsack.fitness(evaluator[0], x, evaluator[1]), reverse=True) best = Knapsack.fitness(evaluator[0], eval_population[0], evaluator[1]) for i in range(population_size): avg += Knapsack.fitness(evaluator[0], eval_population[i], evaluator[1]) avg /= population_size worst = Knapsack.fitness(evaluator[0], eval_population[-1], evaluator[1]) elif problem_type == "tsp": eval_population = sorted(population, key=lambda x: TSP.fitness_TSP(x, evaluator), reverse=False) best = TSP.fitness_TSP(eval_population[0], evaluator) for i in range(population_size): avg += TSP.fitness_TSP(eval_population[i], evaluator) avg /= population_size worst = TSP.fitness_TSP(eval_population[-1], evaluator) return best, avg, worst
def LoadFile(self, e): dialoge = wx.TextEntryDialog(None, '"File Name".tsp', 'Load File') if dialoge.ShowModal() == wx.ID_OK: self.fileName = dialoge.GetValue() fileRead = tsp.consoleFileHandle(self.fileName) problemName = fileRead[0][6:-1] comment = fileRead[1][9:-1] problemType = fileRead[4][18:-1] dimension = fileRead[3][10:-1] self.nameText.SetLabel("Name: " + problemName) self.commentText.SetLabel("Comment: " + comment) self.typeText.SetLabel("Type: " + problemType) self.sizeText.SetLabel("Size: " + dimension + " Nodes") self.timeText.SetLabel("Time: " + datetime.datetime.now().strftime("%H:%M:%S")) self.dateText.SetLabel("Date: " + datetime.datetime.now().strftime("%Y-%m-%d")) TSPtour = tsp.generateCities(fileRead) self.initialNodes = np.trim_zeros(TSPtour) TSPtour = tsp.greedySearch(TSPtour) self.coordGenerate(TSPtour) self.matPlotInit(self.plotParent, self.xs, self.ys) dialoge.Destroy()
def generate_path(cluster, algorithm='greedy', it=100, lifeCount=20): t = TSP() t.cluster = cluster t.it = it t.lifeCount = lifeCount path, diss = t.cal_cluster_path(algorithm=algorithm) path_position = [] for i in range(len(cluster)): path_position.append(cluster[path[i]]) return path, path_position, diss
def main(): ''' Definicao inicial de um vetor de heuristicas Definicao das matrizes [vizinhos] [distancia]--> uma para cada cidade Definicao de um vetor com os nomes das cidades ''' cityNames,heuristicValues,cityANeighbors,cityBNeighbors,cityCNeighbors= configureValues() cityArray=[] counter=0 for i in range(4): counter=0 city= None if i == 0: city=createCity(cityNames[i],cityANeighbors,heuristicValues[i]) elif i==1: city=createCity(cityNames[i], cityBNeighbors, heuristicValues[i]) elif i==2: city=createCity(cityNames[i], cityCNeighbors, heuristicValues[i]) elif i==3: city=createCity(cityNames[i], [], heuristicValues[i]) else: counter=1 if counter==0: cityArray.append(city) for i in range(4): print(cityArray[i]) ''' Criacao do meu objeto TSP--> representante do problema em questao, agregando as cidades existentes ''' problema=TSP.TSP(cityArray) ''' Implementacao do método do Trepa Colinas ''' hillClimb=HillClimbing.HillClimbing(problema) bestCost,percurso=hillClimb.hillClimbing('A') print(bestCost,percurso)
def draw(tour, gen, window, DIST): fon = pg.font.SysFont('monospace', 15) fon = fon.render("%s/%s %s: %s "%(len(set((c.id for c in tour))), len(tour), gen, tsp.score(tour, DIST)), False, (0,255,255)) window.blit(fon, (300,600)) pg.display.init() numcities = len(tour) for i, source in enumerate(tour): dest = tour[(i+1) %numcities] x,a = map(lambda x: normalize(x, (0.0,1800.0), (0,640)), [source.x, dest.x]) y,b = map(lambda x: normalize(x, (0.0,1200.0), (0,640)), [source.y, dest.y]) pg.draw.circle(window, (255,0,0), (int(x),int(y)), 3, 0) pg.draw.line(window, (255,255,255), (x,y), (a,b)) pg.display.flip() return None
def generate_rnd_population(problem_type: str, problem_size: int, population_size: int, evaluator): """ Returneaza o populatie de marime population_size pentru problema problem_type de marime problem_size :param population_size: marimea populatioe :param problem_size: marimea pentru solutia problemei :param problem_type: poate avea valorile "knapsack" sau "tsp" :param evaluator: doar pentru problema rucsacului :return population: populatia noua pentru problema specificata """ population = [] for i in range(population_size): if problem_type == "tsp": population.append(TSP.rdm_solution(problem_size)) elif problem_type == "knapsack": population.append( Knapsack.generate_valid_solution(problem_size, evaluator[0], evaluator[1])) return population
def selection(problem_type: str, population: list, population_size: int, evaluator): """ Aici se selecteaza un parinte din populatia initiala. Se foloseste selectia turnir de marime 5. :param population_size: marimea populatiei :param problem_type: poate avea valorile "knapsack" sau "tsp" :param population: populatia initiala :param evaluator: in cazul unei probleme de tip Kanpsack va avea contine o lista de obiecte si capacitatea maxima in cazul uneil probleme de tip TSP va contine matricea de distante :return parent: lista """ parent1, parent2 = [], [] p = population[:] # copie a populatiei initiale for i in range(2): sample = np.random.default_rng().choice(population_size, size=2, replace=False) possible_parents = [p[s] for s in sample] if sample[0] > sample[1]: sample[0], sample[1] = sample[1], sample[0] del p[sample[0]] del p[sample[1] - 1] population_size -= 2 parent = [] if problem_type == "knapsack": parent = sorted( possible_parents, key=lambda x: Knapsack.fitness(evaluator[0], x, evaluator[1]), reverse=True) elif problem_type == "tsp": parent = sorted(possible_parents, key=lambda x: TSP.fitness_TSP(x, evaluator), reverse=False) if i == 0: parent1 = parent[0] else: parent2 = parent[0] return parent1, parent2
dxy = 10 polyDir = LI.rotDirection(boundingPolygon) crossingAr, crossingCount, tmppos = DMPP.sweep(boundingPolygon, sweepAngle, dxy) openCells, neighbours = DMPP.createCells(crossingAr,crossingCount,dxy,sweepAngle) openShrunkCells = DMPP.shrinkCells(openCells,dxy, sweepAngle) TSP = TSP.Tsp() path = np.array([pos]) subPaths = np.empty(4,dtype='object') transits = np.empty(4,dtype='object') lps = np.empty(4,dtype='object') for i in range(openCells.shape[0]): lastPoint = path[-1] entry, transit = TSP.greedyCellTSP2(openShrunkCells, lastPoint, boundingPolygon, dxy, 5) # note due to cells being monotone to sweep direction, not to the normal of the transit direction, the transit path # plan can cross the polygon boundary # need to write function to hug boundary instead of crossing it # Done - A* handles this transit = np.asarray(transit) if transit != []: path = np.vstack([path,transit]) #tmpStr = openCells[entry[0]][entry[1]] cellDir = LI.rotDirection(openCells[entry[0]]) lp = DMPP.localPoly(openCells[entry[0]],boundingPolygon)#, cellDir, polyDir) subPath = DMPP.genLawnmower(openCells[entry[0]], boundingPolygon,lp,entry[1],sweepAngle,dxy) openCells = np.delete(openCells,entry[0],axis=0) #remove that cell from the list openShrunkCells = np.delete(openShrunkCells, entry[0],axis=0) path = np.vstack([path,subPath]) #for plotting
def analyze_pop(data, population): for person in population: print "%s : %s" % (str(person), str(TSP.tourcost(data, person))) print "-----------------------"
from TSP import * # points : array(20) of tuple; liste de coordonnee des villes points = [(38, 24), (25, 34), (7, 29), (10, 49), (43, 50), (40, 4), (26, 25), (48, 2), (24, 9), (35, 42),(40, 41), (2, 41), (38, 22), (4, 34), (50, 8), (50, 25), (5, 2), (23, 39), (20, 43), (20, 41)] t = TSP(points) t.visit()
def sort_by_fitness(population, data): m = lambda x: TSP.tourcost(data, x) return SelectionSort.selection_sort_by_func(population, m)
import numpy as np import random from TSP import * from Solution import * if __name__ == '__main__': tsp = TSP(10, 1, 100) # print(tsp.getCouts()) print() print("*******glouton**********") print() sol = tsp.glouton1(2) print(sol.getChemin()) print(sol.getFct()) print() print("*******descente*********") print() desc = tsp.descente(2) print(desc.getChemin()) print(desc.getFct()) print() print("******recuit************") print() rec = tsp.recuitSimule(2, 1000) print(rec.getChemin()) print(rec.getFct()) print() print("**********************") print(tsp.getCouts())
def reproduce(dad, mom): child = TSP.partially_mapped_crossover(dad, mom) return child