Esempio n. 1
0
def searchIteration(points,neighborhoods, maxNoImprove, maxNoImproveLocalSearch, timeLimit):
    t_end = time.time() + timeLimit
    best_list = []
    # Permutação aleatória é usada para a construção da solução inicial.
    best ={}
    best["permutation"] = constructInitialSolution(points)
    best["cost"] = tourCost(best["permutation"])
    noImproveCount =0
    while noImproveCount<=maxNoImprove and time.time() < t_end:
        candidate ={}
        candidate["permutation"] = best["permutation"]
        # Para cada vizinhança em vizinhanças.
        for neighborhood in neighborhoods:
            # Calcular vizinhança: Envolve executar duas opções estocásticas por quantidade de vizinhanças.
            for index in range(0,neighborhood):
                # Obter solução canditada de vizinhança.
                candidate["permutation"] = stochasticTwoOpt(candidate["permutation"])

            # Calcular o custo da vizinhança final.
            candidate["cost"] = tourCost(candidate["permutation"])
            # Refinar a solução candidata final usando a busca local e a vizinhança.
            candidate = localSearch(candidate,maxNoImproveLocalSearch, neighborhood, t_end)
            # Se o custo da candidata é menor que o custo da melhor solução atual, então substitua a melhor pela candidata.
            if candidate["cost"] < best["cost"]:
                best, noImproveCount = candidate, 0 # Quando um ótimo local é encontrado a busca é reiniciada. 
                best_list.append(best["cost"]) 
                # Interrupção da iteração das vizinhanças.
                break
            else: # Incremento do contador para informar que um ótimo local não foi encontrado. 
                best_list.append(best["cost"])
                noImproveCount +=1

    return best_list
Esempio n. 2
0
def searchIteration(points, maxIterations, maxTabu, maxCandidates, timeLimit):
    t_end = time.time() + timeLimit
    best_list = []
    # constrói a solução inical
    best = {}
    best["permutation"] = constructInitialSolution(points)
    best["cost"] = tourCost(best["permutation"])
    tabuList = []
    while maxIterations > 0 and time.time() < t_end:
        # Gera candicdatos usando o algoritmo 2-opt de busca local
        # estocásticamente, perto do melhor candidato dessa iteração.
        # Usa a lista tabu para não visitar vértices mais de uma vez
        candidates = []
        for index in range(0, maxCandidates):
            candidates.append(generateCandidates(best, tabuList, points,
                                                 t_end))
        # Procura o melhor candidasto
        # ordena a lista de cnadicados pelo custo
        bestCandidate, bestCandidateEdges = locateBestCandidate(candidates)
        # compara com o melhor candidato e o atualiza se necessário
        if bestCandidate["cost"] < best["cost"]:
            # define o candidato atual como melhor
            best = bestCandidate
            # atuliza a lista tabu
            for edge in bestCandidateEdges:
                if len(tabuList) < maxTabu:
                    tabuList.append(edge)
        maxIterations -= 1
        best_list.append(best["cost"])

    return best_list
Esempio n. 3
0
def search(points, maxIterations, maxTabu, maxCandidates):
    t_end = time.time() + 60
    # construct a random tour
    best = {}
    best["permutation"] = constructInitialSolution(points)
    best["cost"] = tourCost(best["permutation"])
    tabuList = []
    while maxIterations > 0 and time.time() < t_end:
        # Generate candidates using stocahstic 2-opt near current best candidate
        # Use Tabu list to not revisit previous rewired edges
        candidates = []
        for index in range(0, maxCandidates):
            candidates.append(generateCandidates(best, tabuList, points))
        # Locate the best candidate
        # sort the list of candidates by cost
        # since it is an  involved sort, we write a function for getting the least cost candidate
        bestCandidate, bestCandidateEdges = locateBestCandidate(candidates)
        # compare with current best and update if necessary
        if bestCandidate["cost"] < best["cost"]:
            # set current to the best, so thatwe can continue iteration
            best = bestCandidate
            # update tabu list
            for edge in bestCandidateEdges:
                if len(tabuList) < maxTabu:
                    tabuList.append(edge)

        maxIterations -= 1

    return best
Esempio n. 4
0
def search(points, neighborhoods, maxNoImprove, maxNoImproveLocalSearch):
    t_end = time.time() + 60
    # First construct the initial solution. We use a random permutation as the initial solution
    best = {}
    best["permutation"] = constructInitialSolution(points)
    best["cost"] = tourCost(best["permutation"])
    noImproveCount = 0
    while noImproveCount <= maxNoImprove and time.time() < t_end:
        candidate = {}
        candidate["permutation"] = best["permutation"]
        # for each neighborhood in neighborhoods
        for neighborhood in neighborhoods:
            #Calculate Neighborhood : Involves running stochastic two opt for neighbor times
            for index in range(0, neighborhood):
                # Get candidate solution from neighborhood
                candidate["permutation"] = stochasticTwoOpt(
                    candidate["permutation"])

            # Calculate the cost of the final neighborhood
            candidate["cost"] = tourCost(candidate["permutation"])
            # Refine candidate solution using local search and neighborhood
            candidate = localSearch(candidate, maxNoImproveLocalSearch,
                                    neighborhood)
            #if the cost of the candidate is lesser than cost of current best then replace
            #best with current candidate
            if candidate["cost"] < best["cost"]:
                best, noImproveCount = candidate, 0  # We also restart the search when we find the local optima
                # break: this breaks out of the neighborhoods iteration
                break
            else:  # increment the count as we did not find a local optima
                noImproveCount += 1

    return best