def get_ef(self): """Creates a new travelling salesman route evaluation function with the specified class variables. Returns ranges (array): Array of values as specified by N. ef (TravelingSalesmanEvaluationFunction): Evaluation function. """ random = Random() points = [[0 for x in xrange(2)] for x in xrange(self.N)] for i in range(0, len(points)): points[i][0] = random.nextDouble() points[i][1] = random.nextDouble() # create ranges fill = [self.N] * self.N ranges = array('i', fill) if self.subtype == 'route': return ranges, TravelingSalesmanRouteEvaluationFunction(points) elif self.subtype == 'sort': return ranges, TravelingSalesmanSortEvaluationFunction(points)
fit = FixedIterationTrainer(rhc, 200000) score_RHC.append(train(rhc, "RHC", ef, 200000, "test", expt)) print "RHC Inverse of Distance: " + str(ef.value(rhc.getOptimal())) sa = SimulatedAnnealing(1E9, .98, hcp) fit = FixedIterationTrainer(sa, 200000) score_SA.append(train(sa, "SA", ef, 200000, "test", expt)) print "SA Inverse of Distance: " + str(ef.value(sa.getOptimal())) ga = StandardGeneticAlgorithm(225, 40, 5, gap) fit = FixedIterationTrainer(ga, 1000) score_GA.append(train(ga, "GA", ef, 40000, "test", expt)) print "GA Inverse of Distance: " + str(ef.value(ga.getOptimal())) # for mimic we use a sort encoding ef = TravelingSalesmanSortEvaluationFunction(points) fill = [N] * N ranges = array('i', fill) odd = DiscreteUniformDistribution(ranges) df = DiscreteDependencyTree(.1, ranges) pop = GenericProbabilisticOptimizationProblem(ef, odd, df) mimic = MIMIC(150, 20, pop) fit = FixedIterationTrainer(mimic, 1000) score_MIMIC.append(train(mimic, "MIMIC", ef, 4000, "test", expt)) print "MIMIC Inverse of Distance: " + str(ef.value(mimic.getOptimal())) print("Final averaged results") print("RHC= " + str(sum(score_RHC) / len(score_RHC))) print("SA= " + str(sum(score_SA) / len(score_SA))) print("GA= " + str(sum(score_GA) / len(score_GA)))
def solveit(oaname, params): # set N value. This is the number of points N = 50 iterations = 1000 tryi = 1 random = Random() points = [[0 for x in xrange(2)] for x in xrange(N)] for i in range(0, len(points)): points[i][0] = random.nextDouble() points[i][1] = random.nextDouble() ef = TravelingSalesmanRouteEvaluationFunction(points) odd = DiscretePermutationDistribution(N) nf = SwapNeighbor() mf = SwapMutation() cf = TravelingSalesmanCrossOver(ef) hcp = GenericHillClimbingProblem(ef, odd, nf) gap = GenericGeneticAlgorithmProblem(ef, odd, mf, cf) if oaname == "RHC": iterations = int(params[0]) tryi = int(params[1]) oa = RandomizedHillClimbing(hcp) if oaname == "SA": oa = SimulatedAnnealing(float(params[0]), float(params[1]), hcp) if oaname == "GA": iterations=1000 oa = StandardGeneticAlgorithm(int(params[0]), int(params[1]), int(params[2]), gap) if oaname == "MMC": iterations=1000 # for mimic we use a sort encoding ef = TravelingSalesmanSortEvaluationFunction(points) fill = [N] * N ranges = array('i', fill) odd = DiscreteUniformDistribution(ranges) df = DiscreteDependencyTree(.1, ranges) pop = GenericProbabilisticOptimizationProblem(ef, odd, df) oa = MIMIC(int(params[0]), int(params[1]), pop) print "Running %s using %s for %d iterations, try %d" % (oaname, ','.join(params), iterations, tryi) print "="*20 starttime = timeit.default_timer() output = [] for i in range(iterations): oa.train() if i%10 == 0: optimal = oa.getOptimal() score = ef.value(optimal) elapsed = int(timeit.default_timer()-starttime) output.append([str(i), str(score), str(elapsed)]) print 'Inverse of Distance [score]: %.3f' % score print 'train time: %d secs' % (int(timeit.default_timer()-starttime)) scsv = 'tsp-%s-%s.csv' % (oaname, '-'.join(params)) print "Saving to %s" % (scsv), with open(scsv, 'w') as csvf: writer = csv.writer(csvf) for row in output: writer.writerow(row) print "saved." print "="*20 print "Route:" if oaname == 'MMC': optimal = oa.getOptimal() fill = [0] * optimal.size() ddata = array('d', fill) for i in range(0,len(ddata)): ddata[i] = optimal.getContinuous(i) order = ABAGAILArrays.indices(optimal.size()) ABAGAILArrays.quicksort(ddata, order) print order else: path = [] for x in range(0,N): path.append(oa.getOptimal().getDiscrete(x)) print path
def run_traveling_salesman(): # set N value. This is the number of points N = 50 random = Random() points = [[0 for x in xrange(2)] for x in xrange(N)] for i in range(0, len(points)): points[i][0] = random.nextDouble() points[i][1] = random.nextDouble() ef = TravelingSalesmanRouteEvaluationFunction(points) odd = DiscretePermutationDistribution(N) nf = SwapNeighbor() mf = SwapMutation() cf = TravelingSalesmanCrossOver(ef) hcp = GenericHillClimbingProblem(ef, odd, nf) gap = GenericGeneticAlgorithmProblem(ef, odd, mf, cf) iters = [50, 100, 250, 500, 1000, 2500, 5000, 10000, 25000, 50000, 100000] num_repeats = 5 rhc_results = [] rhc_times = [] for i in iters: print(i) for j in range(num_repeats): start = time.time() rhc = RandomizedHillClimbing(hcp) fit = FixedIterationTrainer(rhc, i) fit.train() end = time.time() rhc_results.append(ef.value(rhc.getOptimal())) rhc_times.append(end - start) print "RHC Inverse of Distance: " + str(ef.value(rhc.getOptimal())) # print "Route:" # path = [] # for x in range(0,N): # path.append(rhc.getOptimal().getDiscrete(x)) # print path sa_results = [] sa_times = [] for i in iters: print(i) for j in range(num_repeats): start = time.time() sa = SimulatedAnnealing(1E12, .999, hcp) fit = FixedIterationTrainer(sa, i) fit.train() sa_results.append(ef.value(sa.getOptimal())) sa_times.append(end - start) print "SA Inverse of Distance: " + str(ef.value(sa.getOptimal())) # print "Route:" # path = [] # for x in range(0,N): # path.append(sa.getOptimal().getDiscrete(x)) # print path ga_results = [] ga_times = [] for i in iters: print(i) for j in range(num_repeats): start = time.time() ga = StandardGeneticAlgorithm(2000, 1500, 250, gap) fit = FixedIterationTrainer(ga, i) fit.train() end = time.time() ga_results.append(ef.value(ga.getOptimal())) print "GA Inverse of Distance: " + str(ef.value(ga.getOptimal())) ga_times.append(end - start) # print "Route:" # path = [] # for x in range(0,N): # path.append(ga.getOptimal().getDiscrete(x)) # print path # for mimic we use a sort encoding ef = TravelingSalesmanSortEvaluationFunction(points) fill = [N] * N ranges = array('i', fill) odd = DiscreteUniformDistribution(ranges) df = DiscreteDependencyTree(.1, ranges) pop = GenericProbabilisticOptimizationProblem(ef, odd, df) mimic_results = [] mimic_times = [] for i in iters[0:6]: print(i) for j in range(num_repeats): start = time.time() mimic = MIMIC(500, 100, pop) fit = FixedIterationTrainer(mimic, i) fit.train() end = time.time() mimic_results.append(ef.value(mimic.getOptimal())) print "MIMIC Inverse of Distance: " + str( ef.value(mimic.getOptimal())) # print "Route:" # path = [] # optimal = mimic.getOptimal() # fill = [0] * optimal.size() # ddata = array('d', fill) # for i in range(0,len(ddata)): # ddata[i] = optimal.getContinuous(i) # order = ABAGAILArrays.indices(optimal.size()) # ABAGAILArrays.quicksort(ddata, order) # print order mimic_times.append(end - start) with open('travelingsalesman.csv', 'w') as csvfile: writer = csv.writer(csvfile) writer.writerow(rhc_results) writer.writerow(rhc_times) writer.writerow(sa_results) writer.writerow(sa_times) writer.writerow(ga_results) writer.writerow(ga_times) writer.writerow(mimic_results) writer.writerow(mimic_times) return rhc_results, rhc_times, sa_results, sa_times, ga_results, ga_times, mimic_results, mimic_times
def travelingsalesmanfunc(N, iterations): rhcMult = 1500 saMult = 1500 gaMult = 1 mimicMult = 3 random = Random() points = [[0 for x in xrange(2)] for x in xrange(N)] for i in range(0, len(points)): points[i][0] = random.nextDouble() points[i][1] = random.nextDouble() optimalOut = [] timeOut = [] evalsOut = [] for niter in iterations: ef = TravelingSalesmanRouteEvaluationFunction(points) odd = DiscretePermutationDistribution(N) nf = SwapNeighbor() mf = SwapMutation() cf = TravelingSalesmanCrossOver(ef) hcp = GenericHillClimbingProblem(ef, odd, nf) gap = GenericGeneticAlgorithmProblem(ef, odd, mf, cf) iterOptimalOut = [N, niter] iterTimeOut = [N, niter] iterEvals = [N, niter] start = time.time() rhc = RandomizedHillClimbing(hcp) fit = FixedIterationTrainer(rhc, niter * rhcMult) fit.train() end = time.time() rhcOptimal = ef.value(rhc.getOptimal()) rhcTime = end - start print "RHC Inverse of Distance: optimum: " + str(rhcOptimal) print "RHC time: " + str(rhcTime) #print "RHC Inverse of Distance: " + str(ef.value(rhc.getOptimal())) print "Route:" path = [] for x in range(0, N): path.append(rhc.getOptimal().getDiscrete(x)) print path iterOptimalOut.append(rhcOptimal) iterTimeOut.append(rhcTime) functionEvals = ef.getNumEvals() ef.zeroEvals() iterEvals.append(functionEvals) start = time.time() sa = SimulatedAnnealing(1E12, .999, hcp) fit = FixedIterationTrainer(sa, niter * saMult) fit.train() end = time.time() saOptimal = ef.value(sa.getOptimal()) saTime = end - start print "SA Inverse of Distance optimum: " + str(saOptimal) print "SA time: " + str(saTime) #print "SA Inverse of Distance: " + str(ef.value(sa.getOptimal())) print "Route:" path = [] for x in range(0, N): path.append(sa.getOptimal().getDiscrete(x)) print path iterOptimalOut.append(saOptimal) iterTimeOut.append(saTime) functionEvals = ef.getNumEvals() ef.zeroEvals() iterEvals.append(functionEvals) start = time.time() ga = StandardGeneticAlgorithm(2000, 1500, 250, gap) fit = FixedIterationTrainer(ga, niter * gaMult) fit.train() end = time.time() gaOptimal = ef.value(ga.getOptimal()) gaTime = end - start print "GA Inverse of Distance optimum: " + str(gaOptimal) print "GA time: " + str(gaTime) #print "GA Inverse of Distance: " + str(ef.value(ga.getOptimal())) print "Route:" path = [] for x in range(0, N): path.append(ga.getOptimal().getDiscrete(x)) print path iterOptimalOut.append(gaOptimal) iterTimeOut.append(gaTime) functionEvals = ef.getNumEvals() ef.zeroEvals() iterEvals.append(functionEvals) start = time.time() # for mimic we use a sort encoding ef = TravelingSalesmanSortEvaluationFunction(points) fill = [N] * N ranges = array('i', fill) odd = DiscreteUniformDistribution(ranges) df = DiscreteDependencyTree(.1, ranges) pop = GenericProbabilisticOptimizationProblem(ef, odd, df) start = time.time() mimic = MIMIC(500, 100, pop) fit = FixedIterationTrainer(mimic, niter * mimicMult) fit.train() end = time.time() mimicOptimal = ef.value(mimic.getOptimal()) mimicTime = end - start print "MIMIC Inverse of Distance optimum: " + str(mimicOptimal) print "MIMIC time: " + str(mimicTime) #print "MIMIC Inverse of Distance: " + str(ef.value(mimic.getOptimal())) print "Route:" path = [] optimal = mimic.getOptimal() fill = [0] * optimal.size() ddata = array('d', fill) for i in range(0, len(ddata)): ddata[i] = optimal.getContinuous(i) order = ABAGAILArrays.indices(optimal.size()) ABAGAILArrays.quicksort(ddata, order) print order iterOptimalOut.append(mimicOptimal) iterTimeOut.append(mimicTime) functionEvals = ef.getNumEvals() ef.zeroEvals() iterEvals.append(functionEvals) optimalOut.append(iterOptimalOut) timeOut.append(iterTimeOut) evalsOut.append(iterEvals) return [optimalOut, timeOut, evalsOut]