Exemple #1
0
    def optimizeGap(self, maxiteration, OPT):
        startTime = time.time()
        lastBest = -1
        lastImp = 0
        for ite in range(0, maxiteration):
            for k in range(0, self.parameter_K):
                tmpSol = Solution(self.graph)
                start = SOURCE
                while (len(tmpSol.not_visited) != 0):
                    nextNode = self.get_next_city(tmpSol)
                    tmpSol.add_edge(start, nextNode)
                    start = nextNode
                self.local_update(tmpSol)
                if tmpSol.cost < self.best.cost:
                    self.best = tmpSol
            self.heuristic2opt(self.best)
            self.global_update(self.best)

            if (ite + 1) == 1 or (ite + 1) % 100 == 0:
                print("iteration: " + str(ite + 1))
                gapBest = (self.best.cost - OPT) / OPT
                print("gapBest: " + str(gapBest))
                print("without Imp: " + str(ite - lastImp))
                curTime = time.time()
                print("CPU Time: " + str(curTime - startTime))

            if self.best.cost != lastBest:
                lastBest = self.best.cost
                lastImp = ite
Exemple #2
0
def main():
    g = Graph("N10.data")
    Kruskal.kruskal = Kruskal.Kruskal(g)
    heap = Q.PriorityQueue()
    sol = Solution(g)
    root = Node(SOURCE, sol)
    heap.put(root)

    while heap.qsize() > 0:
        node = heap.get()
        print("curCost: %d" % node.solution.cost)

        if len(node.solution.not_visited) == 0:
            if SOURCE in node.solution.visited:
                node.solution.printf()
                return

            else:
                child_sol = Solution(node.solution)
                child_sol.add_edge(node.v, SOURCE)
                child_node = Node(SOURCE, child_sol)
                heap.put(child_node)

        else:
            node.explore_node(heap)
Exemple #3
0
 def explore_node(self, heap):
     for nVisited in self.solution.not_visited:
         if nVisited == 0 and len(self.solution.not_visited) > 1:
             continue
         solution = Solution(self.solution)
         solution.add_edge(self.v, nVisited)
         node = Node(nVisited, solution)
         heap.put(node)
Exemple #4
0
 def explore_node(self, heap):
     for v in self.solution.not_visited:
         child_sol = Solution(self.solution)
         child_sol.add_edge(self.v, v)
         #child_node = Node(v, child_sol)
         child_node = Node(v, child_sol,
                           Kruskal.kruskal.getMSTCost(child_sol, SOURCE))
         heap.put(child_node)
Exemple #5
0
 def explore_node(self, heap):
     for not_visited in self.solution.not_visited:
         if not_visited == SOURCE and len(self.solution.not_visited) > 1:
             continue
         else:
             new_solution = Solution(self.solution)
             new_solution.add_edge(self.v, not_visited)
             new_node = Node(not_visited, new_solution, heuristic_cost=0)
             heap.put((new_node.solution.cost, new_node))
Exemple #6
0
 def explore_node(self, heap):
     global NUMBER_NODE_EXPLORED
     NUMBER_NODE_EXPLORED = NUMBER_NODE_EXPLORED + 1
     for node in self.solution.not_visited:
         if len(self.solution.not_visited) == 1 or node != SOURCE:
             Sol = Solution(self.solution)
             v = self.v
             Sol.add_edge(v, node)
             nodeToAdd = Node(node, Sol)
             heap.put(nodeToAdd)
Exemple #7
0
def test_heuristic2opt():
    print("testing heuristic 2opt...")
    aco = ACO(0, 0, 0, 0, 0, 'test')
    s = Solution(aco.graph)
    s.add_edge(0, 2)
    s.add_edge(2, 3)
    s.add_edge(3, 1)
    s.add_edge(1, 0)
    aco.heuristic2opt(s)
    assert s.cost == 6
    print('ok')
def test_heuristic2opt():
    print("testing heuristic 2opt...")
    aco = ACO(0, 0, 0, 0, 0, 'test')
    s = Solution(aco.graph)
    s.add_edge(0, 2)
    s.add_edge(2, 3)
    s.add_edge(3, 1)
    s.add_edge(1, 0)
    s=aco.heuristic2opt(s) #<------------------Changement (s=)
