Exemplo n.º 1
0
def main():
    
    
    graph = readFromFile('fisiereInput/easy2.txt' )  # cititre normala
    lungimeGraf=len(graph)
    params = Params(70, 800, 1, 11, 0.3, 0.7, graph, lungimeGraf , [[0] *  lungimeGraf] *  lungimeGraf)


    
    aco = ACO(params)
   
   

    for gen in range(params.noGen):
        aco.initialize(params)
        i=0
        while i!=params.nrTowns - 1:
  
            # fiecare furnica face o mutare/un pas
            aco.realizeazaFurnicileMutare()
            i=i+1

        aco.revinFurnicileStart()
        params.matriceFeromon = aco.actualizeazaCantitateFeromon()
        bestFurnica = aco.furnicaCuDrumulMinim()

        print('Generatia: ' + str(gen) + ' cu reprezentarea ' + str(bestFurnica.representation) + ' si costul ' + str(
            bestFurnica.cost))
Exemplo n.º 2
0
def ejecutando_algoritmo(a):

    save_path = '/home/optimizacion_final/datos_json'

    name_of_file = 'estado'

    completeName = os.path.join(save_path, name_of_file + ".txt")

    with open(completeName) as json_file:
        data = json.load(json_file)

    data[a]['estado'] = 'ejecutando'

    with open(completeName, 'w') as outfile:
        json.dump(data, outfile)

    if (a == 'GA'):
        GA.ejecutarGA()

    if (a == 'SA'):
        SA.ejecutarSA()

    if (a == 'PSO'):
        PSO.ejecutarPSO()

    if (a == 'ACO'):
        ACO.ejecutarACO()
Exemplo n.º 3
0
 def __init__(self,instance,numAnts,max_evals,max_gens,rho,ph_max=1,ph_min=0,alpha=1,beta=1,ax=None):
     """
     Initialise base Ant Colony Optimization for Max-Cut
     Doing Gray Box Optimalization with weights and problem structure known we additionally have:
     :param beta : local heuristic information factor for weights (how much do we use the heuristic 'just take edges with large weight')
     """
     ACO.__init__(self,instance,numAnts,max_evals,max_gens,rho,ph_max,ph_min,alpha,ax)
     self.beta = beta
def gridSearch(X,
               instance,
               numAnts,
               max_evals,
               max_gens,
               rho_list,
               alpha_list,
               beta_list,
               ph_min_list,
               ph_max_list,
               BBO=True):
    plt.ion()
    fig, ax = plt.subplots()
    ax.set_xlabel("# evaluations")
    ax.set_ylabel("fitness")
    lab = ""

    # cm = plt.get_cmap('gist_rainbow')
    cm = plt.get_cmap('tab20')
    markers = ["x", "^"]
    markerind = 0
    NUM_COLORS = len(rho_list) * len(alpha_list) * len(beta_list)
    ax.set_prop_cycle(
        color=[cm(1. * i / NUM_COLORS) for i in range(NUM_COLORS)])

    for rho in rho_list:
        for alpha in alpha_list:
            for beta in beta_list:
                for ph_min in ph_min_list:
                    for ph_max in ph_max_list:
                        if BBO:
                            ACO_instance = ACO.ACO_BBO2(
                                instance, numAnts, max_evals, max_gens, rho,
                                ph_max, ph_min, alpha)
                            lab = r"$\rho = %.2f, \alpha = %.2f $" % (rho,
                                                                      alpha)
                        else:
                            ACO_instance = ACO.ACO_GBO(instance, numAnts,
                                                       max_evals, max_gens,
                                                       rho, ph_max, ph_min,
                                                       alpha, beta)
                            lab = r"$\rho = %.2f, \alpha = %.2f, \beta = %.2f $" % (
                                rho, alpha, beta)

                        x, y, e, _ = rn.executeXtimes(X, ACO_instance)
                        ax.errorbar(x,
                                    y,
                                    e,
                                    linestyle='None',
                                    marker=markers[markerind],
                                    label=lab)
                        ax.legend(loc="lower right")
                        plt.draw(), plt.pause(1e-4)
                        markerind = 1 - markerind

    plt.ioff()
