def TSP(stops, Alg, steps, param, seed=None, coordfile='xycoords.txt'): '''A wrapper function that attempts to optimize the traveling salesperson problem using a specified algorithm. If coordfile exists, a preexisting set of coordinates will be used. Otherwise, a new set of "stops" coordinates will be generated for the person to traverse, and will be written to the specified file.''' # Create the distance matrix, which will be used to calculate # the fitness of a given path if os.path.isfile(coordfile): coords = scipy.genfromtxt(coordfile) distMat = DistanceMatrix(coords) else: distMat = GenerateMap(stops, fname=coordfile, seed=seed) if Alg == 'HC': # param is the number of solutions to try per step bestSol, fitHistory = hc.HillClimber(steps, param, distMat, seed) elif Alg == 'SA': # param is a placeholder bestSol, fitHistory = sa.SimulatedAnnealing(steps, param, distMat, seed) elif Alg == 'MC3': # param is the number of chains bestSol, fitHistory = mc3.MCMCMC(steps, param, distMat, seed) elif Alg == 'GA': # param is the population size bestSol, fitHistory = ga.GeneticAlgorithm(steps, param, distMat, seed) else: raise ValueError('Algorithm must be "HC", "SA", "MC3", or "GA".') outfname = coordfile + '-' + Alg + '-' + \ str(steps) + '-' + str(param) + '.txt' scipy.savetxt(outfname, scipy.array(bestSol), fmt='%i') return bestSol, fitHistory
# Quality: Overall shortest tour found # Route: Array of node_ids in order of travel [node_1,node_2,...] if options.method == "BnB": branch = BranchAndBound.BranchAndBound(cities, options.cutoff) branch.main() quality = branch.minimum route = branch.bestSolution trace = branch.trace elif options.method == "Approx": trace, quality, route = construction_heuristic.nearest_neighbor( params, cities, options.cutoff) elif options.method == "LS1": s = SA.SimulatedAnnealing( cities, 0.00001) # the second argument is the cooling rate, default is 0.001. s.anneal(options.cutoff) quality = s.best_distance route = s.best_route trace = s.trace elif options.method == "LS2": g = genetic.genetic(params, cities, options.cutoff) trace, quality, route = g.evolve() #### ########## #### print(quality) for id in route: print(id, end=" ") print("")