示例#1
0
def main():
    cities = []
    points = []
    # Se lee el archivo .txt se encuentran en orden: el índice de la ciudad, su coordenada en X y su coordenada en Y
    with open(
            '/home/juancm/Desktop/Octavo/Tesis/ProyectoGrado/Metaheuristicas/ant-colony-tsp/ant-colony-tsp/data/chn31.txt'
    ) as f:
        for line in f.readlines():
            city = line.split(' ')
            cities.append(
                dict(index=int(city[0]), x=int(city[1]), y=int(city[2])))
            points.append((int(city[1]), int(city[2])))

    # Se genera la matriz de costos a partir de los nodos y las coordenadas leídas
    cost_matrix = []
    rank = len(cities)
    for i in range(rank):
        row = []
        for j in range(rank):
            row.append(distance(cities[i], cities[j]))
        cost_matrix.append(row)
    # Se instancia ACO, en donde se envía como parámetro: la cantidad de ants, el número de generaciones, alpha, beta, rho, Q, Estrategia para calccular T(i,j)
    aco = ACO(10, 100, 1.0, 10.0, 0.5, 10, 2)
    graph = Graph(cost_matrix, rank)
    path, cost = aco.solve(graph)
    print('cost: {}, path: {}'.format(cost, path))
    plot(points, path)
def main():
    cities = []
    points = []
    with open('./data/att48.txt') as f:
        for line in f.readlines():
            city = line.split(' ')
            cities.append(dict(index=int(city[0]), x=int(city[1]), y=int(city[2])))
            points.append((int(city[1]), int(city[2])))
    cost_matrix = []
    rank = len(cities)
    #print(cities)
    #print(rank)
    for i in range(rank):
        row = []
        for j in range(rank):
            row.append(distance(cities[i], cities[j]))
        cost_matrix.append(row)
        #print(row)
    start = time()
    #print(rank)
    aco = ACO(10, 100, 2.0, 10.0, 0.5, 10, 2)
    graph = Graph(cost_matrix, rank)
    path, cost = aco.solve(graph)
    print('cost: {}, path: {}'.format(cost, path))
    tottime = time() - start
    #plot(points, path)
    print('TotalTime : ', tottime)
示例#3
0
def main():
    cities = []
    cost_matrix = []

    with open(settings.CITIES_DISTANCE) as f:
        data = json.load(f)

    for k, v in data.items():
        x, y = v['point']
        cities.append((y, x, k))
        cost_matrix.append([city['distance'] for city in v['cities']])

    aco = ACO(
        ant_count=20,
        run_without_improvement=20,
        alpha=2,
        beta=5,
        rho=0.5,
        q=5,
        pheromone_strategy='ant_density')

    graph = Graph(cost_matrix)
    path, cost = aco.solve(graph)
    print('cost: {}, path: {}'.format(cost, path))
    plot(cities, path)
示例#4
0
def main():
    cities = []
    points = []
    with open('./data/Loc48.txt') as f:
        for line in f.readlines():
            city = line.split(' ')
            cities.append(
                dict(index=int(city[0]), x=float(city[1]), y=float(city[2])))
            points.append((float(city[1]), float(city[2])))
    costmatrix = []
    level = len(cities)

    for i in range(level):
        row = []
        for j in range(level):
            row.append(distance(cities[i], cities[j]))

        costmatrix.append(row)

    aco = ACO(10, 100, 1.0, 10.0, 0.5, 10)
    graph = Graph(costmatrix, level)
    time, path, cost = aco.solve(graph)
    print('cost: {}, path: {}'.format(cost, path))
    print('Time taken: ', time, 'sec')
    plot(points, path)
示例#5
0
def main():
    cities = []
    points = []
    with open('./data/ulysses16.tsp') as f:
        for line in f.readlines():
            #print(line)
            city = line.split(' ')
            #print(city)
            cities.append(dict(index=float(city[0]), x=float(city[1]), y=float(city[2])))
            #print(cities)
            points.append((float(city[1]), float(city[2])))
    cost_matrix = []
    rank = len(cities)
    #print(rank)
    for i in range(rank):
        row = []
        for j in range(rank):
            row.append(distance(cities[i], cities[j]))
        cost_matrix.append(row)
    #print('cost_matrix',cost_matrix)
    aco = ACO(100,1, 1.0, 10.0, 0.5, 10, 2)
    graph = Graph(cost_matrix, rank)
    path, cost = aco.solve(graph)
    cost=cost+cost_matrix[path[-2]][path[-1]]
    print('cost: {}, path: {}'.format(cost, path))
    plot(points, path)
