Beispiel #1
0
def all_test_tsp_run():
    G = all_test_tsp()
    no_of_alg = list_of_alg().__len__()
    paths = [None] * G.__len__() * no_of_alg
    dists = [None] * G.__len__() * no_of_alg
    i = 0
    for graph in G:
        for alg in list_of_alg():
            if alg == 'min_max':
                colony = AntColony(graph=graph,
                                   ants_total=50,
                                   iter=1,
                                   alpha=1,
                                   beta=5,
                                   rho=0.4,
                                   unique_visit=True,
                                   goal='TSP',
                                   min_pher=0.0001,
                                   max_pher=10,
                                   algo=alg)
            else:
                colony = AntColony(graph=graph,
                                   ants_total=50,
                                   iter=1,
                                   alpha=1,
                                   beta=5,
                                   rho=0.4,
                                   unique_visit=True,
                                   goal='TSP',
                                   algo=alg)

            paths[i], dists[i], _ = colony.find()
            i += 1

    return paths, dists
Beispiel #2
0
def run_alg(args):
    (graph, ants_total, iter, alpha, beta, rho, q0, rho_local, del_min,
     del_max, tau0, algo, outFname) = args
    # G = romanian_graph()
    G = read_graph_from_file(delimiter=' ',
                             file_xy_mat='data/coordinates/' + graph + '.txt')

    colony = AntColony(graph=G,
                       ants_total=ants_total,
                       iter=iter,
                       alpha=alpha,
                       beta=beta,
                       rho=rho,
                       init_pher=tau0,
                       q0=q0,
                       min_pher=del_min,
                       max_pher=del_max,
                       unique_visit=True,
                       goal='TSP',
                       algo=algo,
                       rho_local=rho_local)
    # colony = AntColony(G, 30, 2, 5, 1, 0.2, True, 'TSP', min_pher=0.001, max_pher=10, algo='min_max')
    # colony = AntColony(G, 20, 1000, 3, 1, 0.4, True, 'PathMin', 4, 10)
    # add_info = 'multi' + '_graph-' + graph
    # memory_filename = 'data/mem_' + add_info + '_algo-' + colony.algo + '_ants-' \
    #     + str(colony.ants_total) + '_iter-' + str(colony.iter) \
    #     + '_alpha-' + str(colony.alpha) + '_beta-' + str(colony.beta) \
    #     + '_rho-' + str(colony.rho) + '_q0-' + str(colony.q0) + '_rho_loc-' \
    #     + str(colony.rho_local) + '.npy'
    shortest_path, shortest_dist, memory = colony.find(path=outFname + 'npy')
Beispiel #3
0
def collect_results(graph_number):
    ANTS_NUM = [50, 100, 200, 1000]
    IT_NUM = [100]
    SIGMA = [0.1, 0.3, 0.5, 0.7, 0.9]
    ALPHA = [0.1, 0.5, 1.0, 2.0]
    BETA = [0.1, 0.5, 1.0, 2.0]
    K_ANTS = [0, 1, 5, 10, 15]

    #ANTS_NUM = [50]
    #IT_NUM = [100]
    #SIGMA = [0.9]
    #ALPHA = [1.0, 2.0]
    #BETA = [1.0, 2.0]
    #K_ANTS = [5]

    # pool = ThreadPool(4)
    for ants_num, it_num, sigma, alpha, beta, k_ants in list(
        itertools.product(ANTS_NUM,
                          IT_NUM,
                          SIGMA,
                          ALPHA,
                          BETA,
                          K_ANTS)):
                    aco = AntColony(DATASET_NAMES[graph_number],
                                    ants_num=ants_num,
                                    it_num=it_num,
                                    sigma=sigma,
                                    alpha=alpha,
                                    beta=beta,
                                    k_ants=k_ants)
                    if aco.already_exists:
                        continue
                    aco.flux_colony()
