Ejemplo n.º 1
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)
Ejemplo n.º 2
0
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)
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)
Ejemplo n.º 4
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)
Ejemplo n.º 5
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
Ejemplo n.º 6
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)
Ejemplo n.º 7
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)
Ejemplo n.º 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')
Ejemplo n.º 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
Ejemplo n.º 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))
Ejemplo n.º 11
0
Archivo: main.py Proyecto: 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))
Ejemplo n.º 12
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)
Ejemplo n.º 13
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))
Ejemplo n.º 14
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)
Ejemplo n.º 15
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)
Ejemplo n.º 16
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
Ejemplo n.º 17
0
def main():
    cities = []
    points = []
    with open('./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])))
    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)

    ants = 10
    iterMax = 1000
    alpha = 1.0
    beta = 10.0
    rho = 0.6
    aco = ACO(ants, iterMax, alpha, beta, rho, 10, 2)
    graph = Graph(cost_matrix, rank)
    path, cost = aco.solve(graph)

    print(
        "------------------------------------------------------------------------------"
    )

    print(
        f'ants: {ants}, alpha: {alpha}, beta: {beta}, evaporacion (rho): {rho} '
    )
    print("Best result:")
    print('cost: {}, path: {}'.format(round(cost, 0), path))
    plot(points, path)

    print(
        "------------------------------------------------------------------------------"
    )

    ants = 5
    iterMax = 10
    alpha = 1.0
    beta = 2.0
    rho = 0.3
    aco = ACO(ants, iterMax, alpha, beta, rho, 10, 2)
    graph = Graph(cost_matrix, rank)
    path, cost = aco.solve(graph)

    print(
        "------------------------------------------------------------------------------"
    )

    print(
        f'ants: {ants}, alpha: {alpha}, beta: {beta}, evaporacion (rho): {rho} '
    )
    print("Best result:")
    print('cost: {}, path: {}'.format(round(cost, 0), path))
    plot(points, path)

    print(
        "------------------------------------------------------------------------------"
    )

    ants = 10
    iterMax = 10
    alpha = 2.0
    beta = 0.5
    rho = 0.7
    aco = ACO(ants, iterMax, alpha, beta, rho, 10, 2)
    graph = Graph(cost_matrix, rank)
    path, cost = aco.solve(graph)

    print(
        "------------------------------------------------------------------------------"
    )

    print(
        f'ants: {ants}, alpha: {alpha}, beta: {beta}, evaporacion (rho): {rho} '
    )
    print("Best result:")
    print('cost: {}, path: {}'.format(round(cost, 0), path))
    plot(points, path)

    print(
        "------------------------------------------------------------------------------"
    )

    ants = 20
    iterMax = 10
    alpha = 1.0
    beta = 15.0
    rho = 0.7
    aco = ACO(ants, iterMax, alpha, beta, rho, 10, 2)
    graph = Graph(cost_matrix, rank)
    path, cost = aco.solve(graph)

    print(
        "------------------------------------------------------------------------------"
    )

    print(
        f'ants: {ants}, alpha: {alpha}, beta: {beta}, evaporacion (rho): {rho} '
    )
    print("Best result:")
    print('cost: {}, path: {}'.format(round(cost, 0), path))
    plot(points, path)

    print(
        "------------------------------------------------------------------------------"
    )