示例#6
0
def main():
    sheep = []
    values = []
    cont = 0
    max_weight = 2400

    with open('./data/sheep_list_range2_500_arc4b.txt') as f:
        for line in f.readlines():
            if (cont >= 1):
                s = line.split(' ')
                sheep.append(
                    dict(index=int(s[0]), x=float(s[1]), y=float(s[2])))
            cont = cont + 1

    cost_matrix = []
    rank = len(sheep)
    for i in range(rank):
        row = []
        for j in range(rank):
            row.append(sheep[j]['y'])
        cost_matrix.append(row)

    #print(cost_matrix)

    aco = ACO(50, 5, 1.0, 10.0, 0.5, 10, 2)
    path, cost = aco.solve(sheep, max_weight)
    print('cost: {}, path: {}'.format(cost, path))
示例#7
0
def run(num_cities):
    cities = []
    points = []
    with open('./data/chn31.txt') as f:
        counter = 0
        for line in f.readlines():
            if counter < num_cities:
                city = line.split(' ')
                cities.append(
                    dict(index=int(city[0]), x=int(city[1]), y=int(city[2])))
                points.append((int(city[1]), int(city[2])))
                counter += 1
    cost_matrix = []
    rank = len(cities)
    for i in range(rank):
        row = []
        for j in range(rank):
            row.append(distance(cities[i], cities[j]))
        cost_matrix.append(row)
    aco = ACO(10, 100, 1.0, 10.0, 0.5, 10, 2)
    graph = Graph(cost_matrix, rank)
    path, cost = aco.solve(graph)
    print('number cities: {},cost: {}, path: {}'.format(
        num_cities, cost, path))
    plot(points, path)
    return path, cost
示例#8
0
def main():

    args = parse_args()

    file = args.graph
    matrix, n, m = read_file(file)

    # execution parameters
    ants = args.num_ants
    iterations = args.iterations
    evaporation = args.evaporation
    alpha = args.alpha
    beta = args.beta
    runs = args.runs

    # default
    strategy = 1
    update_pheromone = 2
    min_ph = 0.0001
    max_ph = 10.0
    initial_pheromone = args.initial
    q = args.intensity

    final_results = []
    train_results = []
    for i in range(1, runs + 1):
        # create ACO object
        aco = ACO(ants, iterations, alpha, beta, evaporation, q, strategy,
                  update_pheromone, min_ph, max_ph)
        # create Graph object
        graph = Graph(matrix, n, m, initial_pheromone)
        # Run ACO
        path, cost, stats = aco.solve(graph, i)
        print('------------------------------')
        print('Run ', i)
        print('cost: {}, path: {}'.format(cost, path))
        print(len(path))
        final_results.append((i, cost, len(path)))
        train_results = train_results + stats

    output_file = args.output_file

    col_names = ("repetition", "iteration", "best_cost", "worst_cost",
                 "best_local", "worst_local", "mean_local")

    frame = pd.DataFrame.from_records(train_results, columns=col_names)
    frame.to_csv(output_file + "_train.csv",
                 index=False,
                 sep='\t',
                 encoding='utf-8')

    col_names = ("repetition", "cost", "path_len")
    frame = pd.DataFrame.from_records(final_results, columns=col_names)
    frame.to_csv(output_file + "_final.csv",
                 index=False,
                 sep='\t',
                 encoding='utf-8')
示例#9
0
def get_path(Point_list):
    cost_matrix=[]
    rank=len(Point_list)
    for i in range(rank):
        row=[]
        for j in range(rank):
            row.append(distance(Point_list[i],Point_list[j]))
        cost_matrix.append(row)
    aco=ACO(10,100,1.0,10.0,0.5,10,2)
    graph=Graph(cost_matrix,rank)
    path,cost=aco.solve(graph)
    path=resort(path)
    return path
示例#10
0
def run():

    cost_matrix, nr_orase = read_matrix('input.txt')
    #updatare feromon: ant_density
    # nr_furnici
    # nr_generatii
    # alpha
    # betha
    # coeficient evaporare
    aco = ACO(nr_orase, 100, 1.0, 30.0, 0.5)

    graph = Graph(cost_matrix, nr_orase)
    path, cost = aco.solve(graph)
    print('cost: {}, path: {}'.format(cost, path))