Beispiel #4
0
def ant_traverse(num_nodes, cost_mat, num_iterations, cities, beta, alpha, Q0,
                 Q, rho):

    if num_nodes < len(cost_mat):
        cost_mat = cost_mat[0:num_nodes]
        for i in range(0, num_nodes):
            cost_mat[i] = cost_mat[i][0:num_nodes]

    try:
        graph = AntGraph(num_nodes, cost_mat)
        best_path_vec = None
        best_path_cost = sys.maxsize

        graph.reset_tau()
        ant_colony = AntColony(graph, num_nodes, num_iterations)

        ant_colony.start(beta, alpha, Q0, Q, rho)

        if ant_colony.best_path_cost < best_path_cost:
            best_path_vec = ant_colony.best_path_vec
            best_path_cost = ant_colony.best_path_cost

        print("\n------------------------------------------------------------")
        print("                     Results                                ")
        print("------------------------------------------------------------")
        print("\nBest path = %s" % (best_path_vec, ))
        coordinates = [cities[node] for node in best_path_vec]
        coordinates_as_tuples = list(zip(coordinates, range(len(coordinates))))
        # for node in best_path_vec:
        #     print(cities[node])
        #     geolocator = Nominatim()
        #     location = geolocator.reverse("{0}, {1}".format(cities[node][0], cities[node][1]))
        #     print(location.address)

        edges_len = []
        for i in range(len(best_path_vec) - 1):
            edges_len.append(cost_mat[best_path_vec[i]][best_path_vec[i + 1]])
        last_edge_len = cost_mat[best_path_vec[0]][best_path_vec[-1]]
        edges_len.append(last_edge_len)

    except Exception as e:
        print("exception: " + str(e))
        best_path_cost = sys.maxsize
        edges_len = []
        coordinates = []
        traceback.print_exc()

    return best_path_cost, coordinates_as_tuples, edges_len
Beispiel #5
0
    def findSolution(self):
        try:
            graph = AntGraph(self.num_nodes, self.cost_mat, self.color_mat)
            best_path_vec = None
            best_path_cost = sys.maxint
            for i in range(0, self.num_repetitions):
                graph.reset_tau()
                ant_colony = AntColony(graph, self.num_ants,
                                       self.num_iterations)
                ant_colony.start()
                if ant_colony.best_path_cost < best_path_cost:
                    best_path_vec = ant_colony.best_path_vec
                    best_path_cost = ant_colony.best_path_cost
            return best_path_vec

        except Exception, e:
            print "exception: " + str(e)
            traceback.print_exc()
Beispiel #6
0
def test_total_run_basic(simple_cube):
    """Start at 1 to make life easier"""
    colony = AntColony(graph=simple_cube,
                       ants_total=4,
                       iter=5,
                       alpha=1,
                       beta=5,
                       rho=0.4,
                       start_node=1,
                       unique_visit=True,
                       goal='TSP',
                       algo='ant_system')

    # colony =  AntColony(simple_cube, 4, 5, 1, 1, 1, True, 'TSP', start_node=1, algo='ant_system')
    path_best, dist, _ = colony.find()

    path_best = np.array(path_best)
    assert ((path_best == [1, 2, 3, 4, 1]).all() or (path_best == [1, 4, 3, 2, 1]).all()) and dist == 4,\
        'Best path not found.'
Beispiel #7
0
    def make_colony(self, parent_genes):
        '''
            function to initialize a colony from a set of parent genes.

            @param parent_genes (dict): dictionary like init_params

            @return antcolony object
            @return genes (dict)
            @return id (current count)
        '''

        # variation
        genes = deepcopy(parent_genes)
        for key in parent_genes.keys():
            if parent_genes[key] is not None:
                factor = np.random.uniform(1 - self.variation,
                                           1 + self.variation)
                genes[key] *= factor

        # initialization
        child = AntColony(graph=self.graph,
                          ants_total=self.num_ants,
                          iter=self.iter,
                          alpha=genes['alpha'],
                          beta=genes['beta'],
                          rho=genes['rho'],
                          unique_visit=self.unique_visit,
                          goal=self.goal,
                          start_node=self.start,
                          end_node=self.end,
                          init_pher=genes['init_pher'],
                          min_pher=genes['min_pher'],
                          max_pher=genes['max_pher'],
                          q0=genes['q0'],
                          tau=genes['tau'],
                          algo=self.algo)
        count = self.count
        # print('colony', self.count, 'is born')
        self.count += 1

        return child, genes, count
    cost_mat = stuff[1]

    if num_nodes < len(cost_mat):
        cost_mat = cost_mat[0:num_nodes]
        for i in range(0, num_nodes):
            cost_mat[i] = cost_mat[i][0:num_nodes]

    print (cost_mat)

    try:
        graph = AntGraph(num_nodes, cost_mat)
        best_path_vec = None
        best_path_cost = sys.maxsize
        for i in range(0, num_repetitions):
            graph.reset_tau()
            ant_colony = AntColony(graph, num_ants, num_iterations)
            ant_colony.start()
            if ant_colony.best_path_cost < best_path_cost:
                best_path_vec = ant_colony.best_path_vec
                best_path_cost = ant_colony.best_path_cost

        print ("\n------------------------------------------------------------")
        print ("                     Results                                ")
        print ("------------------------------------------------------------")
        print ("\nBest path = %s" % (best_path_vec,))
        for node in best_path_vec:
            print (cities[node] + " ",)
        print ("\nBest path cost = %s\n" % (best_path_cost,))
    
    except Exception as e:
        print ("exception: " + str(e))
