Beispiel #1
0
    def __init__(self, instance_name: str, file_type: str = '.tsp'):
        self.instance_name = instance_name

        if file_type == '.tsp':
            self.instance = tsplib95.load(Problem.files_path +
                                          self.instance_name + file_type)
            self.nx_graph = self.instance.get_graph()
            try:
                self.tour = tsplib95.load(Problem.files_path +
                                          self.instance_name +
                                          Problem.tour_files_suffix)
                self.opt_cost = self.instance.trace_tours(self.tour.tours)[0]
                self.opt_tour = self.tour.tours[0]
            except:
                self.tour = None
                self.opt_cost = None
                self.opt_tour = None
        elif file_type == '.graphml':
            self.instance = None
            self.tour = None
            self.nx_graph = nx.read_graphml(Problem.files_path +
                                            self.instance_name + file_type)
            self.opt_cost = 0
            self.opt_tour = []

        self.distance_matrix = nx.to_numpy_matrix(self.nx_graph)
        self.instance = None
        self.tour = None
        self.size = self.distance_matrix.shape[0]
        if self.instance_name == "brazil58":
            self.opt_cost = 25395
Beispiel #2
0
def main():
    problem_a: StandardProblem = tsplib95.load('data/kroa200.tsp')
    problem_b: StandardProblem = tsplib95.load('data/krob200.tsp')

    shutil.rmtree("./graphs/", ignore_errors=True)
    os.makedirs('graphs/')

    global_convexity_tests(problem_a, title="problem_a_node")
    global_convexity_tests(problem_a,
                           similarity_function=edge_similarity,
                           title="problem_a_edge")
    global_convexity_tests(problem_b, title="problem_b_node")
    global_convexity_tests(problem_b,
                           similarity_function=edge_similarity,
                           title="problem_b_edge")

    run_experiment_iterative_local_search(problem_a,
                                          ImprovedHybridEvolutionarySolver(),
                                          result_title="kroa200_ihe",
                                          experiment_count=_COUNT,
                                          max_time=20.777)

    run_experiment_iterative_local_search(problem_b,
                                          ImprovedHybridEvolutionarySolver(),
                                          result_title="krob200_ihe",
                                          experiment_count=_COUNT,
                                          max_time=20.205)
Beispiel #3
0
    def _create_training_data(self):
        datadir = self.datadir
        problems = []
        graphs = []
        tours = []
        cur_nodes = []
        adjacencies = []
        for filename in os.listdir(datadir):
            name, ext = os.path.splitext(filename)
            tourpath = f'{name}.opt.tour'

            if ext == '.tsp' and tourpath in os.listdir(datadir):
                problem = tsp.load(os.path.join(datadir, filename))

                if problem.type != 'TSP' or problem.edge_weight_type != 'EUC_2D' or problem.dimension < 20:
                    # Only using 2D symmetric graphs for TSP
                    # also no point in training if graph is so small (could always generate data elsewhere)
                    continue
                print(problem.name, problem.dimension)

                graph = []
                for i in range(1, problem.dimension + 1):
                    graph.append(problem.node_coords[i])

                adj = self.weighted_adj_from_pos(torch.tensor(graph))

                tour = tsp.load(os.path.join(datadir, tourpath))
                if np.array(tour.tours).shape[0] > 1:
                    print(tour.name)
                    breakpoint()

                opttour = np.array(tour.tours[0])
                for i in range(len(opttour)):
                    curtour = np.append(opttour[i:], opttour[:i])
                    curtour = curtour - 1  # adjust to 0 indexed numbering to match graph
                    curnode = curtour[0]
                    graphs.append(graph)
                    tours.append(curtour)
                    cur_nodes.append(curnode)
                    problems.append(problem.name)
                    adjacencies.append(adj)

                opttour = opttour[::-1]  # repeat for reversed tour
                for i in range(len(opttour)):
                    curtour = np.append(opttour[i:], opttour[:i])
                    curtour = curtour - 1  # adjust to 0 indexed numbering to match graph
                    curnode = curtour[0]
                    graphs.append(graph)
                    tours.append(curtour)
                    cur_nodes.append(curnode)
                    problems.append(problem.name)
                    adjacencies.append(adj)

        return np.array(problems), np.array(graphs), np.array(tours), np.array(
            cur_nodes), adjacencies
 def load_problem(self, problem_filename):
     """
     Load problem from file, as well as opt.tour if available
     """
     self.problem = tsp.load(problem_filename)
     CandidateSolution.set_problem(self.problem)
     self.optimum = None
     opt_tour = problem_filename[:-4] + ".opt.tour"
     try:
         self.optimum = CandidateSolution(tsp.load(opt_tour).tours[0])
     except FileNotFoundError as err:
         print("FileNotFoundError: {0}".format(err))
     else:
         pass