Exemplo n.º 5
0
    def run(self):
        maze.initMatrix()
        ACO.createAnts()
        Astar.findPath()
        running = self.pause()  # 刚开始先暂停

        while running:
            for event in pygame.event.get():

                if event.type == KEYDOWN:
                    if event.key == K_SPACE:  # 按空格暂停
                        running = self.pause()
                    elif event.key == K_UP:  # 按向上重置
                        maze.initMatrix()
                        ACO.createAnts()
                        Astar.findPath()

                elif event.type == pygame.QUIT:  # 退出
                    running = False

            self.drawMap()
            pygame.display.flip()  # 画
            # --------------
            ACO.moveAnts()
            ACO.globalEvaporate()
            # --------------

        pygame.quit()  # 退出循环后,结束
Exemplo n.º 6
0
def video():
    csv_names = ['cloud-small']
    db_mins = [0.5]
    datasets = load_datasets(csv_names)
    num_clusters = 3
    num_particles = 10

    for i in range(len(csv_names)):
        print("Starting PSO with:", csv_names[i])
        pso = PSO.PSO(num_particles, num_clusters, datasets[csv_names[i]])
        clusters = pso.runSwarm(100)
        evaluate_clusters('PSO', csv_names[i], clusters)
        graph2dClusters(clusters, 'PSO')

        print("Starting ACO with:", csv_names[i])
        aco = ACO.ACO(data=datasets[csv_names[i]])
        clusters = dict_to_list(aco.main(csv_names[i], max_iter=100000))
        evaluate_clusters('ACO', csv_names[i], clusters)
        graph2dClusters(clusters, 'ACO-100k iterations')

        print("Starting CL with:", csv_names[i])
        clusters = dict_to_list(CL.train(datasets[csv_names[i]], num_clusters))
        evaluate_clusters('CL', csv_names[i], clusters)
        graph2dClusters(clusters, 'CL')

        print("Starting DB with:", csv_names[i])
        clusters = DB.DBScan(datasets[csv_names[i]], db_mins[i])
        evaluate_clusters('DB', csv_names[i], clusters)
        graph2dClusters(clusters, 'DB')

        print("Starting KM with:", csv_names[i])
        clusters, centers = KM.train(datasets[csv_names[i]], num_clusters)
        clusters = dict_to_list(clusters)
        evaluate_clusters('KM', csv_names[i], clusters)
        graph2dClusters(clusters, 'KM')
Exemplo n.º 7
0
def main():
    csv_names = ['airfoil', 'concrete', 'forestfires', 'machine', 'yacht']
    # Precomputed minimum for DBScan to save computations and user interaction
    db_mins = [9, 75, 88, 2000, 3]
    datasets = load_datasets(csv_names)
    # Number of clusters for CL, KM and PSO
    num_clusters = 5
    # Number of particles for PSO
    num_particles = 10

    for i in range(len(csv_names)):
        print("Starting ACO with:", csv_names[i])
        aco = ACO.ACO(data=datasets[csv_names[i]])
        clusters = dict_to_list(aco.main(csv_names[i], max_iter=1000000))
        evaluate_clusters('ACO', csv_names[i], clusters)

        print("Starting CL with:", csv_names[i])
        clusters = dict_to_list(CL.train(datasets[csv_names[i]], num_clusters))
        evaluate_clusters('CL', csv_names[i], clusters)

        print("Starting DB with:", csv_names[i])
        clusters = DB.DBScan(datasets[csv_names[i]], db_mins[i])
        evaluate_clusters('DB', csv_names[i], clusters)

        print("Starting KM with:", csv_names[i])
        clusters = dict_to_list(KM.train(datasets[csv_names[i]], num_clusters))
        evaluate_clusters('KM', csv_names[i], clusters)

        print("Starting PSO with:", csv_names[i])
        pso = PSO.PSO(num_particles, num_clusters, datasets[csv_names[i]])
        clusters = pso.runSwarm(100)
        evaluate_clusters('PSO', csv_names[i], clusters)