def main():
    cities = City.load_cities('./data/data30.txt')
    graph = Graph(cities)
    history, cost = ACO(20, 200, 10, [1.0, 3.0], [4.0, 2.0],
                        [0.4, 0.8]).solve(graph)
    print(cost)
    DynamicPlot().show(cities, history)
示例#12
0
文件: main.py 项目: FOliwa/TSP
def main():
    cost_matrix = distance_matrix
    rank = len(distance_matrix[5])
    """
        :param ant_count:
        :param generations:
        :param alpha: relative importance of pheromone
        :param beta: relative importance of heuristic information
        :param rho: pheromone residual coefficient
        :param q: pheromone intensity
        :param strategy: pheromone update strategy. 0 - ant-cycle, 1 - ant-quality, 2 - ant-density
        """
    aco = ACO(10, 100, 1.0, 10.0, 0.5, 10, 2)
    graph = Graph(cost_matrix, rank)
    path, cost = aco.solve(graph)
    print('cost: {}, path: {}'.format(cost, path))
示例#13
0
def main():

    file_path = 'C:\\Users\\zy3\\work\\workspace\\rideco\\Simpsons.txt'
    line_num, name, route, graph_dis, graph_time, task_list = read_file(
        file_path)

    aco = ACO(40, 50, 1.0, 5.0, 0.5, 10, 1, len(name))
    graph = Graph(np.shape(graph_time)[0], line_num, graph_time, task_list)
    path, cost, time_sequence = aco.solve(graph)
    print(path)
    print(cost)
    print(time_sequence)
    print(len(path))
    print(len(time_sequence))

    output_solution(path, time_sequence, task_list, file_path, name)
def main(fh_input: str, colony: int, iters: int, alpha: float, beta: float, vaporize: float, intensity: float, br_count: int, ch_count: int):
    print('Start optimization...')
    aco = ACO(
        instance_file=fh_input,
        vertex=40,
        colony_size=colony,
        iterations=iters,
        alpha=alpha,
        beta=beta,
        pq=vaporize,
        pi=intensity,
        break_count=br_count,
        change_count=ch_count,
    )
    best_c, best_s, time = aco.optimize()
    print('time: {:.2f}, cost: {:.2f}, solution (len): {}'.format(time, best_c, len(best_s)))
示例#15
0
def run_test(bin_num,
             item_num,
             population,
             evaporation_rate,
             scale=False,
             verbose=False):
    """Run a singular ACO test and return an object of the results found."""
    results = []
    average_fitness = 0
    average_time = 0

    total_time = 0

    # Run 5 tests of the ACO algorithm and compile a set of averages.
    for i in range(5):
        bins = generate_bins(bin_num)
        items = generate_items(quantity=item_num, scale=scale)

        trial = ACO(bins, items, population, evaporation_rate, verbose=False)
        trial.run()

        fitness, time = trial.stats()
        results.append((fitness, time))
        average_fitness += fitness * 0.2
        average_time += time * 0.2

    log("Test finished in %d seconds." % total_time, verbose)
    log("Stats:", verbose)
    log(" -- Average Fitness of Test: %f" % average_fitness, verbose)
    log(" -- Average Time Per Test Run: %f" % average_time, verbose)

    return {
        'raw_results': results,
        'bins': bin_num,
        'items': item_num,
        'population': population,
        'evaporation_rate': evaporation_rate,
        'scale': scale,
        'average_fitness': average_fitness,
        'max_fitness': max(results, key=itemgetter(0))[0],
        'min_fitness': min(results, key=itemgetter(0))[0],
        'average_time': average_time,
        'max_time': max(results, key=itemgetter(1))[1],
        'min_time': min(results, key=itemgetter(1))[1],
        'total_time': total_time
    }