def main():
    problem_a: StandardProblem = tsplib95.load('data/kroa100.tsp')
    problem_b: StandardProblem = tsplib95.load('data/krob100.tsp')

    shutil.rmtree("./graphs/", ignore_errors=True)

    average_time = []
    average_time.append(
        run_experiment_local_search(problem_a, NodeSwapSteepSearch(),
                                    "kroa100_nsss", _EXPERIMENT_COUNT))

    average_time.append(
        run_experiment_local_search(problem_a, EdgeSwapSteepSearch(),
                                    "kroa100_esss", _EXPERIMENT_COUNT))

    average_time.append(
        run_experiment_local_search(problem_a,
                                    GreedyLocalSearch(use_node_swap=True),
                                    "kroa100_gls_ns", _EXPERIMENT_COUNT))

    average_time.append(
        run_experiment_local_search(problem_a,
                                    GreedyLocalSearch(use_edge_swap=True),
                                    "kroa100_gls_es", _EXPERIMENT_COUNT))

    average_time.append(
        run_experiment_local_search(problem_b, NodeSwapSteepSearch(),
                                    "krob100_nsss", _EXPERIMENT_COUNT))

    average_time.append(
        run_experiment_local_search(problem_b, EdgeSwapSteepSearch(),
                                    "krob100_esss", _EXPERIMENT_COUNT))

    average_time.append(
        run_experiment_local_search(problem_b,
                                    GreedyLocalSearch(use_node_swap=True),
                                    "krob100_gls_ns", _EXPERIMENT_COUNT))

    average_time.append(
        run_experiment_local_search(problem_b,
                                    GreedyLocalSearch(use_edge_swap=True),
                                    "krob100_gls_es", _EXPERIMENT_COUNT))

    max_avg_time = max(average_time)
    print(f"Max average time : {round(max_avg_time * 1000.0)}")
    print()
    run_experiment_local_search(problem_a, RandomSearch(max_avg_time),
                                "kroa100_rs", _EXPERIMENT_COUNT)
    run_experiment_local_search(problem_b, RandomSearch(max_avg_time),
                                "krob100_rs", _EXPERIMENT_COUNT)
def main():
    problem_a: StandardProblem = tsplib95.load('data/kroa200.tsp')
    problem_b: StandardProblem = tsplib95.load('data/krob200.tsp')

    shutil.rmtree("./graphs/", ignore_errors=True)

    run_experiment_iterative_local_search(problem_a,
                                          HybridEvolutionarySolver(),
                                          "kroa200_he", _EXPERIMENT_COUNT,
                                          20.777)

    run_experiment_iterative_local_search(problem_b,
                                          HybridEvolutionarySolver(),
                                          "krob200_he", _EXPERIMENT_COUNT,
                                          20.205)
Beispiel #7
0
def christofides(path):
    problem = tsplib95.load(path)
    G = problem.get_graph()
    preproc(G)
    print("preproc done")

    T = kruskal(G)

    print("kruskal done")

    O = oddsubgraph(T, G)

    print("oddsubgraph done")

    M = matching(O)

    print("matching done")

    H = nx.MultiGraph()
    H.add_edges_from(T.edges)
    H.add_edges_from(M.edges)

    eulerkreis = get_euler_kreis(H)

    print("eulerkreis found")

    hamiltonkreis = get_hamilton_kreis(eulerkreis)

    print("hamiltonkreis found")

    return weight(hamiltonian, G)