def doGlobalTest():
    np.set_printoptions(formatter={'float': lambda x: "{0:0.2f}".format(x)})
    instances_directory = 'testinstances/'
    opt_directory = 'opts/'
    instancenamelist = [
        "maxcut_random_16_0.4_100_instance_0",
        "maxcut_random_32_0.4_100_instance_1",
        "maxcut_random_64_0.4_100_instance_2",
        "maxcut_random_128_0.4_100_instance_3",
        "maxcut_random_256_0.4_100_instance_4",
        "maxcut_random_512_0.4_100_instance_5"
    ]
    # instancenamelist = ["maxcut_random_16_0.4_100_instance_0","maxcut_random_32_0.4_100_instance_1"]
    plt.ion()

    f = open("ACOend_results.txt", "a")
    f.write(
        "filename \t\t\t\t\t\t\t evaluations \t mean \t std \t maxfitness \n")
    # f2 = open("ACOrun_results.txt","w")
    for instancename in instancenamelist:
        fig, ax = plt.subplots()

        instance = maxcut.MaxCut(instancename + ".txt", instances_directory,
                                 opt_directory)
        numAnts = 20
        max_evals = 10000000000
        max_gens = 200

        # best parameters for instance newL50_1_opt2078 without local search, rho = 0.2
        rho = 0.3  # result for with local search on N=128, 0.3 or 0.35
        ph_max = 100
        ph_min = 0.1
        alpha = 0.7

        ACO_instance = ACO.ACO_BBO2(instance, numAnts, max_evals, max_gens,
                                    rho, ph_max, ph_min, alpha)

        X = 10
        x, y, e, maxfit = rn.executeXtimes(X, ACO_instance)
        ax.errorbar(x, y, e, linestyle='None', marker="x", label=instancename)
        ax.legend(loc="lower right")
        plt.draw(), plt.pause(1e-4)

        f.write("%s \t %.0f \t %.2f \t %.5f \t %.0f \n" %
                (instancename, x[-1], y[-1], e[-1], maxfit))
        f.flush()
        # f.write("end mean: %.2f \n" % y[-1])
        # f.write("end std: %.5f \n" % e[-1])
        # f.write("best fitness found: %.0f" % maxfit)

    plt.ioff()
    f.close()
    plt.show()
def main():
    problema = sphere.Sphere()
    individuos = 32
    dimensiones = [2, 4, 8, 16]
    intervalos = 8
    a = 1
    Q = 20
    evaporacion = 0.9
    t0 = 0.00001
    generaciones = 2000
    for dim in dimensiones:
        for i in range(5):
            aco = ACO.ACO(i, individuos, dim, intervalos, a, Q, evaporacion,
                          t0, problema, generaciones)
            aco.run()
Exemplo n.º 10
0
def main():
    ros = rosenbrock.Rosenbrock()
    individuos = 32
    dimensiones = [2, 4, 8, 16]
    intervalos = 8
    a = 1
    Q = 20
    evaporacion = 0.9
    t0 = 0.00001
    generaciones = 2000
    for dim in dimensiones:
        for i in range(5):
            aco = ACO.ACO(i, individuos, dim, intervalos, a, Q, evaporacion,
                          t0, ros, generaciones)
            aco.run()
Exemplo n.º 11
0
def main():
    ros = rosenbrock.Rosenbrock()
    sph = sphere.Sphere()
    qua = quartic.Quartic()
    ras = rastrigin.Rastrigin()

    aux = np.array([])
    graph = np.array([])
    ejecuciones = 1
    draw = drawer.Drawer()

    individuos = 32
    dimensiones = 16
    intervalos = 8
    a = 1
    Q = 20
    evaporacion = 0.9
    t0 = 0.00001
    generaciones = 100
    bestFitnessPos = 100

    graphName = "Quartic" + str(dimensiones) + "D"
    aco = ACO.ACO(individuos, dimensiones, intervalos, a, Q, evaporacion, t0,
                  ras, generaciones, bestFitnessPos)

    for i in range(ejecuciones):
        aux = aco.run()
        if i == 0:
            graph = aux
        else:  #Sumamos el resto de las ejecuciones.
            for a in range(len(aux)):
                graph[a] = graph[a] + aux[a]

    for x in range(len(graph)):
        graph[x] = graph[
            x] / ejecuciones  #Obtenemos el promedio de cada posicion

    draw.drawIndividual(graph, graphName)

    file = open(graphName + ".txt", "w")
    for y in range(len(graph)):
        file.write(str(graph[y]) + "\n")
    file.close()