示例#16
0
def trial(trials, bins, items, ants, evaporation_rate, bpp2):
    """
    Trials function. Performs n ACO trials
    :param trials: amount of trials
    :param bins: amount of bins
    :param items: amount of items
    :param ants: amount of ants
    :return: a list with minimal fitness, index of the best path,
    best path, bins and execution time.
    """
    overall_output = []
    for i in range(trials):
        b = BinPackingProblem(bins, items, 1, items, bpp2)
        aco = ACO(b, ants, evaporation_rate)
        aco.iterate()
        min_fit, min_index = aco.get_min_fitness()
        best_path = aco.get_best_path()
        b.path_to_bin(best_path)
        output_trial = [
            min_fit, min_index, best_path,
            b.get_bins(),
            aco.get_exec_time()
        ]
        overall_output.append(output_trial)
    return overall_output
def main():

    simulation_runs = 5
    num_ants = 5
    q = 10000
    nc_max = 100

    aco = ACO(simulation_runs=simulation_runs,
              num_ants=num_ants,
              pheromone_quantity=q,
              num_colonies=nc_max)
    tsp = TSP()

    graph_nodes_list = [9, 10, 11]
    alpha_list = [1, 3, 7]
    beta_list = [1, 3, 7]
    ro_list = [0.0, 0.5, 0.9, 1.0]
    table_data = []

    for graph_nodes in graph_nodes_list:
        cost_graph = create_graph(graph_nodes)
        # print_graph(cost_graph)
        total_tsp_cost, tsp_solution = tsp.run(cost_graph)
        for alpha in alpha_list:
            for beta in beta_list:
                for ro in ro_list:
                    print(
                        "graph_nodes = {3}, alpha = {0}, beta = {1}, ro = {2}".
                        format(alpha, beta, ro, graph_nodes))
                    solution, total_aco_cost = aco.run(cost_graph, alpha, beta,
                                                       ro)
                    error_value = abs(total_tsp_cost - total_aco_cost)
                    table_data += [[
                        str(graph_nodes),
                        str(alpha),
                        str(beta),
                        str(ro),
                        str(total_aco_cost),
                        str(total_tsp_cost),
                        str(error_value)
                    ]]
                    pass

    print_table_data(table_data)
示例#18
0
def runACO(numOfBins,
           numOfItems,
           population,
           evaporation,
           bpp1=True,
           numOfTrials=5):
    """Run ACO trial and return an object of the calculated results.
    
    :param numOfBins: number of bins
    :param numOfItems: number of items
    :param population: population size
    :param evaporation: evaporation rate
    :param bpp1: boolean indicating which problem to run
    :param numOfTrials: number of wanted trials for each rule

    :returns: dictionary with results
    """
    results = []
    avgFitness = 0
    avgTime = 0

    # Run 5 trials of the ACO algorithm
    for i in range(numOfTrials):
        bins = createBinObjects(numOfBins)
        items = generateBinItems(quantity=numOfItems, bpp1=bpp1)

        trial = ACO(bins, items, population, evaporation)
        trial.run()

        fitness = trial.bestRun.fitness
        time = trial.runtime

        results.append((fitness, time))
        avgFitness += fitness * 0.2
        avgTime += time * 0.2

    return {
        'avgFitness': avgFitness,
        'maxFitness': max(results, key=itemgetter(0))[0],
        'minFitness': min(results, key=itemgetter(0))[0],
        'avgTime': avgTime,
        'maxTime': max(results, key=itemgetter(1))[1],
        'minTime': min(results, key=itemgetter(1))[1],
    }
示例#19
0
def main():
    cities = []
    points = []
    with open('./data/berlin52.tsp.txt') as f:
        for line in f.readlines():
            city = line.split(' ')
            cities.append(dict(index=int(city[0]), x=int(city[1]), y=int(city[2])))
            points.append((int(city[1]), int(city[2])))
    cost_matrix = []
    rank = len(cities)
    for i in range(rank):
        row = []
        for j in range(rank):
            row.append(distance(cities[i], cities[j]))     #.............................step 0
        cost_matrix.append(row)
    aco = ACO(20, 500, 1.0, 10.0, 0.5, 10, 2) #ant_count,generations,alpha,beta,rho,q,strategy
    graph = Graph(cost_matrix, rank)
    path, cost = aco.solve(graph)
    print('cost: {}, path: {}'.format(cost, path))
    plot(points, path)