Beispiel #8
0
 def load_problem(self, filename):
     problem = tsplib95.load(filename)
     coord = problem.as_name_dict().get('node_coords')
     self._labels = list(coord.keys())
     self._coordinates = list(coord.values())
     self._distance_matrix = distance_matrix(self._coordinates,
                                             tsplib95.distances.euclidean)
Beispiel #9
0
def tsplib_distance_matrix(tsplib_file: str) -> np.ndarray:
    """Distance matrix from a TSPLIB file

    Parameters
    ----------
    tsplib_file
        A string with the complete path of the TSPLIB file (or just its name if
        it is the in current path)

    Returns
    -------
    distance_matrix
        A ND-array with the equivalent distance matrix of the input file

    Notes
    -----
    This function can handle any file supported by the `tsplib95` lib.
    """

    tsp_problem = tsplib95.load(tsplib_file)
    distance_matrix_flattened = np.array(
        [tsp_problem.get_weight(*edge) for edge in tsp_problem.get_edges()])
    distance_matrix = np.reshape(
        distance_matrix_flattened,
        (tsp_problem.dimension, tsp_problem.dimension),
    )

    # Some problems with EXPLICIT matrix have a large number in the distance
    # from a node to itself, which makes no sense for our problems. Thus,
    # always ensure a diagonal filled with zeros
    np.fill_diagonal(distance_matrix, 0)
    return distance_matrix
Beispiel #10
0
def main():
    cities = tsplib95.load(filePath)
    n_nodes = len(list(cities.get_nodes()))

    solutions = []
    best_round_value = (0, 0)

    for i in range(iterations):
        nodes = list(range(1, n_nodes + 1))
        random.shuffle(nodes)  #initial configuration|: sort all nodes randomly
        value = evaluation_function(nodes, cities, n_nodes)

        step = 0
        result = Solution(i)
        result_file.write("\t==============  Round: " + str(i + 1) +
                          "   ==============\n")
        start_t = time.time()
        iterations_t = []
        while (True):
            step += 1
            child_nodes, child_value = operate(nodes, cities, n_nodes)
            result_file.write("\t==== " + str(step) + " iteration -> f(n): " +
                              str(value) + "\n")
            if child_value <= value and step <= 300:
                value = child_value
                nodes = child_nodes
            else:
                result.set(nodes, value, step)
                solutions.append(result)  #print best results in file
                result_file.write("\n\t====   Best Solution -> " + str(step) +
                                  " iterations: f(n): " + str(value))
                result_file.write("\n\t====    - Elapsed time: " +
                                  str(sum(iterations_t)) +
                                  " |  time / iterations: " +
                                  str(sum(iterations_t) / step) + "\n\n\n")
                if best_round_value[0] == 0 or value < best_round_value[0]:
                    best_round_value = (value, i + 1)
                    with open(result_file.name[:-4] + "_nodes.txt",
                              'w',
                              encoding='utf-8') as f:  #print final node
                        f.write("\t=====  Best Solution found, in round: " +
                                str(i + 1) + "  -> f(n): " +
                                str(best_round_value[0]) + "   ######\n")
                        f.write("\t=====      - Elapsed time: " +
                                str(sum(iterations_t)) +
                                " |  time / iterations: " +
                                str(sum(iterations_t) / step) + "\n")
                        f.write("Order to visit cities: ")
                        for n in nodes:
                            f.write(str(n) + ", ")
                    if i == step - 1:
                        result_file.write("Best Solution: " +
                                          str(best_round_value[1]) +
                                          " round -> f(n): " +
                                          str(best_round_value[0]))
                break
            iterations_t.append(time.time() - start_t)
            start_t = time.time()
    result_file.close()