#    print("Voila le resultat : ",s.cost)
    assert s.cost == 6
    print('ok')
 def explore_node(self, heap):
     for not_visited in self.solution.not_visited:
         if not_visited == SOURCE and len(self.solution.not_visited) > 1:
             continue
         else:
             new_solution = Solution(self.solution)
             new_solution.add_edge(self.v, not_visited)
             import Kruskal
             Kruskal.kruskal = Kruskal.Kruskal(new_solution.g)
             heuristic_cost = Kruskal.kruskal.getMSTCost(
                 new_solution, SOURCE)
             new_node = Node(not_visited, new_solution, heuristic_cost)
             heap.put((new_node.solution.cost + new_node.heuristic_cost,
                       new_node))
    def runACO(self, maxiteration):

        # Initialiser la meilleure solution globalement trouvee
        overall_best = Solution(self.graph)
        overall_best.cost = 9999999999999.0

        for iter in range(maxiteration):  # Pour chaque iteration

            # Initialiser la meilleure solution pour cette iteration
            iter_best = Solution(self.graph)
            iter_best.cost = 9999999999999.0

            # Pour chacune des K fourmis
            for k in range(self.parameter_K):
                sk = Solution(
                    self.graph
                )  # construction de la solution de chaque fourmis

                # Execution de la recherche locale
                for step in range(
                        self.graph.N
                ):  # Boucle chaque ville a visiter (il y en a N)
                    current_city = sk.visited[-1]
                    next_city = self.get_next_city(
                        sk)  # Trouver la prochaine ville
                    sk.add_edge(current_city, next_city)
                    # Mise a jour locale des pheromones
                    self.local_update(sk)

                # Mise a jour de la meilleure solution pour cette iteration (iter):
                if sk.cost < iter_best.cost:
                    iter_best = sk

            # Ameliorer la meilleure solution a l'aide de 2-Opt
            self.heuristic2opt(iter_best)

            # mise a jour globale de la pheromone
            self.global_update(iter_best)

            # Mise a jour de la meilleure solution trouvee a date (sur plusieurs iterations)
            if iter_best.cost < overall_best.cost:
                overall_best = iter_best

        #print('*** Meilleure Solution trouvee au cout de : ', overall_best.cost)
        #print(overall_best.visited)

        self.best = overall_best
        return overall_best
Exemple #11
0
 def runACO(self, maxiteration):
     startTime = time.time()
     for ite in range(0, maxiteration):
         for k in range(0, self.parameter_K):
             tmpSol = Solution(self.graph)
             start = SOURCE
             while (len(tmpSol.not_visited) != 0):
                 nextNode = self.get_next_city(tmpSol)
                 tmpSol.add_edge(start, nextNode)
                 start = nextNode
             self.local_update(tmpSol)
             if tmpSol.cost < self.best.cost:
                 self.best = tmpSol
         self.heuristic2opt(self.best)
         self.global_update(self.best)
     endTime = time.time()
     return (endTime - startTime)
def test_local_update():
    print("testing local update...")
    phi = 0.5
    aco = ACO(0, 0, 0, phi, 0, 'test')
    s = Solution(aco.graph)
    aco.pheromone[:, :] = 1
    c = copy.copy(aco.pheromone)
    s.add_edge(0, 2)
    s.add_edge(2, 3)
    s.add_edge(3, 1)
    s.add_edge(1, 0)
    aco.local_update(s)
    assert (c != aco.pheromone).sum() == 8
    assert abs(aco.pheromone[0, 1] - 0.833) < 1e-3
    assert abs(aco.pheromone[0, 2] - 0.833) < 1e-3
    assert abs(aco.pheromone[3, 1] - 0.833) < 1e-3
    assert abs(aco.pheromone[3, 2] - 0.833) < 1e-3
    print('ok')
def test_global_update():
    print('testing global update...')
    rho = 0.1
    aco = ACO(0, 0, rho, 0, 0, 'test')
    s = Solution(aco.graph)
    s.add_edge(0, 2)
    s.add_edge(2, 3)
    s.add_edge(3, 1)
    s.add_edge(1, 0)
    aco.pheromone[:, :] = 1
    aco.global_update(s)
    print(aco.pheromone)
    assert abs(aco.pheromone[0, 3] - 0.9) < 1e-3
    assert abs(aco.pheromone[1, 2] - 0.9) < 1e-3
    assert abs(aco.pheromone[0, 2] - 0.91) < 1e-3
    assert abs(aco.pheromone[2, 3] - 0.91) < 1e-3
    assert abs(aco.pheromone[3, 1] - 0.91) < 1e-3
    assert abs(aco.pheromone[1, 0] - 0.91) < 1e-3
    print('ok')