Exemplo n.º 12
0
          (108.33, 22.84), (126.63, 45.75), (125.35, 43.88), (123.38, 41.8),
          (114.48, 38.03), (112.53, 37.87), (101.74, 36.56), (117, 36.65),
          (113.6, 34.76), (118.78, 32.04), (117.27, 31.86), (120.19, 30.26),
          (119.3, 26.08), (115.89, 28.68), (113, 28.21), (114.31, 30.52),
          (113.23, 23.16), (121.5, 25.05), (110.35, 20.02), (103.73, 36.03),
          (108.95, 34.27), (104.06, 30.67), (106.71, 26.57), (102.73, 25.04),
          (114.1, 22.2), (113.33, 22.13)]

city = city34
d = cal_distance(city)

aco_round = 5000
ga_round = 5000
ts_round = 5000
sa_round = 5000
aco_champions, aco_best, aco_t = ACO.tsp_aco(city, d, aco_round)
ga_champions, ga_best, ga_t = GA.tsp_ga(city, d, ga_round)
ts_champions, ts_best, ts_t = TS.tsp_ts(city, d, ts_round)
sa_champions, sa_best, sa_t = SA.tsp_sa(city, d, sa_round)

# sa result
plot_champions(sa_champions)
plot_current_best(city, sa_best)
print("sa best", sa_best[0], "spend", sa_t, "round", sa_round)

# ts result
plot_champions(ts_champions)
plot_current_best(city, ts_best)
print("ts best", ts_best[0], "spend", ts_t, "round", ts_round)

# ga result
Exemplo n.º 13
0
            p = kkk[0]
            x = kkk[1]
            y = kkk[2]
            p, x, y = int(p)-1, int(x), int(y)
            for j in range(i, len(points)):
                #[p1, x1, y1] = points[j].split(' ')
                kkk = points[j].split(' ')
                p1 = kkk[0]
                x1 = kkk[1]
                y1 = kkk[2]
                p1, x1, y1 = int(p1)-1, int(x1), int(y1)
                self.matrix[p][p1] = self.matrix[p1][p] = round(distance(x, x1, y, y1),2)

if __name__ == '__main__':

    # ten program testuje instancje przykladowa
    # narazie jest to ta bayg29 ale mozeliwe ze moze to byc nasz instancja
    for c in range(2):
        print("\nProba {0}\n".format(c))
        contents = open("bayg29.txt", "r").readlines()  # load data

        print("wyniki dla bayg29:")

        n = int(contents[0]) # number of vertex
        contents = contents[1:] #coordinates of vertex (starts at one)
        graph =Graph(n, contents)
        greedySol=Greedy.Greedy_Solution(graph)
        AcoSol=ACO.antcolony(graph)
        printResults(greedySol, AcoSol)
        print("---------------------------------------------------------------------")
Exemplo n.º 14
0
Arquivo: Main.py Projeto: Zonaira/ACO
import ACO
import Functions

colony = ACO.ACO()
ranges = [[-5,5],
          [-5,5],
          [-5,5]]

colony.cost(Functions.Sphere)
colony.variables(3, ranges)
colony.parameters(50, 5, 50, 0.01, 0.85)
solution = colony.optimize()

print "Optimized solution is"
print solution
def pruebaACO(d,k):

    for i in range(5):
        ACO.ejecutarACO(d,i,k)