Beispiel #11
0
def main():
    problem_a: StandardProblem = tsplib95.load('data/kroa100.tsp')
    problem_b: StandardProblem = tsplib95.load('data/krob100.tsp')

    shutil.rmtree("graphs/", ignore_errors=True)

    run_experiment_constructive(problem_a, NearestNeighbourProblemSolver(),
                                "kroa100_nn", _EXPERIMENT_COUNT)
    run_experiment_constructive(problem_b, NearestNeighbourProblemSolver(),
                                "krob100_nn", _EXPERIMENT_COUNT)
    run_experiment_constructive(problem_a, GreedyCycleProblemSolver(),
                                "kroa100_gc", _EXPERIMENT_COUNT)
    run_experiment_constructive(problem_b, GreedyCycleProblemSolver(),
                                "krob100_gc", _EXPERIMENT_COUNT)
    run_experiment_constructive(problem_a, RegretCycleProblemSolver(),
                                "kroa100_rc", _EXPERIMENT_COUNT)
    run_experiment_constructive(problem_b, RegretCycleProblemSolver(),
                                "krob100_rc", _EXPERIMENT_COUNT)
def main():
    problem_a: StandardProblem = tsplib95.load('data/kroa200.tsp')
    problem_b: StandardProblem = tsplib95.load('data/krob200.tsp')

    shutil.rmtree("./graphs/", ignore_errors=True)

    run_experiment_local_search(problem_a, CandidateSteepSearch(),
                                "kroa200_css", _EXPERIMENT_COUNT)
    run_experiment_local_search(problem_b, CandidateSteepSearch(),
                                "krob200_css", _EXPERIMENT_COUNT)
    # This algorithm is implemented using wrong method
    # run_experiment_local_search(problem_a, ScoreSteepSearch(), "kroa200_sss", _EXPERIMENT_COUNT)
    # run_experiment_local_search(problem_b, ScoreSteepSearch(), "krob200_sss", _EXPERIMENT_COUNT)
    run_experiment_local_search(problem_a, EdgeSwapSteepSearch(),
                                "kroa200_ess", _EXPERIMENT_COUNT)
    run_experiment_local_search(problem_b, EdgeSwapSteepSearch(),
                                "krob200_ess", _EXPERIMENT_COUNT)
    run_experiment_constructive(problem_a, GreedyCycleProblemSolver(),
                                "kroa200_gc", _EXPERIMENT_COUNT)
    run_experiment_constructive(problem_b, GreedyCycleProblemSolver(),
                                "krob200_gc", _EXPERIMENT_COUNT)
Beispiel #13
0
def run(filename, is_plot=True):
    datapath = get_example_path()
    filepath = os.path.join(datapath, filename)
    problem = tsplib95.load(filepath)
    start = time()
    solver = TSPSolver.from_tspfile(filepath)
    solution = solver.solve()
    end = time()
    print("Time spent to solve {}s".format(end - start))
    print("Optimal value: ", solution.optimal_value)
    tour = solution.tour
    tour = [t + 1 for t in tour]
    plot(problem, tour)
Beispiel #14
0
def solve(solver='LKH', problem=None, **params):
    assert shutil.which(solver) is not None, f'{solver} not found.'

    valid_problem = problem is not None and isinstance(
        problem, tsplib.models.StandardProblem)
    assert ('problem_file' in params
            ) ^ valid_problem, 'Specify a TSPLIB95 problem object *or* a path.'
    if problem is not None:
        # hack for bug in tsplib
        if len(problem.depots) > 0:
            problem.depots = map(lambda x: f'{x}\n', problem.depots)

        prob_file = tempfile.NamedTemporaryFile(mode='w')
        problem.write(prob_file)
        prob_file.write('\n')
        prob_file.flush()
        params['problem_file'] = prob_file.name

    # need dimension of problem to parse solution
    problem = tsplib.load(params['problem_file'])

    if 'tour_file' not in params:
        tour_file = tempfile.NamedTemporaryFile(mode='w')
        params['tour_file'] = tour_file.name

    with tempfile.NamedTemporaryFile(mode='w') as par_file:
        par_file.write('SPECIAL\n')
        for k, v in params.items():
            par_file.write(f'{k.upper()} = {v}\n')
        par_file.flush()

        try:
            subprocess.check_output([solver, par_file.name],
                                    stderr=subprocess.STDOUT)
        except subprocess.CalledProcessError as e:
            raise Exception(e.output.decode())

        solution = tsplib.load(params['tour_file'])
        return solution.tours