Ejemplo n.º 18
0
def main():
    cities = []
    points = []
    """
    :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
    """

    num_ants = 30
    generations = 100
    alpha = 1.0
    beta = 9
    rho = 2
    q = 0.2
    strategy = 2

    with open('./data/berlin.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(num_ants, generations, alpha, beta, rho, q, strategy)
    graph = Graph(cost_matrix, rank)
    #path, cost, all_costs, all_paths, all_best_costs, all_best_paths, all_gen_best_costs = aco.solve(graph)
    path, cost, all_converge, total_converge = aco.solve(graph)
    print('cost: {}, path: {}'.format(cost, path))

    f, (ax1, ax2) = plt.subplots(1, 2, sharey=True)

    ax1.plot(range(num_ants),
             np.mean(all_converge, axis=0),
             'r-',
             alpha=1,
             label="mean")

    for i in range(generations):
        ax1.plot(range(len(all_converge[i])),
                 all_converge[i],
                 '#82848c',
                 alpha=0.3)

    ax1.set_title('Generations')
    ax2.set_title('Convergence (lowest cost found)')

    ax1.set(xlabel="Ants", ylabel="Cost (Distance)")
    ax2.set(xlabel="Ants * Generations", )

    ax2.plot(range(len(total_converge)), total_converge)

    #plt.xlabel('Ants')
    #plt.ylabel('Cost (Distance)')
    #plt.legend(['mean','iteration'])
    plt.show()
Ejemplo n.º 19
0
def calcminmax(nodes):
    min_len = None
    max_len = 0
    for ns in itertools.permutations(nodes[1:]):
        l = length([nodes[0]] + list(ns))
        if min_len is None:
            min_len = l
        if l < min_len:
            min_len = l
        if l > max_len:
            max_len = l

    return min_len, max_len


graph = Graph()
nodes = [
    City(random.randint(0, 100), random.randint(0, 100)) for i in range(6)
]

for from_node, to_node in itertools.combinations(nodes, 2):
    graph.add_node(from_node)
    graph.add_node(to_node)

    e = Edge(from_node, to_node, pheromone=random.random())
    graph.add_edge(e)

min_len, max_len = calcminmax(nodes)
print('Min Length: {}'.format(min_len))
print('Max Length: {}'.format(max_len))
Ejemplo n.º 20
0
    row = []
    for j in range(rank):
        row.append(time_cost_between_points(locations[i], locations[j], 1, 0))
    cost_matrix.append(row)

# Pass in user arguments
aco = ACO(ant_count=args.ant_count,
          generations=args.g,
          alpha=args.alpha,
          beta=args.beta,
          rho=args.rho,
          q=args.q,
          strategy=2)

# Build graph with cost matrix and number of points
graph = Graph(cost_matrix, rank)
# Get results from ant colony, specify whether verbose output
best_path, cost, avg_costs, best_costs = aco.solve(graph, args.verbose)

# Print out and plot final solution
print('Final cost: {} minutes, path: {}'.format(cost, best_path))

# Output the mean and standard deviantion of min costs per generation
print("Min cost mean:", np.mean(best_costs))
print("Min cost standard deviation:", np.std(best_costs))

# Print out final addresses in solution
if args.verbose:
    print("Final path addresses:")
    try:
        addresses = []
Ejemplo n.º 21
0
def main():
    if len(sys.argv) != 2:
        print("Wrong!")
        print("Pass number of iterations as argument!")
        return

    num_itr = int(sys.argv[1])
    cities = []
    points = []
    cost_matrix = []
    with open('./data/gr17.txt') as f:  # importing the dataset file
        for line in f.readlines(
        ):  # reading matrix from the dataset file and putting into cost_matrix
            city = line.split(' ')
            row = []
            for i in city:
                row.append(float(i))
            cost_matrix.append(row)

    rank = len(row)

    print('No. of cities:', rank)
    #print(rank)
    print("\nCost Matrix:")
    for i in range(rank):
        print(cost_matrix[i])  # printing the cost matrix given in the dataset

    alpha = []
    beta = []
    rho = []

    #for varying alpha
    with open('./input/alpha.txt') as f1:
        for line in f1.readlines():
            a = line.split(' ')
            for i in range(len(a)):
                alpha.append(float(a[i]))
    print(alpha)

    #for varying beta
    with open('./input/beta.txt') as f1:
        for line in f1.readlines():
            a = line.split(' ')
            for i in range(len(a)):
                beta.append(float(a[i]))
    print(beta)

    #for varying rho
    with open('./input/rho.txt') as f1:
        for line in f1.readlines():
            a = line.split(' ')
            for i in range(len(a)):
                rho.append(float(a[i]))
    print(rho)

    total_cost1 = [0.0 for j in range(len(alpha))]
    total_cost2 = [0.0 for j in range(len(beta))]
    total_cost3 = [0.0 for j in range(len(rho))]

    print('\n\nNumber of iterations: ', num_itr)

    # for varying alpha
    print('Keeping  β=1 and ρ=0.1 and varying α\n')
    for j in range(len(alpha)):
        aco = ACO(rank, num_itr, alpha[j], 1, 0.1, 10, 2)
        graph = Graph(cost_matrix, rank)
        path, cost = aco.solve(graph)
        total_cost1[j] = cost
        print('α = {} , Total Cost = {}'.format(alpha[j], total_cost1[j]))
        print('Path: ', path)
    print('\n')

    # for varying beta
    print('Keeping  α = 0.5 and ρ=0.1 and varying β\n')
    for j in range(len(beta)):
        aco = ACO(rank, num_itr, 0.5, beta[j], 0.1, 10, 2)
        graph = Graph(cost_matrix, rank)
        path, cost = aco.solve(graph)
        total_cost2[j] = cost
        print('β = {} , Total Cost = {}'.format(beta[j], total_cost2[j]))
        print('Path: ', path)
    print('\n')

    # β=1, ρ=0.1 and varying values of  α
    #for varying rho
    print('Keeping  α = 0.5 and β=1 and varying ρ\n')
    for j in range(len(rho)):
        aco = ACO(rank, num_itr, 0.5, 1, rho[j], 10, 2)
        graph = Graph(cost_matrix, rank)
        path, cost = aco.solve(graph)
        total_cost3[j] = cost
        print('ρ= {} , Total Cost = {}'.format(rho[j], total_cost3[j]))
        print('Path: ', path)
    print('\n')
Ejemplo n.º 22
0
from aco import ACO, Graph
from plot_graphs import plot_path, plot_boxplot, plot_convergence_graphs

SIMULATIONS = 30

with open("data/att48.txt", "r") as f:
    matrix_cities = []
    for line in f.readlines():
        _, pos1, pos2 = line.split(" ")
        matrix_cities.append([float(pos1), float(pos2)])

with open("data/att48_optimal_tour.txt", "r") as f:
    best_solution = [int(line) for line in f.readlines()]
best_solution = [i - 1 for i in best_solution]

graph = Graph(cities=matrix_cities)
optimal = ACO.calculate_tour_distance(graph, best_solution)

best_fitness = []
for _ in range(SIMULATIONS):
    aco = ACO(graph=graph, algorithm_type=1, rho_evaporation_rate=0.9)
    best_cost_list = aco.search()
    best_fitness.append(best_cost_list)
    print("Optimal: ", optimal)
    print("Found: ", ACO.calculate_tour_distance(graph, aco.best_solution))
print("ACO Min: ", np.array(best_fitness).min())

# plot_boxplot(best_fitness, "Boxplot ACO Average 30 Runs")
# average_best_fitness = np.sum(np.array(best_fitness), axis=0) / SIMULATIONS

# plot_path(graph.cities, aco.best_solution, "ACO Found Solution")