Exemplo n.º 16
0
def main():

    # creates 2D mock data for testing the clusters
    mockData = []
    for i in range(100):
        mockData.append([random.uniform(0, .4), random.uniform(0.6, 1)])
        mockData.append([random.uniform(0.6, 1), random.uniform(0, 0.4)])

    # select the data to use by uncommenting the relevant line
    #data, name = import_data('datasets/car.txt')  # 4 clusters
    #data, name = import_data('datasets/cmc.txt')  # 3 clusters
    #data, name = import_data('datasets/seeds.txt')  # 3 clusters
    #data, name = import_data('datasets/wholesale_customers data.txt') # ? clusters
    #data, name = import_data('datasets/yeast.txt')  # 5/6 to 10 clusters
    #data, name = import_data('datasets/iris.txt')  # 3 clusters
    data, name = (mockData, 'mock')

    # select which algorithm to run by setting  their entry to True
    algorithms = {"KMeans": True, "DBScan": True, "CompLearn": True, "PSO": True, "ACO": True}

    # set display to True to output 2D scatter plots of clusters
    display = True

    if algorithms["KMeans"]:
        print("Using K-Means to cluster dataset {}:".format(name))
        start = time.time()
        clusters = KMeans.kmeans_clustering(copy.deepcopy(data), 2, 10000)
        end = time.time()
        test_clustering(clusters, end-start, normal=False)
        if display: show_2d_clusters(data, clusters, normal=False)

    if algorithms["DBScan"]:
        print("Using DBScan to cluster dataset {}:".format(name))
        start = time.time()
        clusters = DBScan.db_clustering(copy.deepcopy(data), 20, 0.3)
        end = time.time()
        if clusters:
            test_clustering(clusters, end - start, normal=False)
        else:
            print("No clusters returned.\nTime = {}".format(end - start))

        if display: show_2d_clusters(data, clusters, normal=False)

    if algorithms["CompLearn"]:
        print("Using CompLearn to cluster dataset {}:".format(name))
        start = time.time()
        clusters = CompLearn.complearn_clustering(copy.deepcopy(data), 4, 100000)
        end = time.time()
        test_clustering(clusters, end - start, normal=True)

        if display: show_2d_clusters(data, clusters, normal=True)

    if algorithms["PSO"]:
        print("Using PSO to cluster dataset {}:".format(name))
        start = time.time()
        clusters = PSO.pso_clustering(copy.deepcopy(data), 2, 1000)
        end = time.time()
        test_clustering(clusters, end - start, normal=False)

        if display: show_2d_clusters(data, clusters, normal=False)

    if algorithms["ACO"]:
        print("Using ACO to cluster dataset {}:".format(name))
        start = time.time()
        clusters = ACO.aco_clustering(copy.deepcopy(data), 40, 500000, display)
        end = time.time()
        test_clustering(clusters, end - start, normal=True)
Exemplo n.º 17
0
    variables = (sys.argv[1], sys.argv[2], sys.argv[3], sys.argv[4],
                 sys.argv[5])
    #            Type         DataSet      numParam     iterations   other

    data = getInputData('DataSets/' + str(variables[1]))
    print("DataSet:", str(variables[1]))
    print("\nInputs:\n" + str(data) + '\n')
    if variables[0] == 'K':
        clusters = kmeans.kmeans(data, int(variables[2]), int(variables[3]))
    elif variables[0] == 'D':
        clusters = dbscan.dbscan(data, 15)
    elif variables[0] == 'C':
        clusters = compLearn.compLearn(data, int(variables[2]),
                                       int(variables[3]), float(variables[4]))
    elif variables[0] == 'A':
        clusters = ACO.ACO(data, int(variables[2]), int(variables[3]))
    elif variables[0] == 'P':
        clusters = PSO.PSO(data, int(variables[2]), int(variables[3]))
    else:
        print('Unknown function specified...')
        sys.exit(1)
    print("\nClusters:\n" + str(clusters))
    (coh, sep) = main(clusters)
    print("\nNumClusters:", len(clusters))
    print("\nNumPerCluster:", [len(x) for x in clusters])
    print("\nCohesion:", coh)
    print("\nSeperation: ", sep)

    #data = getInputData('DataSets/blood.txt')
    #print("Inputs:\n" + str(data))
    ##clusters = PSO.PSO(data, 5, 1000)
import ACO
from heuristics import cost, energy
import random
import plot

colony = ACO.AntColony(neighbour_radius=10000,
                       energy_heuristic=energy.euclideanEnergy,
                       energy_kwargs={"weight": float('inf')},
                       ant_count=10,
                       cycles=10,
                       cost_heuristic=cost.euclideanCost)
#Producers
for i in range(10):
    n = ACO.Node(demand=0,
                 production=10,
                 position=(random.randint(0, 50), random.randint(0, 50)))
    colony.addNode(n)

#Consumers
for i in range(5):
    d = ACO.Node(demand=10,
                 production=0,
                 position=(random.randint(0, 50), random.randint(0, 50)))
    colony.addNode(d)

