Ejemplo n.º 1
0
def solve(algorithm, path):
    startTime = time.time()
    bestState, bestCost, initPoint = None, None, None
    initPoint, capacity, graph, demand, optimalValue, ncars, problemName = getData(
        path)
    initState = createShuffledState(graph.keys())
    if algorithm == 0:
        #SA
        alg = simulatedAnnealing(initState, graph, demand, capacity, initPoint,
                                 optimalValue, ncars, 2000, 2000000, 30)
        bestState, bestCost, initPoint, iteration = alg.simulate()

    elif algorithm == 1:
        #tabu
        alg = tabuSearch(initState, graph, demand, capacity, initPoint,
                         optimalValue, ncars, 2000000, 100, 300, 30)
        bestState, bestCost, initPoint, iteration = alg.run()
    elif algorithm == 2:
        alg = ACO(graph, demand, capacity, initPoint, optimalValue, ncars,
                  100000, 70, 23)
        best, runtime, iteration = alg.runAnts()
        bestState, bestCost = best[0], best[1]
    elif algorithm == 3:
        bestState, bestCost, iteration = startGenetic(path)

    print("Total elapsed time: ", str(time.time() - startTime))
    prinSolution(bestState, bestCost, graph, initPoint)
def runSimulatedAnnealingAlgorithm(cities, coolDownRate):
    print "Simulated Annealing..."
    resetCitiesToUnvisited(cities)
    title = "Simulated Annealing Algorithm"
    startTime = datetime.now()
    distance, orderedListOfCities = simulatedAnnealing(cities, coolDownRate)
    endTime = datetime.now()
    printResultsAndWriteOutput(distance, orderedListOfCities, startTime,
                               endTime, title)
Ejemplo n.º 3
0
def benchSA(verbose, nsize):
    
    '''
        Benchmarking variables
        Nmax = 100 Queens
        nincr = 5 Queens increment per round
    '''
    nmax = 45
    nqincr = 5
    iterations = 30
    alpha = 0.999 # very low decrease in temperature
    maxIter = 100000
    initTemp = 100000
    
    '''
        Simulation Result Structure
    '''
    simResStruct = namedtuple('simResStruct', "Queens ArchivedSolution averageIterations executionTime")    
    
    print('Benchmarking Simulated Annealing N-Queens')
    
    results = []
    sa = simulatedAnnealing(False)
    
    '''
        Run the benchmarking for loop
    '''
    #(x,y) = sa.simulatedAnnealing(steps, alpha, maxIter, initTemp)
    #s = sa.simulatedAnnealing(10, alpha, 10, initTemp)
    
    for steps in range(nqincr, nmax, nqincr):

        totalT = 0
        averageIterations = 0
        foundSolution = 0
        for i in range(iterations):
            s = sa.simulatedAnnealing(steps, alpha, maxIter, initTemp)
            
            averageIterations += s[0]
            foundSolution += s[1]
            totalT += s[2]
            
            print(s)
        # add it
        foundSolution = foundSolution / iterations
        averageIterations = averageIterations / iterations
        totalT = totalT / iterations
        results.append(simResStruct(steps, foundSolution, averageIterations, totalT))
        print(results)