示例#20
0
def main():
    cities = []
    points = []
    with open('data/qatar.txt') as f:
        for line in f.readlines():
            city = line.split()
            cities.append(dict(index=int(city[0]), x=float(city[1]), y=float(city[2])))
            points.append((float(city[1]), float(city[2])))
    cost_matrix = []
    rank = len(cities)
    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=500, time_limit=1800, generations=0, alpha=5.0, beta=5.0, rho=0.2, q=5, strategy=1)
    graph = Graph(cost_matrix, rank)
    path, cost, time = aco.solve(graph)
    print("Elapsed time was {0:.1f} seconds.".format(time))
    print('cost: {}, path: {}'.format(cost, path))
示例#21
0
    def find_path(self, maze, locationA, locationB):
        maze.reset_start_end(locationA, locationB)

        tries = 1
        settings = self.base_aco_settings.copy()
        if self.refine:
            settings.update(dict(
                iterations=10,
                ant_count=15,
                ant_max_steps=4000,
                evaporation=0.2
            ))
        else:
            settings.update(dict(
                iterations=4,
                ant_count=10,
                ant_max_steps=4000,
                evaporation=0.1
            ))

        aco = ACO(maze, **settings)
        ant = aco.run()

        if ant is None:
            print 'try reverse,',
            maze.reset_start_end(locationB, locationA)
            aco = ACO(maze, **settings)
            ant = aco.run()
            tries += 1

        if not self.refine:
            while ant is None and tries < 3:
                print 'try %d failed,' % tries,
                # we have to reset pheromone to start a really new search
                maze.reset_pheromone()
                settings.update(dict(
                    iterations=8,
                    ant_count=tries * 10,
                    ant_max_steps=tries * 8000,
                ))
                aco = ACO(maze, **settings)
                ant = aco.run()

                tries += 1

        return ant
示例#22
0
def main():
    cities = []
    points = []
    with open('../data/chn144.txt') as f:
        for line in f.readlines():
            city = line.split(' ')
            cities.append(
                dict(index=int(city[0]), x=int(city[1]), y=int(city[2])))
            points.append((int(city[1]), int(city[2])))
    cost_matrix = []
    rank = len(cities)
    for i in range(rank):
        row = []
        for j in range(rank):
            row.append(distance(cities[i], cities[j]))
        cost_matrix.append(row)
    aco = ACO(15, 100, 1.0, 10.0, 0.5, 10, 2)
    graph = Graph(cost_matrix, rank)
    path, cost = aco.solve(graph)
    print('cost: {}, path: {}'.format(cost, path))
    plot(points, path)
示例#23
0
def main():
    cidades = []
    pontos = []
    with open('./exemplo.txt') as f:
        for line in f.readlines():
            city = line.split(' ')
            cidades.append(
                dict(index=int(city[0]), x=int(city[1]), y=int(city[2])))
            pontos.append((int(city[1]), int(city[2])))
    matriz_custo = []
    rank = len(cidades)
    for i in range(rank):
        row = []
        for j in range(rank):
            row.append(distancia(cidades[i], cidades[j]))
        matriz_custo.append(row)
    aco = ACO(10, 100, 1.0, 10.0, 0.5, 10, 2)
    grafico = Grafico(matriz_custo, rank)
    caminho, custo = aco.resolve(grafico)
    print('custo: {}, caminho: {}'.format(custo, caminho))
    plot(pontos, caminho)
示例#24
0
def particles_prevelance():
    P = generate_p(2)
    x, f_x = PSO(RASTRIGIN, OPSEG_RASTRIGIN, 20, 30, 0, P, 2, True)
    print(x, f_x)

    p = Populacija(RASTRIGIN, OPSEG_RASTRIGIN, 2, 1.7, 30, 0.75, 0.15, 20, 1,
                   20, True)
    x, f_x = p.GenerisiGeneracije()
    print(x, f_x)

    x_best, f_best = ACO(RASTRIGIN, OPSEG_RASTRIGIN, 20, 30, 50, 0.0001, 0.5,
                         2, True)
    print(x_best, f_best)
示例#25
0
def main():
    cities = []
    points = []
    with open('../tsp-instances/instance1.csv') as f:
        index = 1
        for line in f.readlines():
            city = line.split(',')
            cities.append(dict(index=index, x=int(city[0]), y=int(city[1])))
            points.append((int(city[0]), int(city[1])))
            index += 1
    cost_matrix = []
    rank = len(cities)
    for i in range(rank):
        row = []
        for j in range(rank):
            row.append(distance(cities[i], cities[j]))
        cost_matrix.append(row)
    aco = ACO(50, 500, 1.0, 10.0, 0.5, 10, 0)
    graph = Graph(cost_matrix, rank)
    path, cost, time = aco.solve(graph)
    print('cost: {}, path: {}'.format(cost, path))
    plot(points, path)
    return time