Beispiel #15
0
def tsp_input():

    global problem
    global ARC
    global A
    global Weighted_ARC
    global Weighted_ARC_Sorted
    global input_nodes

    #Uploading of input data from following directory

    roots = Tk.Tk()
    roots.withdraw()
    roots.filename = filedialog.askopenfilename(
        initialdir="/",
        title="Select file",
        filetypes=(("tsp files", "*.tsp"), ("all files", "*.*")))

    problem = tsplib95.load(roots.filename)
    nodes = list(problem.get_nodes())
    input_nodes = len(nodes)

    coords = []
    ARC = []

    for i in nodes:
        coords.append(problem.node_coords[i])

    #Initialization of adjacency matrix
    A = np.ones((len(nodes), len(nodes)))
    A = np.triu(A)
    for i in nodes:
        A[i - 1][i - 1] = 0

    Weighted_ARC = []
    Weighted_ARC_Sorted = []

    for i in nodes:
        for j in nodes:
            if A[i - 1][j - 1] == 1:
                #Weight of each arc is the distance between the two extremal nodes
                x = ((coords[j - 1][0] - coords[i - 1][0])**2 +
                     (coords[j - 1][1] - coords[i - 1][1])**2)**(1 / 2)
                Weighted_ARC.append([i, j, x])
                ARC.append(tuple([i, j]))

    #Ordering of the arcs given by the weight
    Weighted_ARC_Sorted = Weighted_ARC.copy()
    Weighted_ARC_Sorted.sort(key=operator.itemgetter(2))

    return
 def generate_cities(self, filename):
     problem = tsplib95.load(filename)
     G = problem.get_graph()
     nodes = list(problem.get_nodes())
     outer_array = []
     for i, o in enumerate(nodes):
         for j, v in enumerate(nodes):
             if i == j:
                 outer_array.append([o - 1, v - 1, 0])
             else:
                 outer_array.append([o - 1, v - 1, G.edges[o, v]['weight']])
     self.edges = outer_array
     self.data = len(nodes)
     self.graph = problem
def _read_opt_sol(path: str):
    """
    Ler o arquivo com a solução ótima da tsplib
    :param path: path para o arquivo
    :return: set com as tuplas (i,j), onde i < j, correspondente as arestas da solução
    """
    tour = tsplib.load(path)
    tour = np.array(tour.tours[0]) - 1
    edges = set([(tour[0], tour[-1])])
    for i in range(1, len(tour)):
        edges.add((tour[i - 1],
                   tour[i]) if tour[i - 1] < tour[i] else (tour[i],
                                                           tour[i - 1]))
    return edges
def main():
    problem_a: StandardProblem = tsplib95.load('data/kroa200.tsp')
    problem_b: StandardProblem = tsplib95.load('data/krob200.tsp')

    shutil.rmtree("./graphs/", ignore_errors=True)

    avg_time_kroa = run_experiment_local_search(problem_a, MultipleStartLocalSearch(), "kroa200_msls",
                                                _EXPERIMENT_COUNT)
    avg_time_krob = run_experiment_local_search(problem_b, MultipleStartLocalSearch(), "krob200_msls",
                                                _EXPERIMENT_COUNT)

    run_experiment_iterative_local_search(problem_a, IteratedLocalSearch1(), "kroa200_ils1", _EXPERIMENT_COUNT,
                                          avg_time_kroa)
    run_experiment_iterative_local_search(problem_b, IteratedLocalSearch1(), "krob200_ils1", _EXPERIMENT_COUNT,
                                          avg_time_krob)

    run_experiment_iterative_local_search(problem_a, IteratedLocalSearch2(), "kroa200_ils2", _EXPERIMENT_COUNT,
                                          avg_time_kroa)
    run_experiment_iterative_local_search(problem_b, IteratedLocalSearch2(), "krob200_ils2", _EXPERIMENT_COUNT,
                                          avg_time_krob)
    run_experiment_iterative_local_search(problem_a, IteratedLocalSearch2a(), "kroa200_ils2a", _EXPERIMENT_COUNT,
                                          avg_time_kroa)
    run_experiment_iterative_local_search(problem_b, IteratedLocalSearch2a(), "krob200_ils2b", _EXPERIMENT_COUNT,
                                          avg_time_krob)