Ejemplo n.º 4
0
def main():
    fileName = input('Enter file name : ')
    # Used variables
    pawnAmountBW = {'WHITE': 0, 'BLACK': 0}  # number of pawns for each side
    dataSplitted = []
    readFile(fileName, dataSplitted)  # parse user's input into array

    # Algorithms option
    print("Choose Algorithm By Input The Number :")
    print("1. Hill Climbing")
    print("2. Simulated Annealing")
    print("3. Genetic Algorithm")
    chosenAlgo = int(input("Choose : "))
    while (chosenAlgo > 3 or chosenAlgo < 1):
        print("Choose The Correct Number Please...")
        chosenAlgo = int(input("Choose : "))

    # Execute the chosen algorithm
    if (chosenAlgo == 1):
        state = parseState(dataSplitted,
                           pawnAmountBW)  # generate an initial state
        result = hillClimbing(state, pawnAmountBW)
    elif (chosenAlgo == 2):
        temperature = int(input('Temperature: '))
        decreaseRate = int(input('Decrease Rate: '))
        iteration = int(input('Maximum Iteration: '))
        state = parseState(dataSplitted,
                           pawnAmountBW)  # generate an initial state
        result = simulatedAnnealing(state, pawnAmountBW, temperature,
                                    decreaseRate, iteration)
    elif (chosenAlgo == 3):
        populationAmount = int(input('Number Of Population: '))
        limit = int(input('Maximum generation: '))
        listOfStates = createListOfStates(dataSplitted, pawnAmountBW,
                                          populationAmount)
        result = geneticAlgorithm(listOfStates, pawnAmountBW, populationAmount,
                                  limit)

    # Print the result
    attackNum = countAtack(
        result)  # Get the number of attack from the result state
    printBoard(result)
    print(attackNum['friend'], end='')
    print(' ', end='')
    print(attackNum['enemy'])
Ejemplo n.º 5
0
def inverseSchedule(t):
    if t > 100000:
        return 0
    return 1 / (0.001 * t + 1)

def reverseInverseSchedule(t):
    if t > 100000:
        return 0
    return 1 - inverseSchedule(100000 - t)

def stepSchedule(t):
    if t > 100000:
        return 0
    return 1 - (t - t % 10000) / 100000

def sqrtSchedule(t):
    return sqrt(linearSchedule(t))

def reverseSqrtSchedule(t):
    if t > 100000:
        return 0
    return 1 - sqrtSchedule(100000 - t)

schedules = [linearSchedule, exponentialSchedule, inverseSchedule, reverseInverseSchedule, stepSchedule, sqrtSchedule, reverseSqrtSchedule]

if __name__ == '__main__':
    problem = sa.Problem(11, taylorApproximation_c, taylorApproximation_scale, taylorApproximation, sqrtSchedule, 8)

    res = sa.simulatedAnnealing(problem)
    print(res)
Ejemplo n.º 6
0
        visited_list = []
        w = W
        for i in range(n, 0, -1):
            if res <= 0:
                break
            if res == K[i - 1][w]:
                continue
            else:
                visited_list.append(attractions[i - 1])
                print(attractions[i - 1].name)
                res = res - val[i - 1]
                w = w - wt[i - 1]
        return visited_list

    def k_means(self, data, k=3):
        ''' Runs k means algorithm on data, and returns the clustered data '''
        kmeans = KMeans(k)
        kmeans.fit(data)
        return kmeans.classification_names


center = "40.7304, -73.9921"
dataFilter = DataFilter()
attractions = dataFilter.query_potential_locations("40.7304", "-73.9921")
filtered_attractions = dataFilter.filter_by_popularity(center, attractions)
clustered_attractions = dataFilter.cluster_attractions(filtered_attractions, 3)
print(type(clustered_attractions[0][0]))
print(clustered_attractions)

print(simulatedAnnealing.simulatedAnnealing(clustered_attractions, center))
Ejemplo n.º 7
0
tries = 100;
randomSearch.randomSearch(myMatrix, tries);


########################################################################################################################
#                                                                                                                      #
#                                                 SIMULATED ANNEALING                                                  #
#                                                                                                                      #
########################################################################################################################
#Change values of these variables here below as you want

myMatrix =  readFromFile("filesFlowShopPermutation/Doc5.txt")
alpha = 0.9
L = 100
finalT = 0.001
bestAnnealing = simulatedAnnealing.simulatedAnnealing(alpha, L, finalT, myMatrix)
localSearch.firstImprovement(myMatrix, bestAnnealing)


########################################################################################################################
#                                                                                                                      #
#                                                 GENETICAL ALGORITHM                                                  #
#                                                                                                                      #
########################################################################################################################
#Change values of these variables here below as you want