示例#26
0
def runtime_rastrigin():
    P = generate_p(2)

    start = time.time()
    for i in range(0, 30):
        PSO(RASTRIGIN, OPSEG_RASTRIGIN, 20, 30, 0, P, 2, False)
    end = time.time()
    print('PSO:', (end - start) / 30)

    start = time.time()
    for i in range(0, 30):
        p = Populacija(RASTRIGIN, OPSEG_RASTRIGIN, 2, 1.7, 30, 0.75, 0.15, 20,
                       1, 20, False)
        p.GenerisiGeneracije()
    end = time.time()
    print('GA', (end - start) / 30)

    start = time.time()
    for i in range(0, 30):
        ACO(RASTRIGIN, OPSEG_RASTRIGIN, 20, 30, 50, 0.0001, 0.5, 2, False)
    end = time.time()
    print('ACO', (end - start) / 30)
示例#27
0
from aco import ACO

#Set parameters for model:
parameters = {
    "seed": 0,  #Random seed that allows replicating results
    "ALPHA": 1,  #Exponential weight of pheromone on walk probabilities
    "BETA": 1,  #Exponential weight of desirability on walk probabilities
    "init_pheromone": 0.999,  #Initial pheromone for all edges
    "pheromone_constant":
    1,  #Constant that helps to calculate edge pheromone contribution
    "min_pheromone": 0.001,  #Minimun pheromone value of an edge
    "evaporation_rate": 0.91,  #Pheromone evaporatio rate per cycle
    "ant_numbers": 20,  #Number of ants walking in a cycle
    "cycles": 20,  #Number of cycles
    "dataset": 'la40.txt'  #File name that contains job/machine times
}

colony = ACO(ALPHA=parameters['ALPHA'],
             BETA=parameters['BETA'],
             dataset=parameters['dataset'],
             cycles=parameters['cycles'],
             ant_numbers=parameters['ant_numbers'],
             init_pheromone=parameters['init_pheromone'],
             pheromone_constant=parameters['pheromone_constant'],
             min_pheromone=parameters['min_pheromone'],
             evaporation_rate=parameters['evaporation_rate'],
             seed=parameters['seed'])

colony.releaseTheAnts()
示例#28
0
from utils import readData
from aco import ACO, World
from plot import plot