cost, solution = colony.solve()
print(cost)
plot.plot_solution(solution, colony.graph)
Exemplo n.º 19
0
import util
import ACO
import random
from pprint import pprint

ambient = util.generateCities(30)
antColony = ACO.antColony(len(ambient['cities']),
                          random.randrange(0, len(ambient['cities'])))

ACO.ACO(antColony, ambient, 0.1)
Exemplo n.º 20
0
 def __init__(self,instance,numAnts,max_evals,max_gens,rho,ph_max=1,ph_min=0,alpha=1,ax=None):
     ACO.__init__(self,instance,numAnts,max_evals,max_gens,rho,ph_max,ph_min,alpha,ax)
Exemplo n.º 21
0
    instance = mc.MaxCut(instancename+".txt", instances_directory, opt_directory)
    numAnts = 20
    max_evals = 1000
    max_gens = 100
    # rho = 1 - 0.01**(1/(max_evals/4))

    # 
    rho = 0.21
    ph_max=10
    ph_min=0.1
    alpha = 0.7

    fig, ax = plt.subplots()
    fig2, ax2 = plt.subplots()

    ACO_BBO = ACO.ACO_BBO(instance,numAnts,max_evals,max_gens,rho,ph_max,ph_min,alpha,ax)
    ACO_BBO.run()

    ACO_BBO2 = ACO.ACO_BBO2(instance,numAnts,max_evals,max_gens,rho,ph_max,ph_min,alpha,ax)
    ACO_BBO2.run()

    # GBO
    rho = 0.41
    alpha = 1.5
    beta = 1

    # ACO_GBO = ACO.ACO_GBO(instance,numAnts,max_evals,max_gens,rho,ph_max,ph_min,alpha,beta,ax)
    # ACO_GBO.run()

    # ACO_GBO2 = ACO.ACO_GBO2(instance,numAnts,max_evals,max_gens,rho,ph_max,ph_min,alpha,beta,ax)
    # ACO_GBO2.run()
def main(argv):

    parser = argparse.ArgumentParser()

    parser.add_argument(
        '-o',
        action='store',
        dest='output_file',
        help='The file where to save the solution and, in case, plots')

    parser.add_argument('-t',
                        action='store',
                        dest='time_limit',
                        type=int,
                        required=True,
                        help='The time limit')

    parser.add_argument('-s',
                        dest="split_route",
                        action='store_true',
                        help='Split the route to different subplot')

    parser.add_argument('-g',
                        dest="graphic_sol",
                        action='store_true',
                        help='graphical solution')

    parser.add_argument('instance_file',
                        action='store',
                        help='The path to the file of the instance to solve')

    parser.add_argument(
        '-all',
        action='store',
        dest='all',
        help='The file where to save the solution and, in case, plots')

    parser.add_argument(
        '-performancetest',
        action='store',
        dest='performancetest',
        help='The file where to save the solution and, in case, plots')

    config = parser.parse_args()

    print('instance_file    = {!r}'.format(config.instance_file))
    print('output_file      = {!r}'.format(config.output_file))
    print('time_limit       = {!r}'.format(config.time_limit))
    print('graphical solution= {!r}'.format(config.graphic_sol))
    print('split route       = {!r}'.format(config.split_route))

    if config.performancetest:
        performance_testing()
    else:
        instance = data.Data(config.instance_file)
        # alg = solverNN.algorithm
        # alg = solverCHH.algorithm
        alg = ACO.Ant().algorithm
        # alg = metaFFD.algorithm
        sol = solve(instance, alg, config)

        if config.output_file is not None:
            if config.graphic_sol:
                import matplotlib.pyplot as plt
                plt.figure(figsize=(20, 10))
                plt.rcParams.update({'font.size': 22})
                sol.plot_routes(split=config.split_route,
                                output_filename=config.output_file + '_sol' +
                                '.png')
            # sol.write_to_file(config.output_file+'.sol')
            # print(instance_times_costs)
            # sol.plot_table(config.output_file+'_tbl', instance.instance_name, instance_times_costs)
        print("{} routes with total cost {:.1f}".format(
            len(sol.routes), sol.cost()))