Exemple #14
0
    def explore_node(self, heap, *kruskal):
        if len(self.solution.not_visited)>1:
            for n in self.solution.not_visited:
                if n==SOURCE:
                    continue # il reste encore des sommets à visiter avant de retourner à la source

                s=Solution(self.solution)
                s.add_edge(self.v,n)
                node = Node(n,s)

                node.heuristic_cost = heuristic(kruskal,node)
                heap.put(node)

        else: # il ne reste plus que le noeud source : on l'ajoute avec une heuristique de 0: on a complété la boucle
            n=self.solution.not_visited[0]
            s=Solution(self.solution)
            s.add_edge(self.v,n)
            node = Node(n, s)
            node.heuristic_cost = 0
            heap.put(node)
Exemple #15
0
    def build_sol(self):

        s = Solution(self.graph)

        s.not_visited.remove(SOURCE)

        while (len(s.not_visited) > 0):
            if (len(s.visited) == 0):
                actualCity = SOURCE
            else:
                actualCity = s.visited[len(s.visited) - 1]

            # Loop act as a do-while
            #while True:
            cityToVisit = self.get_next_city(s)
            #    if cityToVisit != origin or len(s.not_visited) == 1 :
            #        break

            s.add_edge(int(actualCity), int(cityToVisit))

        s.not_visited.append(SOURCE)
        s.add_edge(int(s.visited[len(s.visited) - 1]), SOURCE)

        return s
def main():
    # Initialisation and input data
    g = Graph('N17.data')  #Graph
    opt_val = 0
    max_iter = 1000  #Max iterations allowed
    iter = 0  #Iteration indicator
    tabu = []
    town = 0
    no_update = 0
    heap = Q.PriorityQueue()
    history = []

    # Initial solution:
    current_sol = Solution(g)
    for i in range(g.N)[0:-1]:
        current_sol.add_edge(i, i + 1)
    current_sol.cost += g.get_edge(g.N - 1, 0).cost
    best_solution = Solution(current_sol)
    print("Solution initale: ", current_sol.visited, "  Cout = ",
          current_sol.cost, '   f_Cout = ', eval_sol(current_sol))

    # -----Local search loop--------
    while current_sol.cost > opt_val and iter <= max_iter:

        #Find position of current switching town
        print(' ')
        print("Solution Courante: ", current_sol.visited, "  Cout = ",
              current_sol.cost)
        position = current_sol.visited.index(town)
        print('Ville a changer: ', town, '      A la position = ', position)

        # Explore and evaluate current solution neighbors
        del heap
        heap = Q.PriorityQueue()
        print('Q vide? : ', heap.empty())
        for i in range(len(current_sol.visited)):
            v = current_sol.visited[i]
            if v != town and v not in tabu:  # explore all possible neighbors
                neighbor = Solution(current_sol)
                neighbor.visited = []
                for j in range(len(current_sol.visited)):
                    if j != i and j != position:
                        neighbor.visited.append(current_sol.visited[j])
                    else:
                        if j == position:
                            neighbor.visited.append(v)
                        else:
                            neighbor.visited.append(town)

                # Evaluate neighbor
                neighbor.cost = eval_sol(neighbor)
                heap.put((neighbor.cost,
                          neighbor))  # Add neighbor to the priority queue
                print(' Neighnor ', i, ' : ', neighbor.visited, '    cost = ',
                      neighbor.cost)

        # Get best neighbor
        best_neighbor = heap.get()[1]
        print(' Meilleur Voisin: ', best_neighbor.visited, '    cost = ',
              best_neighbor.cost)

        #Update new current solution
        if best_neighbor.cost < current_sol.cost:
            current_sol = Solution(best_neighbor)
            no_update = 0
            if best_neighbor.cost < best_solution.cost:
                best_solution = Solution(best_neighbor)
                history.append([time.clock(), iter])
                print('NEW BEST SOLUTION !! ', best_solution.visited,
                      'COST = ', best_solution.cost)
        else:
            if no_update < g.N:
                no_update += 1
                print(' No update = ', no_update)
            else:
                current_sol = Solution(best_neighbor)
                no_update = 0
                tabu = [town]
                print('Degradation: ', best_solution.cost, 'TABOU = ', tabu)

        # Update iteration counter
        town = (town + 1) % g.N  # new switching town
        iter += 1

    # PRINT
    print(' ')
    print('---- TERMINÉ ----')
    print('Meilleure Solution Trouvee: ', best_solution.visited, ' COUT = ',
          best_solution.cost)
    print('CPU Time (sec): ', time.clock(), '    Nb Iterations = ', iter)
    print('Meilleur trouvé à CPU Time (sec): ', history[-1][0],
          '    Et à nb Iterations = ', history[-1][1])