Beispiel #19
0
def load_problems(n):
    source = pathlib.Path.home(
    ) / 'Desktop/TSP/TSPLIB'  #hardcoded source, change later
    p_path = source / 'problems'
    s_path = source / 'solutions'

    problems = sorted(list(p_path.glob('*.tsp')))[:n]
    solutions = sorted(list(s_path.glob('*.opt.tour')))[:n]
    p_s = list(zip(problems, solutions))

    problems = {
        i.stem: {
            'n_nodes': int(re.split(r'\D', i.stem)[-1]),
            'problem': tsplib95.load(i),
            'opt_path': tsplib95.load(j).tours,
        }
        for (i, j) in p_s
    }

    for k, v in problems.items():
        pnodes = min(list(v['problem'].get_nodes()))
        snodes = min(v['opt_path'][0])

        if pnodes == 0 and snodes == 1:
            problems[k]['opt_sol'] = v['problem'].trace_tours(
                [[i - 1 for i in v['opt_path'][0]]])[0]
        elif (pnodes == 1 and snodes == 1) or (pnodes == 0 and snodes == 0):
            problems[k]['opt_sol'] = v['problem'].trace_tours(
                [v['opt_path'][0]])[0]
        elif pnodes == 1 and snodes == 0:
            problems[k]['opt_sol'] = v['problem'].trace_tours(
                [[i + 1 for i in v['opt_path'][0]]])[0]
        else:
            raise ValueError("Problem nodes have abnormal indices")

    return problems
def read_graphs(path_dir: str):
    """
    Ler todos  arquivo de instancias da tsplib no diretório
    :param path_dir: path para o diretório contendo arquivos de isntâncias da tsplib
    :return: dicionários {<nome da instância>: <nx graph>}
    """
    g = {}
    file_list = os.listdir(path_dir)
    for i, file_name in enumerate(file_list):
        g[os.path.basename(file_name).split('.')[0]] = tsplib.load(
            os.path.join(path_dir, file_name)).get_graph(normalize=True)
        progress(i + 1, len(file_list), 'Lendo instâncias', file_name)
        # break
    print()
    return g
Beispiel #21
0
def getDictFromTspFile(tspFile):
    p = tsp.load(tspFile)
    if not p.is_depictable:
        printf("Problem is not depictable!")

    # Amendments as we need the nodes lexographically ordered
    nnodes = len(list(p.get_nodes()))
    i = 0
    while nnodes > 1:
        nnodes = nnodes / 10
        i += 1
    formatString = f"{{:0{i}d}}"
    nodes = {
        formatString.format(value): p.node_coords[index + 1]
        for index, value in enumerate(p.get_nodes())
    }
    return nodes
Beispiel #22
0
    def reset(self):

        self.problem = tsplib95.load(self.tsp_name)
        self.node_position = self.problem.as_name_dict().get("node_coords")

        #Construct a Graph
        self.node_from = []
        self.node_to = []

        self.node_features = []

        for nodeID, position in self.node_position.items():

            adjacent_nodes = []
            node_feature = position + [0 for _ in range(12)]

            for _ in range(12):
                adjacent_nodeID = random.sample(
                    list(self.node_position.keys()), 1)[0]
                while adjacent_nodeID == nodeID:
                    adjacent_nodeID = random.sample(
                        list(self.node_position.keys()), 1)[0]

                adjacent_nodes.append(adjacent_nodeID)
            adjacent_nodes = sorted(adjacent_nodes)

            for i in range(12):
                self.node_from.append(nodeID - 1)
                self.node_to.append(adjacent_nodes[i] - 1)

            for i in range(12):
                node_feature[i + 2] = self.statistics[nodeID].get(i)

            self.node_features.append(node_feature)

        self.graph = dgl.DGLGraph((self.node_from, self.node_to))

        self.graph.ndata["h"] = np.float32(self.node_features)
        self.graph.edata["h"] = np.float32(
            np.random.randn(len(self.node_position) * 12, 5))

        #Randomly choose a starting point
        self.start = random.randint(0, self.numberOfNodes - 1)
        self.start_position = self.node_position.get(self.start + 1)

        return self.graph, self.start