if __name__ == '__main__':

    #noCities, cost_matrix, points = readData("D:\\UBB_info_sem_4\\AI\\LAB\\Teme\\Lab5\\ulysses16.txt")
    noCities, cost_matrix, points = readData(
        "D:\\UBB_info_sem_4\\AI\\LAB\\Teme\\Lab5\\data.txt")
    #noCities, cost_matrix, points = readData("D:\\UBB_info_sem_4\\AI\\LAB\\Teme\\Lab5\\data2.txt")
    #noCities, cost_matrix, points = readData("D:\\UBB_info_sem_4\\AI\\LAB\\Teme\\Lab5\\data3.txt")

    paramACO = {
        "ant_count": 10,
        "generations": 100,
        "alpha": 1.0,
        "beta": 10.0,
        "rho": 0.5,
        "q": 10
    }
    paramWorld = {"cost_matrix": cost_matrix, "noCities": noCities}

    aco = ACO(paramACO)
    graph = World(paramWorld)

    path, cost = aco.solve(graph)
    print("\n")
    print("\n")
    print("BEST: Cost: " + str(cost) + " \nPath: " + str(path))
    plot(points, path)
    def calculate_paths(self):
        count = self.count()

        total_paths = 0.5 * (count - 1) * count
        if self.refine:
            total_paths *= 2
            print 'Trying to find better paths in maze...'
        else:
            print 'Calculate paths between %d products (%d paths total) in maze %s.' % (
                count, total_paths, self.maze.name
            )
        overall_start_time = time.time()
        elapsed_list = []

        # # clear paths from/to start/end
        # for A in range(len(self.locations())):
        #     self.set_result(0, A, TSPMaze.FAILED)
        #     self.set_result(19, A, TSPMaze.FAILED)

        # set path from from/to same node to zero
        for A in range(len(self.locations())):
            self.set_result(A, A, None)
        self.dump_cache()

        # set path from start to end and end to start to infinity
        self.set_result(0, self.count() - 1, TSPMaze.INFINITY)

        if self.do_reconnaissance > 0:
            settings = self.base_aco_settings.copy()
            settings.update(dict(
                ant_count=2,
                do_reconnaissance=self.do_reconnaissance
            ))
            aco = ACO(self.maze, **settings)
            maze = aco.reconnaissance(iterations=4)
        else:
            maze = self.maze

        i = 1
        failes = 0
        locationsA = self.locations()
        random.shuffle(locationsA)
        locationsA = locationsA
        for A, locationA in locationsA:
            locationsB = self.locations()
            random.shuffle(locationsB)
            for B, locationB in locationsB:
                i += 1

                if ((A is self.original_start and B is self.original_end) or
                        (B is self.original_start and A is self.original_end) or
                        (not self.refine and self.results[B][A] not in (TSPMaze.EMPTY, TSPMaze.FAILED)) or
                        (A is B)):
                    continue

                print 'Route #%2d (%2d, %2d) -> #%2d (%2d, %2d)' % ((A, ) + locationA + (B, ) + locationB),

                start_time = time.time()
                ant = self.find_path(maze, locationA, locationB)
                elapsed = time.time() - start_time

                elapsed_list.append(elapsed)

                if ant is None:
                    self.set_result(A, B, TSPMaze.FAILED)
                    print RED, '\n!!', ENDC, ' not found in %0.2fs, run again to try again. ' % elapsed
                    failes += 1
                else:
                    self.set_result(A, B, ant)

                    print 'done (length: %d) in %0.2fs' % (len(ant.trail), elapsed)

                if i % self.count() == 1:
                    print '  running %0.2fs now, average time: %0.2fs (TSP matrix done in: %0.0fs)' % (
                        time.time() - overall_start_time,
                        mean(elapsed_list),
                        total_paths * mean(elapsed_list)
                    )

        return failes
示例#30
0
文件: main.py 项目: mesziman/uni
                        graph_roadblock_chance=0.05,
                        graph_roadblock_length=3,
                        graph_quarantine_chance=0.01,
                        no_ants=30,
                        elite_ants_percentage=0.1,
                        pheromones_importance=1,
                        pheromones_leave_quantity=1,
                        pheromones_evaporation_rate=0.02,
                        weight_importance=3)
parameters.graph = Graph.from_path("data/berlin52.txt",
                                   parameters,
                                   separator=",")

seed(103)

profiled = False
console = True
plot = True
no_generations = 500
aco = ACO(parameters)


def run():
    aco.run_iterations(no_generations, console=console, plot=plot)


if profiled:
    cProfile.run(run.__code__)
else:
    run()
    def calculate_paths(self):
        count = self.count()

        total_paths = 0.5 * (count - 1) * count
        if self.refine:
            total_paths *= 2
            print 'Trying to find better paths in maze...'
        else:
            print 'Calculate paths between %d products (%d paths total) in maze %s.' % (
                count, total_paths, self.maze.name)
        overall_start_time = time.time()
        elapsed_list = []

        # # clear paths from/to start/end
        # for A in range(len(self.locations())):
        #     self.set_result(0, A, TSPMaze.FAILED)
        #     self.set_result(19, A, TSPMaze.FAILED)

        # set path from from/to same node to zero
        for A in range(len(self.locations())):
            self.set_result(A, A, None)
        self.dump_cache()

        # set path from start to end and end to start to infinity
        self.set_result(0, 19, TSPMaze.INFINITY)

        if self.do_reconnaissance > 0:
            settings = self.base_aco_settings.copy()
            settings.update(
                dict(ant_count=2, do_reconnaissance=self.do_reconnaissance))
            aco = ACO(self.maze, **settings)
            maze = aco.reconnaissance(iterations=4)
        else:
            maze = self.maze

        i = 1
        failes = 0
        locationsA = self.locations()
        random.shuffle(locationsA)
        locationsA = locationsA
        for A, locationA in locationsA:
            locationsB = self.locations()
            random.shuffle(locationsB)
            for B, locationB in locationsB:
                i += 1

                if ((A is self.original_start and B is self.original_end) or
                    (B is self.original_start and A is self.original_end)
                        or (not self.refine and self.results[B][A]
                            not in (TSPMaze.EMPTY, TSPMaze.FAILED))
                        or (A is B)):
                    continue

                print 'Route #%2d (%2d, %2d) -> #%2d (%2d, %2d)' % (
                    (A, ) + locationA + (B, ) + locationB),

                start_time = time.time()
                ant = self.find_path(maze, locationA, locationB)
                elapsed = time.time() - start_time

                elapsed_list.append(elapsed)

                if ant is None:
                    self.set_result(A, B, TSPMaze.FAILED)
                    print RED, '\n!!', ENDC, ' not found in %0.2fs, run again to try again. ' % elapsed
                    failes += 1
                else:
                    self.set_result(A, B, ant)

                    print 'done (length: %d) in %0.2fs' % (len(
                        ant.trail), elapsed)

                if i % self.count() == 1:
                    print '  running %0.2fs now, average time: %0.2fs (TSP matrix done in: %0.0fs)' % (
                        time.time() - overall_start_time, mean(elapsed_list),
                        total_paths * mean(elapsed_list))

        return failes