Beispiel #9
0
for row in range(1, ws.nrows):
    y_data.append(ws.cell_value(row, ws.ncols - 1))

if num_nodes < len(cost_mat):
    cost_mat = cost_mat[0:num_nodes]
    for i in range(0, num_nodes):
        cost_mat[i] = cost_mat[i][0:num_nodes]

try:
    graph = AntGraph(num_nodes, cost_mat)
    best_path_vec = None
    best_path_cost = sys.maxsize
    num_repetitions = 1
    for i in range(0, num_repetitions):
        graph.reset_tau()
        ant_colony = AntColony(graph, num_ants, num_iterations)
        ant_colony.start()
        if ant_colony.best_path_cost < best_path_cost:
            best_path_vec = ant_colony.best_path_vec
            best_path_cost = ant_colony.best_path_cost
    print("\n                     Результати                                ")
    print("Вектор найкращого шляху = %s" % (best_path_vec, ))
    for node in best_path_vec:
        print(str(cities[node]) + " ", )
        graph_x_cords.append(float(x_data[node]))
        graph_y_cords.append(float(y_data[node]))

    print("Довжина найкращого шляху = %s\n" % (best_path_cost, ))

    graph_x_cords.append(graph_x_cords[0])
    graph_y_cords.append(graph_y_cords[0])