myMatrix =  readFromFile("filesFlowShopPermutation/Doc5.txt")  #Problem to solve - Important: READ NOTE
n = 50 #Size of my population
nGen = 20 #Number of generations of my algorithm
k = 30 #Size of the tournament
Ejemplo n.º 8
0
def SASolver(nsize, iterations, verbose):
    
    sa = simulatedAnnealing(True)
    sa.simulatedAnnealing(nsize, 0.999, iterations, iterations*10)
Ejemplo n.º 9
0
    if default == 't':
        tester.populationBased()
    #
    # else:
    #     print("Error, unknown input")


''' SIMULATED ANNEALING '''
if algorithm == '3':

    default = input("\n If you want to run the algorithm once with the default parameters, type 'd'.\n\n \
                        For custom parameters, type 'c'. \n\n \
                        For running the algorithm (with default parameters) on a test-set with 100 random genomes of length 25, type 't'  \n\n")

    if default == 'd':
        print(simulatedAnnealing(data.mel, data.mir, 1000, score.scoreNeighbours))

    elif default == 'c':

        print("\nDefine the score-function you would like to use.\n\nFor scoreNeighbours, type: 1\nFor scoreNeighboursModifier, type: 2\n")
        scoreF = input("Type in which score-funtion that you would like the algorithm to use: ")

        if scoreF == '1':
            print("\nDefine the interval with which the algorithm allows lesser mutations to pass.\n\nFor an interval of 1000, type: s\nFor an interval of 10.000, type: m\nFor an interval of 100.000, type l\n")
            failV = input("Type in which interval-size you would like the algorithm to use: ")

            if failV == 's':
                print(simulatedAnnealing(data.mel, data.mir, 1000, score.scoreNeighbours))
            if failV == 'm':
                print(simulatedAnnealing(data.mel, data.mir, 10000, score.scoreNeighbours))
            if failV == 'l':
Ejemplo n.º 10
0
if (len(sys.argv) != 3):
    printUsage()
else:
    # Test InputFunction
    pathToInputFile = sys.argv[1]
    coolDownRate = 0.99995
    if sys.argv[2] == 'fast':
        coolDownRate = 0.9995
    elif sys.argv[2] == 'normal':
        coolDownRate = 0.99995
    elif sys.argv[2] == 'slow':
        coolDownRate = 0.999995
    else:
        printUsage()
        exit()

    cities = readInput(pathToInputFile)
    # Print results
    print "------------------------------------------"
    startTime = datetime.now()
    distance, orderedListOfCities = simulatedAnnealing(cities, coolDownRate)
    endTime = datetime.now()

    print "Total Running Time: ", str(endTime - startTime)
    print "Distance: ", distance
    print "------------------------------------------\n"

    extension = ".tour-SA-NN-" + sys.argv[2]
    writeOutput(pathToInputFile, distance, orderedListOfCities, extension)
Ejemplo n.º 11
0
def saJob(constraintFunc, scale, evalFunc, schedule, trial):
    problem = simulatedAnnealing.Problem(11, constraintFunc, scale, evalFunc, schedule, trial)
    simulatedAnnealing.simulatedAnnealing(problem)
Ejemplo n.º 12
0
from nQueens import queen
from simulatedAnnealing import simulatedAnnealing
import math

def func(i):
    return 1/(1+i)


# Solução para um valor de N de livre escolha, altere abaixo:
N = 25

problem = queen(N)
schedule = func

solution = simulatedAnnealing(problem, schedule)

print(solution)

for i in range(problem.N):
    for j in range(problem.N):
        if j != solution[i]:
            print(". ", end="")
        else:
            print("Q ", end="")
    print("")