def parameter_compare(maze_name, vary_parameter, compute=True):
    filename = '../data/%s-maze.txt' % maze_name
    outputfile = 'compare-graphs/%s/param-compare-%%s.pickle' % maze_name

    iterations = 10

    if compute:
        start_time = time.time()
        print 'Running ACO on %s maze %d times for each %d different values of %s: ' % (
            maze_name,
            iterations,
            len(parameters[vary_parameter]),
            vary_parameter
        )
        print parameters[vary_parameter]

        results = []
        for param in parameters[vary_parameter]:
            print '%s = %s: ' % (vary_parameter, str(param)),

            param_result = dict(
                best_trail=[],
                best_at_iteration=[],
                running_time=[]
            )
            for i in range(iterations):
                settings = default_settings.copy()
                settings.update({
                    vary_parameter: param
                })
                aco_start = time.time()
                maze = Maze.from_file(filename)
                aco = ACO(maze=maze, **settings)
                best_ant = aco.run()
                print len(best_ant.trail),

                param_result['best_trail'].append(len(best_ant.trail))
                param_result['best_at_iteration'].append(aco.get_first_iteration_with_best_trail())
                param_result['running_time'].append(time.time() - aco_start)

            results.append(param_result)
            print

        print '%d runs done in %0.2fs' % (
            iterations * len(parameters[vary_parameter]),
            start_time - time.time()
        )
        with open(outputfile % vary_parameter, 'w') as f:
            pickle.dump(results, f)
    else:
        results = pickle.load(open(outputfile % vary_parameter))

    for metric, labely in (
            ('best_trail', 'Trail length of best trail'),
            ('best_at_iteration', 'First iteration best occurs'),
            ('running_time', 'Running time of ACO'), ):

        make_boxplot(
            basename='compare-graphs/' + maze_name + '/aco-compare-' + vary_parameter + '-' + metric,
            data=[x[metric] for x in results],
            plot_title='ACO on maze %s (%d times)' % (maze_name, iterations),
            xvalues=parameters[vary_parameter],
            labelx='Values for %s' % vary_parameter,
            labely=labely
        )

    return results
        for i, j in itertools.combinations(range(self.n), 2):
            delta = 0
            for k in range(self.n):
                if k == i or k == j:
                    continue
                delta += self.dist[i, k] * (self.flow[d[j], d[k]] - self.flow[d[i], d[k]])
                delta += self.dist[j, k] * (self.flow[d[i], d[k]] - self.flow[d[j], d[k]])
            if delta < 0:
                d[i], d[j] = d[j], d[i]

        return set(d.items())

    def score(self, sol):
        perm = dict(sol)
        total = 0
        for i in range(self.n):
            for j in range(self.n):
                total += self.dist[i, j] * self.flow[perm[i], perm[j]]
        return total

    def approximate(self):
        return np.amax(self.dist) * np.amax(self.flow) * self.n * self.n


if __name__ == "__main__":
    p = MyProblem('els19.dat.pkl')
    a = ACO(p, rho=0.01, q0=0.1, xi=0)
    assert p.score(list(enumerate(i-1 for i in [9, 10, 7, 18, 14, 19, 13, 17, 6, 11, 4, 5, 12, 8, 15, 16, 1, 2, 3]))) == 17212548
    print('hi')
    print(sorted(a.optimize(100000)[0]))