Beispiel #10
0
        print("tour cost is", g.tour_cost(tour))
        """
###########################################
## Ant colony
###########################################
        num_nodes = 10
        num_ants = 20
        num_iterations = 1
        num_repetitions = 1
        try:
            graph = AntGraph(numCity, distMatr)
            best_path_vec = None
            best_path_cost = sys.maxsize
            for i in range(0, num_repetitions):
                graph.reset_tau()
                ant_colony = AntColony(graph, num_ants, num_iterations, colorList)
                ant_colony.start(colorList)
                if ant_colony.best_path_cost < best_path_cost:
                    best_path_vec = ant_colony.best_path_vec
                    best_path_cost = ant_colony.best_path_cost

            best_path_vec = [x+1 for x in best_path_vec]
            
            print("-----------AntColony Result-------------")
            print "best path = ", str(best_path_vec)
            print "best path cost is", str(best_path_cost)
        
        except Exception as e:
            print "exception: ", str(e)
            traceback.print_exc()
    fout.close()
Beispiel #11
0
        8: rho
        9: init_pher
        10: q0
        11: rho_local
        12: unique_visit
        '''

        G = read_graph_from_file(file_xy_mat='data/' + sys.argv[1], delimiter=' ')
        memory_filename = 'data/history/' + sys.argv[2] + '.npy'

        colony = AntColony(graph=G,
                           ants_total=int(sys.argv[5]),
                           iter=int(sys.argv[6]),
                           alpha=1,
                           beta=float(sys.argv[7]),
                           rho=float(sys.argv[8]),
                           init_pher=float(sys.argv[9]),
                           q0=float(sys.argv[10]),
                           unique_visit=bool(sys.argv[12]),
                           goal=sys.argv[4],
                           algo=sys.argv[3],
                           rho_local=float(sys.argv[11]))

        shortest_path, shortest_dist, memory = colony.find(path=memory_filename)

    else:
        '''If not enough arguments were passed, run this predefined example.
        '''
        G = read_graph_from_file(file_xy_mat='data/coordinates/us48_xy.txt')

        colony = AntColony(graph=G,
                           ants_total=10,
Beispiel #12
0
        cost_mat = d 

        print "\n"
        print "\n************************************************************"
        print "\nTest # %s" % t 
#        print d
        print "\nSize of Input: %s" % N


        try:
            graph = AntGraph(N, cost_mat)
            best_path_vec = None
            best_path_cost = sys.maxint
            for i in range(0, num_repetitions):
                graph.reset_tau()
                ant_colony = AntColony(graph, num_ants, num_iterations, c)
#                print "HANG AFTER ANYCOLONY"

                ant_colony.start(c)
#                print "HANG AFTER START?"
                if ant_colony.best_path_cost < best_path_cost:
                    best_path_vec = ant_colony.best_path_vec
                    best_path_cost = ant_colony.best_path_cost


            best_path_vec = [x+1 for x in best_path_vec]

            print "\n------------------------------------------------------------"
            print "                     Results                                "
            print "------------------------------------------------------------"
            print "\nBest path = %s" % (best_path_vec,)
import numpy as np
import pandas as pd

from antcolony import AntColony

# read csv and prepare to be a normal numpy distance matrix
distances = pd.read_csv('europe.csv', delimiter=',')
distances = distances.replace('-', np.inf)  # diagonal should be infinity
distances = distances.apply(
    pd.to_numeric, errors='coerce')  # convert strings in dataframe to floats
distances = distances.values[:,
                             1:]  # take only the columns and rows with values, i.e. remove city name column

ant_colony = AntColony(distances,
                       nr_ants=20,
                       nr_best=10,
                       nr_iterations=500,
                       decay=0.95,
                       alpha=1,
                       beta=1,
                       phero_min=0.1,
                       phero_max=1,
                       nr_procs=6)
shortest_path = ant_colony.run()
print(f"shortest_path: {shortest_path}")
Beispiel #14
0
from abstract_tsp_solver import AbstractTSPSolver
from antcolony import AntColony
from christofides import Christofides
from furthest_neighbor import FurthestNeighbor
from nearest_neighbor import NearstNeighbor

algorithms = {
    algo.name: algo
    for algo in
    [Christofides(),
     AntColony(),
     NearstNeighbor(),
     FurthestNeighbor()]
}
Beispiel #15
0
    cost_matrix = []
    rank = len(src.cities)
    for i in range(rank):
        row = []
        for j in range(rank):
            row.append(distance(src.cities[i], src.cities[j]))
        cost_matrix.append(row)

    du_lieu = cost_matrix

    # xay dung mang
    so_dinh = len(du_lieu)
    dothi = AntGraph(so_dinh, du_lieu)
    duong_di_tot_nhat = None
    do_dai_tot_nhat = sys.maxsize
    for i in range(0, so_lan_chay):
        dothi.reset_tau()
        ant_colony = AntColony(dothi, so_kien, so_lan_lap_toi_da)
        ant_colony.start()
        if ant_colony.do_dai_tot_nhat < do_dai_tot_nhat:
            duong_di_tot_nhat = ant_colony.duong_di_tot_nhat
            do_dai_tot_nhat = ant_colony.do_dai_tot_nhat

    print("\n------------------------------------------------------------")
    print("                     Kết quả                                ")
    print("------------------------------------------------------------")
    print("\nĐường đi tốt nhất = %s" % (duong_di_tot_nhat,))
    #for node in duong_di_tot_nhat:
    #   print(cac_dinh[node] + " ", )
    print("\nĐộ dài tốt nhất = %s\n" % (do_dai_tot_nhat,))
def main(argv):
    """
    Program to show a possible approach to the Travelling Salesman Problem using Ant Colony Optimization

    To use the anttsp.py from the command line:
    Useage: python anttsp.py <cities> <city data file> <output file>

    :param argv - should contain 3 elements, a number of cities to visit, a city data file and a target output

    The number of cities should be a non-negative integer equal to or less than the number of cities in the data file.
    The function will use the first n cities in the data file.

    The data file should be a pickled data file of the form
    [[cityA,cityB,...cityN], [[distanceAA, distanceAB..distanceAN],[distanceBA, distanceBB,.. distanceBN]]]

    This is a list composed of a list of city names and a list of lists represents the NxN array of distances between
    cities.

    The output file should be a target space to write the output information to, this will be a pickled form of:
    [[list of graph node indices], [list of node names], path cost]
    """
    # default
    num_nodes = 10

    if len(argv) >= 3 and argv[0]:
        num_nodes = int(argv[0])

    if num_nodes <= 10:
        num_ants = 20
        num_iterations = 12
        num_repetitions = 1
    else:
        num_ants = 28
        num_iterations = 20
        num_repetitions = 1

    stuff = pickle.load(open(argv[1], "r"))
    cities = stuff[0]
    cost_mat = stuff[1]

    if num_nodes < len(cost_mat):
        cost_mat = cost_mat[0:num_nodes]
        for i in range(0, num_nodes):
            cost_mat[i] = cost_mat[i][0:num_nodes]

    # print cost_mat

    try:
        graph = AntGraph(num_nodes, cost_mat)
        best_path_vec = None
        best_path_cost = sys.maxint
        for i in range(0, num_repetitions):
            print "Repetition %s" % i
            graph.reset_tau()
            ant_colony = AntColony(graph, num_ants, num_iterations)
            print "Colony Started"
            ant_colony.start()
            if ant_colony.best_path_cost < best_path_cost:
                print "Colony Path"
                best_path_vec = ant_colony.best_path_vec
                best_path_cost = ant_colony.best_path_cost

        print "\n------------------------------------------------------------"
        print "                     Results                                "
        print "------------------------------------------------------------"
        print "\nBest path = %s" % (best_path_vec,)
        city_vec = []
        for node in best_path_vec:
            print cities[node] + " ",
            city_vec.append(cities[node])
        print "\nBest path cost = %s\n" % (best_path_cost,)
        results = [best_path_vec, city_vec, best_path_cost]
        pickle.dump(results, open(argv[2], 'w+'))
    except Exception, e:
        print "exception: " + str(e)
        traceback.print_exc()