示例#1
0
def Opt2(tour: List[Location.Location]):

    oldTour = tour.copy()
    newTour = tour.copy()
    shortestDist = Location.FindTourLength(tour)

    i = 0
    j = 0
    ij = len(tour)**2
    while (i < len(tour)):
        j = i + 1
        if miscGlobal.specialPrint == True:
            Funcs.PrintProgressBar(i * j, ij)
        while (j < len(tour)):
            if (time.process_time() - miscGlobal.start
                ) > miscGlobal.maxTime:  #A little bit spaghetti
                if miscGlobal.specialPrint == True:
                    print()
                return oldTour
            newTour = oldTour.copy()
            TwoOptSwap(i, j, oldTour, newTour)
            # print('Elements: ' + str(len(newTour)))
            newDist = Location.FindTourLength(newTour)
            # print('CurDist: ' + str(newDist))
            if (newDist < shortestDist):
                oldTour = newTour
                shortestDist = newDist
                yield oldTour
                # print("\tNew shorter dist: " + str(shortestDist))
            j += 1
        i += 1
    if miscGlobal.specialPrint == True:
        Funcs.PrintProgressBar(100, 100)
        print()
    return oldTour
示例#2
0
def SimulatedAnneal(tour : List[Location.Location], temp : float = 1000000.0, coolRate : float = 0.0003, targetTmp : float = 0.001, maxIts : int = 10000000):
	bestTour = tour
	bestDist = Location.FindTourLength(tour)

	currentTour = bestTour
	currentDist = bestDist

	#Initialise these once
	tourIndex1 = 0
	tourIndex2 = 0

	totalIts = 0

	while temp > targetTmp and totalIts < maxIts:
		if (100 / maxIts * totalIts) % 1 == 0 and miscGlobal.specialPrint == True: #Only write to console when needed
			Funcs.PrintProgressBar(totalIts, maxIts)
			
		if (time.process_time() - miscGlobal.start) > miscGlobal.maxTime: #A little bit spaghetti 
			if miscGlobal.specialPrint == True:
				print()
			return bestTour
		totalIts += 1
		newTour = currentTour.copy()

		while tourIndex1 == tourIndex2: #Make sure that these aren't the same
			tourIndex1 = random.randint(0, len(newTour) - 1)
			tourIndex2 = random.randint(0, len(newTour) - 1)

		#Swap the locations
		Location.Swap(newTour, tourIndex1, tourIndex2)
		
		newDist = Location.FindTourLength(newTour)

		if AcceptProbs(currentDist, newDist, temp) : #Should we accept this new tour
			currentTour = newTour
			currentDist = newDist
			# print('New tour dist: ' + str(currentDist))

		if newDist < bestDist:
			bestTour = newTour
			bestDist = newDist
			yield newTour

		tourIndex1 = tourIndex2 #Makes them both equal so they will be recalculated
		
		temp *= 1 - coolRate
		# print(temp)
	
	if miscGlobal.specialPrint == True:
		Funcs.PrintProgressBar(100, 100)
		print()
	return bestTour
示例#3
0
def SolveProblem(problemText: str, problemName: str, maxTime: float):
    miscGlobal.maxTime = float(maxTime)

    path = []

    # print(Parse(problemText))
    path = Parse(problemText)
    path = NearestNeighbour(path)
    path = TwoOpt(path)
    path = SimulatedAnnealing(path)

    if miscGlobal.specialPrint == True:
        print('\nComputation time: ' +
              str(time.process_time() - miscGlobal.start))
        print('Total path length: ' + str(Location.FindTourLength(path)))
    else:
        Funcs.PrintData(problemName, Location.FindTourLength(path), path)

    return path
示例#4
0
def TwoOpt(path: List[Location.Location]):
    #2Opt
    if miscGlobal.specialPrint == True:
        print('Opt2 Results:')
    pathLenDiff = 10
    pathLenDiffThreshold = 0.001
    lastLength = Location.FindTourLength(path)
    #If the path_delta < 1, it's not worth calculating anymore
    while pathLenDiff >= pathLenDiffThreshold and (
            time.process_time() - miscGlobal.start) < miscGlobal.maxTime:
        for newPath in Opt2.Opt2(path):
            yield newPath
            path = newPath
        newLength = Location.FindTourLength(path)
        pathLenDiff = lastLength - newLength  #Calculate this once
        if miscGlobal.specialPrint == True:
            print('Made path shorter by: ' + str(lastLength - newLength))
        lastLength = newLength

    if miscGlobal.specialPrint == True:
        Funcs.PrintTour(path)
    return path
示例#5
0
    if not DataBaseInterface.DoesProblemExist(problemName):
        print(DataBaseInterface.AddProblem(sys.argv[3], problemName))
    else:
        print("PROBLEM ALREADY EXISTS")
elif len(sys.argv) >= 4 and sys.argv[
        2] == 'SOLVE':  #> python TSP_db.py problemName SOLVE maxSolveTime
    if DataBaseInterface.DoesProblemExist(problemName):
        solution = tsp.SolveProblem(
         DataBaseInterface.GetProblem(problemName), \
         problemName,
         sys.argv[3]
         )
        DataBaseInterface.AddSolution(
         problemName, \
         Funcs.TourToIDText(solution), \
         Location.FindTourLength(solution), \
         "Test algorithm" \
        )
    else:
        print(f"Problem '{problemName}' does not exist")
    # print(DataBaseInterface.RetrieveProblemInfo(sys.argv[1]))
elif len(sys.argv) >= 3 and sys.argv[
        2] == 'FETCH':  #> python TSP_db.py problemName FETCH
    if DataBaseInterface.DoesSolutionExist(problemName):
        print(DataBaseInterface.GetSolution(problemName))
    else:
        print(f"Solution for problem '{problemName}' does not yet exist")
elif len(sys.argv) >= 3 and sys.argv[2] == 'PROBLEMEXISTS':
    print(
        'TRUE' if DataBaseInterface.DoesProblemExist(problemName) else 'FALSE')
elif len(sys.argv) >= 3 and sys.argv[2] == 'SOLEXISTS':
示例#6
0
def SaveToSolution(any):
    DataBaseInterface.AddSolution(miscGlobal.name, Funcs.TourToIDText(miscGlobal.tour), \
    Location.FindTourLength(miscGlobal.tour), miscGlobal.algorithmChoice.name)
示例#7
0
def TourToText(tour : List[Location.Location]):
	text = 'Length: ' + str(Location.FindTourLength(tour)) + '\n'
	for n in tour :
		text += f"{n._id}\t{n._xpos}\t{n._ypos}\n"
	text += f"-1\t{tour[0]._xpos}\t{tour[0]._ypos}\n" #Add first 
	return text