Beispiel #23
0
def index(file_name):
    cities = tsplib95.load(
        os.path.join(os.getcwd(), '../data/' + file_name + '.tsp'))

    initial_state = random_state(cities)
    distance_initial_state = calc_distance_of_state(initial_state, cities)

    best_distance, best_solution = swap_neighbours(initial_state, cities)

    print(initial_state)
    plot_path(cities, initial_state, distance_initial_state, 'estado_inicial',
              file_name)
    print('initial: {}'.format(distance_initial_state))

    print(best_solution)
    plot_path(cities, best_solution, best_distance, 'melhor_solucao',
              file_name)
    print('best: {}'.format(best_distance))
    print('difference: {}'.format(distance_initial_state - best_distance))
 def load_file_and_create_graph(self, filename):
     problem = tsplib95.load(filename)
     G = problem.get_graph()
     nodes = list(problem.get_nodes())
     outer_array = []
     for i, o in enumerate(nodes):
         inner_array = []
         for j, v in enumerate(nodes):
             if i == j:
                 inner_array.append([0, 1])
             elif i > j:
                 inner_array.append(outer_array[j][i])
             else:
                 inner_array.append([G.edges[o, v]['weight'], 1])
         outer_array.append(inner_array)
     self.edges = outer_array
     self.cities = self.ants = len(nodes)
     self.nodes = nodes
     self.graph = problem
def main_run():
    global cm, coords, WIDTH, HEIGHT, CITIES
    path = os.path.join(os.path.dirname(__file__), 'data/fri26.tsp')
    problem = tsplib95.load(path)
    print(list(problem.get_nodes()))

    CITIES = len(list(problem.get_nodes()))
    for i in range(0, CITIES):
        for j in range(0, CITIES):
            edge = i, j
            weight = problem.get_weight(*edge)
            cm[i, j] = weight

    genome = G1DList.G1DList(CITIES)

    genome.setParams(dist=cm)
    genome.evaluator.set(lambda chromosome: tour_length(cm, chromosome))
    genome.crossover.set(G1DListCrossoverPMX)
    genome.mutator.set(G1DListMutatorDisplacement)
    genome.initializator.set(G1DListTSPInitializatorRandom)

    # 3662.69
    ga = GSimpleGA.GSimpleGA(genome)
    ga.setGenerations(GENERATION_COUNT)
    ga.setMinimax(Consts.minimaxType["minimize"])
    ga.setCrossoverRate(1.0)
    ga.setMutationRate(0.02)
    ga.setPopulationSize(80)
    ga.selector.set(SelectionRank.SelectorLinearRanking)

    # This is to make a video
    if PIL_SUPPORT:
        ga.stepCallback.set(evolve_callback)
    # 21666.49

    ga.evolve(freq_stats=1)
    best = ga.bestIndividual()

    if PIL_SUPPORT:
        write_tour_to_img(coords, best, f"{RESULTS_DIRECTORY}/tsp_result.png")
    else:
        print("No PIL detected, cannot plot the graph !")
Beispiel #26
0
def christofides(path):
    problem = tsplib95.load(path)
    G = problem.get_graph()
    preproc(G)

    T = minspantree(G)

    O = oddsubgraph(T, G)

    M = perfectmatching(O)

    H = nx.MultiGraph()
    H.add_edges_from(T.edges)
    H.add_edges_from(M.edges)

    print(H.edges)
    nx.draw_networkx(H)
    #plt.show()
    eulerian = EulerianCircle(H)

    hamiltonian = HamiltonianCircle(eulerian)
    #draw(G, hamiltonian)
    return weight(hamiltonian, G)
