示例#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)
示例#2
0
def run_aco(data="./data/data_20.txt"):
    points = []
    locations = []
    with open(data) as f:
        for line in f.readlines():
            character = line.split(" ")
            locations.append(
                dict(index=int(character[0]),
                     x=float(character[1]),
                     y=float(character[2])))
            points.append((float(character[1]), float(character[2])))

    cost_matrix = []
    rank = len(points)
    for i in range(rank):
        row = []
        for j in range(rank):
            row.append(distance(locations[i], locations[j]))
        cost_matrix.append(row)
    aco = ACO(20, 200)
    graph = Graph(points, cost_matrix, rank)
    path, length, all_path, all_length = aco.solve(graph)
    print('length: {}, path: {}'.format(length, path))
    print(all_length)
    plot_all(points, all_path, all_length, algorithm="Ant Colony Algorithm")
    plot_animation(points, path, length)
示例#3
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')
示例#5
0
文件: Main.py 项目: VNAndrei/ACO
def main():
    graph = readFile("data/hardE.txt")
    parameters = {}
    parameters["numberOfCities"] = len(graph)
    parameters["numberOfGenerations"] = 200
    parameters["numberOfAnts"] = int(len(graph) * 0.8)
    parameters["graph"] = graph
    parameters["degradation"] = 0.03
    parameters["pheromoneQuantity"] = 1
    parameters["beta"] = 2.5
    parameters["alpha"] = 2

    aco = ACO(parameters)
    aco.run()
def test_next_city():
    print('testing get next city...')
    aco = ACO(0.5, 2, 0, 0, 0, 'test')
    s = Solution(aco.graph)
    c1 = 0
    c3 = 0
    for i in range(1000):
        c = aco.get_next_city(s)
        if c == 3:
            c3 += 1
        elif c == 1:
            c1 += 1
    assert (abs(c3 - 870) < 30)
    assert (abs(c1 - 90) < 30)
    print('ok')
示例#7
0
    def run(self):
        i = 0
        listOfFitnesses = []
        for i in range(30):
            #show progres
            print("Validation ", i, '/', 30)
            minimum = 0
            maximum = random.randint(21, 30)
            individualSize = (maximum) * 2

            problem = ACO(minimum, maximum - 1, individualSize)

            noEpoch = 30
            noAnts = 40
            alpha = random.random() + random.randint(0, 3)
            beta = random.random() + random.randint(0, 3)
            rho = random.random()
            q0 = random.random()
            pheromoneMatrix = [[1 for i in range(individualSize)]
                               for j in range(individualSize)]

            controller = Controller(problem, noEpoch, noAnts, alpha, beta, rho,
                                    q0, pheromoneMatrix)
            fitness = controller.run()[1]
            listOfFitnesses.append(fitness)
        return listOfFitnesses
示例#8
0
 def run(self):
     self.readProblem()
     #initialize ACO
     aco = ACO(self.algorithm, self.numAnts, self.numIter, self.problem,
               self.optimalSolutionLength, self.tolerance)
     #start timer
     start_time = time.time()
     #run solve
     solution, solutionCost = aco.solve()
     #format the solution returned so it starts with 1 index
     formatedSol = self.formatSolution(solution)
     #print results
     print("solution: ", formatedSol)
     print()
     print("solutionCost: ", solutionCost)
     print("Total Time: {} seconds.".format(time.time() - start_time))
示例#9
0
文件: Main.py 项目: caluianbianca/AI
def run():

        params = {"evaporation": 0.1, "distancePriority": 2, "pheromoneImportance": 0.1, "randomFactor": 0.3, "steps": 100, "antFactor": 0.9}
        repository = Repository("resources/eil51.txt")
        aco = ACO(params, repository.params)
        ui = UI(aco)

        ui.run()
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')
示例#12
0
def main():
    tsp = reader.read('data/dj38.tsp')
    cities = tsp['NODE_COORD_SECTION']
    rank = int(tsp['DIMENSION'])
    cost_matrix = []
    for i in range(rank):
        row = []
        for j in range(rank):
            row.append(distance(cities[i], cities[j]))
        cost_matrix.append(row)
    aco = ACO(ant_count=10,
              iterations=100,
              alpha=1.0,
              beta=10.0,
              rho=0.5,
              q=10)
    graph = Graph(cost_matrix, rank)
    route, route_length = aco.solve(graph)
    writer.write(rank, route, route_length, 'output.txt')
示例#13
0
 def runHeuristic(self, type, paramTuned):
     if not type:
         return None
     if type == "ACO":
         if not paramTuned:
             paramTuned = 0.1
         Q = paramTuned
         acoModel = aco.ACO(self.data,
                            maxIteration=20,
                            antNumber=50,
                            cc=1,
                            Q=Q,
                            e=0.95)
         score, featureSet, quality = acoModel.run()
         return score, featureSet, quality