Ejemplo n.º 13
0
def execute(dcel_i, polygons_i, l, r, maxExecs, minR, maxR, relationship,
            method, coloursDistribution, static, path, it):

    dcel = dcel_i
    polygons = polygons_i

    #n
    n = len(dcel.faces)

    #initial symmetric difference
    sd = symmetricDifference.symDif(dcel.faces, polygons,
                                    dcel.box)  #initial energy (global)

    #T inicial
    tIni = math.fabs(1 / math.log10(sd))

    #T final
    tFin = tIni / (100 * math.log10(n))

    #################################   SELECTOR   ##################################
    #Execution switch
    if (relationship == "classic"):
        bestPSet, bestSD, bestsDs, sDs, temps, its, acceptance = simulatedAnnealing.simulatedAnnealing(
            dcel, r, tIni, tFin, l, n, minR, maxR)
    elif (relationship == "peers"):
        if (method == "and"):
            bestPSet, bestSD, bestsDs, sDs, temps, its, acceptance = simulatedAnnealingPeers.simulatedAnnealingPeers_AndMethod(
                dcel, r, tIni, tFin, l, n, minR, maxR)
        elif (method == "or"):
            bestPSet, bestSD, bestsDs, sDs, temps, its, acceptance = simulatedAnnealingPeers.simulatedAnnealingPeers_OrMethod(
                dcel, r, tIni, tFin, l, n, minR, maxR)
        elif (method == "numbers"):
            bestPSet, bestSD, bestsDs, sDs, temps, its, acceptance = simulatedAnnealingPeers.simulatedAnnealingPeers_NumbersMethod(
                dcel, r, tIni, tFin, l, n, minR, maxR)
        else:
            print("error_peers")
    elif (relationship == "groups"):
        if (method == "and"):
            bestPSet, bestSD, bestsDs, sDs, temps, its, acceptance = simulatedAnnealingGroups.simulatedAnnealingGroups_AndMethod(
                dcel, r, tIni, tFin, l, n, minR, maxR)
        elif (method == "or"):
            bestPSet, bestSD, bestsDs, sDs, temps, its, acceptance = simulatedAnnealingGroups.simulatedAnnealingGroups_OrMethod(
                dcel, r, tIni, tFin, l, n, minR, maxR)
        elif (method == "numbers"):
            bestPSet, bestSD, bestsDs, sDs, temps, its, acceptance = simulatedAnnealingGroups.simulatedAnnealingGroups_NumbersMethod(
                dcel, r, tIni, tFin, l, n, minR, maxR)
        else:
            print("error_groups")
    elif (relationship == "colours"):
        if (method == "and"):
            bestPSet, bestSD, bestsDs, sDs, temps, its, acceptance = simulatedAnnealingColours.simulatedAnnealingColours_AndMethod(
                dcel, r, tIni, tFin, l, n, minR, maxR, coloursDistribution,
                static)
        elif (method == "or"):
            bestPSet, bestSD, bestsDs, sDs, temps, its, acceptance = simulatedAnnealingColours.simulatedAnnealingColours_OrMethod(
                dcel, r, tIni, tFin, l, n, minR, maxR, coloursDistribution,
                static)
        elif (method == "numbers"):
            bestPSet, bestSD, bestsDs, sDs, temps, its, acceptance = simulatedAnnealingColours.simulatedAnnealingColours_NumbersMethod(
                dcel, r, tIni, tFin, l, n, minR, maxR, coloursDistribution,
                static)
        else:
            print("error_colours")
    else:
        print("error")

    #managing name
    change = ""
    if (relationship != ""):
        relationship = ' - ' + relationship
    if (method != ""):
        method = ' - ' + method
    if (coloursDistribution != ""):
        coloursDistribution = ' - ' + coloursDistribution
        if (static):
            change = "- static"
        else:
            change = "- dynamic"

    #Final plot
    plottingModule.plt.figure(6 + it)
    bestPVor = Voronoi(bestPSet)
    polygonsPBest = finiteVoronoi.vorFiniteDelPolygonsList(bestPVor, dcel.box)
    plottingModule.plotDcel(dcel, 'k')
    plottingModule.plt.suptitle('l: ' + repr(l) + ' - r: ' + repr(r))
    plottingModule.plt.title('SA' + relationship + method +
                             coloursDistribution + change + " - best SD: " +
                             repr(bestSD))
    plottingModule.plotPolys(polygonsPBest, 'g')
    plottingModule.plotPoints(bestPSet, '-ob')

    #plottingModule.plt.savefig(path + repr(bestSD) + '.jpg')

    return bestPSet, bestSD, bestsDs, sDs, temps, its, acceptance