ZZ = tm.time()
P_q0 = [0, 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1]
P_beta = [1.1, 1.5, 2, 2.5, 3, 3.5, 4, 4.5, 5]
P_rho = [0.05, 0.1, 0.15, 0.2, 0.25, 0.3, 0.35, 0.4, 0.45, 0.5]
P_phi = [0.05, 0.1, 0.15, 0.2, 0.25, 0.3, 0.35, 0.4, 0.45, 0.5]
P_K = [1, 2, 5, 10, 15, 20, 25, 30]
N_iter = 250
#(0.8, 2.5, 0.05, 0.1, 15)

resPq0 = []
timePq0 = []
for p in P_q0:
    r = 0
    t = 0
    for i in range(5):
        aco = ACO.ACO(p, 2, 0.1, 0.1, 10, 'qatar')
        a = tm.clock()
        sol = aco.runACO(N_iter)
        b = tm.clock()
        t += b - a
        r += sol.cost
    resPq0.append(r / 5.0)
    timePq0.append(t / 5.0)

q0_opt = P_q0[resPq0.index(min(resPq0))]

plt.figure(1)
plt.plot(P_q0, resPq0)
plt.xlabel("q0")
plt.ylabel("Solution cost")
plt.figure(2)
Exemplo n.º 24
0
#     acalres["atime"] += res["time"]
#     acalres["avalue"] += res["value"]
# amyres["atime"] /= count
# amyres["avalue"] /= count
# acalres["atime"] /= count
# acalres["avalue"] /= count
#
# print("my params:")
# pp.pprint(amyres)
# print("calibrated:")
# pp.pprint(acalres)
# print("\ncalibration result:")
# print("time: {} %, value: {} %".format(
#     round(amyres["atime"] / acalres["atime"] * 100, 2),
#     round(acalres["avalue"] / amyres["avalue"] * 100, 2)
# ))

d_precs = [1, 2, 3, 5, 10, 20, 30, 50, 100, 200, 300]
for d_prec in d_precs:
    log = open("easom_analysis.txt", mode="a+")
    log.write("\n" + "d_prec: {}, ants: {} >".format(d_prec, pow(d_prec, 2)) +
              "\n")
    log.close()
    res = ACO.main_ACO(ft_easom, 2,
                       [[-100, 100], [-100, 100]], d_prec, 0, 0.2, 0.1, 0.25,
                       pow(d_prec,
                           2), fit_min_value, 1000 if d_prec > 5 else 5000)
    log = open("easom_analysis.txt", mode="a+")
    log.write(str(res) + "\n")
    log.close()
Exemplo n.º 25
0
import util
import ACO
import random
from pprint import pprint

ambient = util.getAmbient("RNP.json")
request = util.getRandomRequest(len(ambient['servers'], 5))
antColony = ACO.antColony(15, request)

ACO.ACO(antColony, ambient, 0.1)
Exemplo n.º 26
0
 def run_function(dataset, score_funcs):
     return ACO.ACO(dataset, iterations, num_clusters, num_ants, beta,
                    prob_cutoff, num_elite_ants, decay_rate, q,
                    score_funcs)
Exemplo n.º 27
0
GA_config_iter = config['GA']['iter']
GA_config_pop = config['GA']['populacja']

for i, edge in enumerate(edges_G1):
    edges_G1[i] = eval(edge)

for i, edge in enumerate(edges_G2):
    edges_G2[i] = eval(edge)

nodes_G1 = eval(nodes_G1)
nodes_G2 = eval(nodes_G2)

G1 = nx.Graph()
G1.add_nodes_from(nodes_G1)
G1.add_edges_from(edges_G1)

G2 = nx.Graph()
G2.add_nodes_from(nodes_G2)
G2.add_edges_from(edges_G2)
constGraph = nx.Graph()

if mode == 'ANT':
    A = ACO(G1, G2, int(ANT_config_ant), int(ANT_config_gen),
            float(ANT_config_alpha), float(ANT_config_beta))
    A.ACO_algo()

if mode == 'GA':
    ga = GeneticAlgorithm.GA(G1, G2, float(GA_config_mut), float(GA_config_cr),
                             int(GA_config_iter), int(GA_config_pop))
    ga.Generic_algorithm()