示例#14
0
def main():
    finished = False
    while not finished:
        try:
            printMenu()
            choice = int(input(">>"))
            if choice == 0:
                finished = True
            elif choice == 1:
                minimum = 0
                maximum = int(
                    input("How many numbers do you wish to permute? "))
                individualSize = (maximum) * 2

                problem = ACO(minimum, maximum - 1, individualSize)

                noEpoch = int(input("Number of eras: "))
                noAnts = int(input("Number of ants: "))
                if (noAnts > individualSize):
                    raise ValueError(
                        "Number of ants must be at most 2*number of numbers you wish to permute."
                    )
                alpha = float(input("Trail importance(alpha): "))
                beta = float(input("Visibility importance(beta): "))
                rho = float(input("Pheromone degradation(0<=rho<=1): "))
                if rho < 0 or rho > 1:
                    raise ValueError("Rho must be >=0 and <=1")
                q0 = float(input("Random proportional rule(0<=q0<=1): "))
                if q0 < 0 or q0 > 1:
                    raise ValueError("q0 must be >=0 and <=1")
                pheromoneMatrix = [[1 for i in range(individualSize)]
                                   for j in range(individualSize)]

                controller = Controller(problem, noEpoch, noAnts, alpha, beta,
                                        rho, q0, pheromoneMatrix)
                solution = controller.run()[0]
                print("Solution:")
                for row in solution.formSolution(solution.getIndividual()):
                    print(row)
            elif choice == 2:
                runValidation()
            else:
                print("Invalid choice. Please try again.")
        except ValueError as ve:
            print(ve)
示例#15
0
from MyGraph import Graph
from ACO import ACO
from Repository import Repository
from Service import Service
r = Repository("hardE.txt", type='coord')
params = {
    'repo': r,
    'graph': r.getGraph(),
    'alpha': 0.5,
    'beta': 0.5,
    'antsNr': 15,
    'q0': 0.5,
    'degrad': 0.5,
    'phero': 5
}
aco = ACO(params)
serv = Service(aco)
serv.run()  #dynamic=False
    print('ok')



def test_next_city():
    print('testing get next city...')
    aco = ACO(0.5, 2, 0, 0, 0, 'test')
    s = Solution(aco.graph)
    c1 = 0
    c3 = 0
    for i in range(1000):
        c = aco.get_next_city(s)
        if c == 3:
            c3 += 1
        elif c == 1:
            c1 += 1
    assert (abs(c3 - 870) < 30)
    assert (abs(c1 - 90) < 30)
    print('ok')
 #   print(c3,c1)


if __name__ == '__main__':
#    test_global_update()
#    test_local_update()
#    test_next_city()
#    test_heuristic2opt()

    aco = ACO(0.9, 2, 0.1, 0.1, 10, 'testa')
    aco.runACO(50)
示例#17
0
def main():
    xmldoc = md.parse('../maps/kt2.net.xml')

    find_junction = xmldoc.getElementsByTagName('junction')
    find_edge = xmldoc.getElementsByTagName('edge')

    edge_num = len(find_edge)
    check = bool
    count = 0

    junc_list, from_node, to_node, edge_list = insertIntoList(
        find_junction, edge_num, find_edge)

    rank = len(junc_list)

    traci.start(sumoCmd)

    step = 0
    end = "e40"
    weight_list = []
    '''while step < 1:
        for i in range(len(edge_list)):
            weight = traci.edge.getTraveltime(edge_list[i])
            weight_list.append(weight)
        step += 1
        traci.simulationStep()'''

    while traci.simulation.getMinExpectedNumber() > 0:
        if step == 70:
            for i in range(len(edge_list)):
                weight = traci.edge.getTraveltime(edge_list[i])
                weight_list.append(weight)

            cost_matrix = createMatrix(junc_list, from_node, to_node,
                                       weight_list, check)

            aco = ACO(5, 100, 0.6, 0.4, 0.3, 10)
            graph = Graph(cost_matrix, rank)
            path, cost = aco.solve(graph)

            route = createRoute(path, junc_list)
            edge = selectEdges(edge_num, find_edge, route, count)

            traci.route.add("optRoute", edge)
            traci.vehicle.add('veh0', "optRoute", typeID='DEFAULT_VEHTYPE')
            traci.vehicle.setColor('veh0', (255, 0, 0))
            # traci.vehicle.setRoute('veh0', edge)

            while traci.simulation.getMinExpectedNumber() > 0:

                if "veh0" in traci.simulation.getArrivedIDList():
                    break
                traci.simulationStep()
            break

        step += 1
        traci.simulationStep()

    traci.close()

    display(cost, route, edge)
            sum_of_row = int(arc[1])
            row = [arc[1]]
        else:
            row.append(arc[1])
            sum_of_row += int(arc[1])
    if sum_of_row:  # checks if a new tow has started
        sol.append(row)
    return sol


if __name__ == "__main__":
    Niter = 30
    Nant = 200
    filename1 = "rotterdam.txt"
    print(filename1 + " :")
    ant_colony = ACO(filename1, Nant, Niter, 4, rho=0.95, alpha=1, beta=3)
    shortest_path, fitness = ant_colony.run()
    sol = print_sol(shortest_path)
    print("manged to organize in ", fitness, " rows")
    print(sol)
    print("population = ", Nant, "     num_of_iter = ", Niter)
    print("calculated the fitness ", str(Niter * Nant), " times\n\n")

    filename2 = "roskilde.txt"
    print(filename2 + " :")
    ant_colony = ACO(filename2, Nant, Niter, 4, rho=0.95, alpha=1, beta=3)
    shortest_path, fitness = ant_colony.run()
    sol = print_sol(shortest_path)
    print("manged to organize in ", fitness, " rows")
    print(sol)
    print("population = ", Nant, "     num_of_iter = ", Niter)