Beispiel #27
0
    def __init__(self, tsp_name) :

        self.problem = tsplib95.load(tsp_name)
        #Create a Graph
        node_position = self.problem.as_name_dict().get("node_coords")
        edges, distances, node_position = self.construct_edges(node_position)
        
        self.edges = edges
        self.distances = distances
        self.node_position = node_position

        node_from = []
        node_to = []

        for key, value in self.node_position.items() :
            for i in range(8) :
                node_from.append(key-1)
                node_to.append(value[i+2]-1)
            
        self.graph = dgl.DGLGraph((node_from, node_to))
        self.graph.ndata["h"] = np.float32(list(node_position.values()))
        self.graph.edata["h"] = np.float32(np.random.randn(len(self.node_position) * 8, 5))

        self.visited = dict()
Beispiel #28
0
    def __init__(self, tsp_name):

        #Load a Problem
        self.tsp_name = tsp_name
        self.problem = tsplib95.load(self.tsp_name)

        #Get Node Information
        self.node_position = self.problem.as_name_dict().get("node_coords")
        self.numberOfNodes = len(self.node_position)

        #Get Distance Information
        self.distances = dict()
        self.statistics = dict()
        for i in range(self.numberOfNodes):
            self.distances[i + 1] = dict()
            self.statistics[i + 1] = dict()
            for j in range(12):
                self.statistics[i + 1][j] = 0

        for i in range(self.numberOfNodes):
            for j in range(self.numberOfNodes):
                if i >= j: continue
                else:
                    distance = math.sqrt((self.node_position[i + 1][0] -
                                          self.node_position[j + 1][0])**2 +
                                         (self.node_position[i + 1][1] -
                                          self.node_position[j + 1][1])**2)
                    self.distances[i + 1][j + 1] = distance
                    self.distances[j + 1][i + 1] = distance
                    distance_class = int(distance * (10**-3))
                    self.statistics[i + 1][min(
                        distance_class, 11)] = self.statistics[i + 1].get(
                            min(distance_class, 11)) + 1
                    self.statistics[j + 1][min(
                        distance_class, 11)] = self.statistics[j + 1].get(
                            min(distance_class, 11)) + 1
Beispiel #29
0
def main():
    points = tsplib95.load('data/' + points_path)
    n_nodes = len(list(points.get_nodes()))
    all_value = 1000000000

    file_name = points_path.split('.')[0] + '_' + swap_strategy + '_' + str(
        n_tries)
    if swap_strategy == 'random':
        file_name += '_' + str(n_random_swap) + '_' + str(n_child_random_swap)
    file_name += '_random_decay.txt'
    file_log = open('results/log_' + file_name, 'w')

    for i in tqdm.tqdm(range(n_tries)):
        best_path, best_value, best_n = find_best_solution(points, n_nodes)
        if best_value < all_value:
            all_path, all_value, all_n, all_try = best_path, best_value, best_n, (
                i + 1)

        file_log.write("[" + str(i + 1) + "]:" + "\n")
        file_log.write("\tDistância do melhor caminho: " + str(best_value) +
                       "\n")
        file_log.write("\tIterações executadas: " + str(best_n) + "\n")
        file_log.write("\tMelhor caminho: ")
        write_list_file(file_log, best_path)

    file_log.close()

    file_best = open('results/best_' + file_name, 'w')

    file_best.write("Overall best[" + str(all_try) + "]:" + "\n")
    file_best.write("\tDistância do melhor caminho: " + str(all_value) + "\n")
    file_best.write("\tIterações executadas: " + str(all_n) + "\n")
    file_best.write("\tMelhor caminho: ")
    write_list_file(file_best, all_path)

    file_best.close()
import tsplib95
import acopy

# setting up the environment
solver = acopy.Solver(rho=.03, q=1)
colony = acopy.Colony(alpha=1, beta=3)

# adding a timer to record the total time to find the best path
timer = acopy.plugins.Timer()
solver.add_plugin(timer)

# setting it up so that is prints out each iteration
printout = acopy.plugins.Printout()
solver.add_plugin(printout)

problem = tsplib95.load('problems/pr124.tsp.txt')  # loading in the dataset
G = problem.get_graph()  # changing the dataset so that it can be used by the algorithm

tour = solver.solve(G, colony, limit=100)  #running the algorithm

# printing out relevant information
print("Shortest tour: ", tour.cost)
print("Best tour: ", tour.nodes)
print("Time to complete: ", timer.duration)