示例#19
0
# -*- coding: utf-8 -*-


from ACO import AntforTSP as ACO
import numpy as np
import os
def PrintBorad(n,shortest_path):
    print("Checkerboard pattern:")
    x = np.zeros((n, n), dtype=int)
    # fill with 1 the alternate rows and columns
    i = 0
    for a in shortest_path:
        x[i,a] = 1
        i += 1
    # print the pattern
    np.savetxt("temp.txt", x, fmt="%d")
    for i in range(n):
        for j in range(n):
            print(x[i][j], end=" ")
        print()

if __name__ == "__main__" :
    Niter = 100
    Nant = 200
    n_queens = 64
    ant_colony = ACO(n_queens, Nant, Niter, rho=0.95, alpha=1, beta=8)
    shortest_path = ant_colony.run()
    PrintBorad(n_queens,shortest_path[0])
    print("shortest_path: {}".format(shortest_path))
示例#20
0
from ACO import ACO
from Graph import Graph
from Read import read, readTSP
from random import seed
from random import randint

net = read('data/easy.txt')
graph = Graph(net['mat'], net['noNodes'])
aco = ACO(100, 150, 1, 1, 0.5, 5)
bestSolution, bestDistance = aco.solve(graph)
print(str(bestDistance) + ": ")
for i in range(len(bestSolution)):
    print(str(bestSolution[i]) + " ")
    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')


def test_next_city():
    print('testing get next city...')
    aco = ACO(0.5, 2, 0, 0, 0, 'test')
    s = Solution(aco.graph)
    c1 = 0
    c3 = 0
    for i in range(1000):
        c = aco.get_next_city(s)
        if c == 3:
            c3 += 1
        elif c == 1:
            c1 += 1
    assert (abs(c3 - 870) < 30)
    assert (abs(c1 - 90) < 30)
    print('ok')


if __name__ == '__main__':
    aco = ACO(0.9, 2, 0.1, 0.1, 10, 'canada')
    sol = aco.runACO(1)
    print(sol.visited, sol.cost, sol.get_cost(Source=0), b - a)
示例#22
0
import numpy as np
import time
from ACO import ACO
from MatrixGraph import MatrixGraph

mtxgraph = MatrixGraph()
distances = mtxgraph.encode_to_array('example.tsp')
aco = ACO(distances, 1, 1, 100, 0.95, alpha=1, beta=1)
mtxgraph.normalize_answer(shortest_path)
print("The shortest path in the graph is {} with length {}".format(
    shortest_path[0], shortest_path[1]))
fd.close()
    """*********** REGLAGE Q0 ************* """
    Param = 'Reglage_q0' #<-------------------------------------------
    Reglages = []

    Param_values = [0.95, 0.9, 0.75, 0.5, 0.25] #<-------------------------------------------

    for value in Param_values:

        costs_list = []
        cpu_lists = []

        for case in range(5):

            start_time = time.time()

            aco = ACO(value, 2, 0.1, 0.1, 10, 'qatar') #<-------------------------------------------
            aco.runACO(100)

            costs_list.append(aco.best.cost)

            end_time = time.time()
            cpu_time = end_time - start_time

            cpu_lists.append(cpu_time)

            mean_cost = sum(costs_list)/len(costs_list)
            mean_cpu = sum(cpu_lists)/len(cpu_lists)

        Reglages.append([aco.parameter_q0, mean_cost, mean_cpu]) #<-------------------------------
        print(Param+'= '+ str(aco.parameter_q0)+ ' val= '+ str(value)+ ' CoutMoy= '+ str(mean_cost)+ ' TempsMoy(s)= '+ str(mean_cpu)) #<-------------------------------
示例#24
0
文件: train.py 项目: ap9272/SOP-2016
                    # print pheromone_initial_array
                    # pi_index = 0.001
                    # pu_index = 0.5
                    # hi_index = 0
                    # hu_index = 0.3
                    # e_index = 0.8

                    # sys.stdout.write(str(pi_index) + "," + str(pu_index) + "," + str(hi_index) + "," + str(hu_index) + "," + str(e_index) + ",")
                    initialize_arrays(pi_index, hi_index)

                    print "Training"
                    for j in range(9):
                        for i in range(j, len(data), 10):
                            #prediction =
                            ACO(data.iloc[i], pi_index, pu_index, hi_index,
                                hu_index, e_index)

                            #print prediction
                            # if prediction == data['sentiment'][i]:
                            #     correct += 1
                            # else:
                            #     incorrect += 1

                            #print str(correct) + "," + str(incorrect)

                        result_after_iteration()

                    # print_graph()

                    print "Testing"
                    for i in range(9, len(data), 10):