コード例 #1
0
def read_tsp_network(path):
    network = {}
    graph = tsp.load_problem(path).get_graph()
    network["number_of_cities"] = len(graph.nodes())
    network["matrix"] = nx.to_numpy_matrix(graph)

    return network
コード例 #2
0
def branchandbound(filename, tlim):

    problem = tsplib95.load_problem("benchmarks/" + filename)

    print("-------------------")
    print("Group : Devys, Dugeon, Guyard, Hourman, Prejean")
    print("Problem :", problem.comment)
    print("-------------------")

    (
        status,
        optimal_value,
        optimal_path,
        solving_time,
        nodes_explored,
        relax_solved,
    ) = solve(problem, tlim)

    print("-------------------")
    print("Problem :", problem.comment)
    print("Number of cities :", len(list(problem.get_nodes())))
    print("Method : Branch and Bound")
    print("Status :", status)
    if status == "Optimal":
        print("Optimal value :", round(optimal_value))
        print("Optimal tour :", optimal_path)
        print("Solving time :", solving_time)
        print("Nodes explored :", nodes_explored)
        print("Resolved relaxations :", relax_solved)
    print("-------------------")
コード例 #3
0
    def __init__(self, problem_path, prng_type=LEHMER_0):
        # Problem instance
        self.problem = tsplib95.load_problem(problem_path)

        # Graph of nodes
        G = self.problem.get_graph()

        # Cost (distance/duration) matrix
        self.M = np.array(nx.to_numpy_matrix(G))

        # Depot index
        if len(self.problem.depots) > 1:
            raise Exception(
                "This solver can only work with one depot problems. Please make sure that the problem only has one depot."
            )

        self.DI = self.problem.depots[0] - 1

        # Capacity constraint of vehicles
        self.CAPACITY = self.problem.capacity

        # Demands of jobs
        self.DEMANDS = [v for k, v in self.problem.demands.items()]

        # The savings list
        S = self._construct_savings_list(self.M)

        # Sorted saving list
        self.S = S[(-S[:, 2]).argsort()]

        # Random number generator type
        self.prng_type = prng_type
コード例 #4
0
ファイル: aco_problem.py プロジェクト: yhn280385395/swarmlib
    def __init__(self, **kwargs):
        """Initializes a new instance of the `ACOProblem` class.

        Arguments:  \r
        `ant_number` -- Number of ants used for solving

        Keyword arguments:  \r
        `tsp_file`   -- Path of the tsp file that shall be loaded  \r
        `rho`           -- Evaporation rate (default 0.5)  \r
        `alpha`         -- Relative importance of the pheromone (default 0.5)  \r
        `beta`          -- Relative importance of the heuristic information (default 0.5)  \r
        `q`             -- Constant Q. Used to calculate the pheromone, laid down on an edge (default 1)  \r
        `iterations`    -- Number of iterations to execute (default 10)  \r
        `plot_interval` -- Plot intermediate result after this amount of iterations (default 10) \r
        `two_opt`       -- Additionally use 2-opt local search after each iteration (default true)
        """

        self.__ant_number = kwargs['ant_number']  # Number of ants
        tsp_file = kwargs.get('tsp_file', path.join(path.abspath(path.dirname(inspect.getfile(inspect.currentframe()))), 'resources/burma14.tsp'))
        self.__graph = Graph(tsplib95.load_problem(tsp_file))
        LOGGER.info('Loaded tsp problem="%s"', tsp_file)

        self.__rho = kwargs.get('rho', 0.5)  # evaporation rate
        self.__alpha = kwargs.get('alpha', 0.5)  # used for edge detection
        self.__beta = kwargs.get('beta', 0.5)  # used for edge detection
        self.__Q = kwargs.get('q', 1)  # Hyperparameter Q
        self.__num_iterations = kwargs.get('iteration_number', 10)  # Number of iterations
        self.__use_2_opt = kwargs.get('two_opt', False)

        self.__visualizer = Visualizer(**kwargs)
コード例 #5
0
    def __init__(self, problem_path, prng_type=LEHMER_0):
        # Problem instance
        self.problem = tsplib95.load_problem(problem_path)

        # Graph of nodes
        self.G = self.problem.get_graph()

        # Cost (distance/duration) matrix
        self.M = np.array(nx.to_numpy_matrix(self.G))

        # Depot index
        self.DI = self.problem.depots[0] - 1

        # Capacity constraint of vehicles
        self.CAPACITY = self.problem.capacity

        # Demands of jobs
        self.DEMANDS = [v for k, v in self.problem.demands.items()]

        # The saving list
        S = self.get_saving_list(self.M)

        # Sorted saving list
        self.S = S[(-S[:, 2]).argsort()]

        # Random number generator type
        self.prng_type = prng_type
コード例 #6
0
def tsp(genome):
    tsp_path = 'TSP/bays29.tsp'
    tsp_problem = tsplib95.load_problem(tsp_path)

    count = 0
    for i in range(len(genome) - 1):
        count += tsp_problem.wfunc(genome[i] + 1, genome[i + 1] + 1)
    return count + tsp_problem.wfunc(genome[-1] + 1, genome[0] + 1)
コード例 #7
0
def solveTSPLib(fname, exact=True, logFile=None):
    """
    Solve a TSPLIB instance stored in file "fname" by means of
    Concorde's TSP solver.

    Parameters:
        fname : str
            Name (including) the path to the data file (format TSPLIB).
        exact : bool
            If true (default) it is tried to solve the instance exactly
            by means of Concorde's branch-and-cut solver; otherwise 
            Concorde only applies the Lin-Kernighan heuristic.
        logFile : str
            If not None, it need to be the name of file, where to 
            redirect output from Concorde.

    Returns:
        routeLen : int
            Length of the route (routeLen).
        route : list of int
            Computed route (route[0] is the depot and route[-1] is the
            last customer).
    """

    if __CC_Lib is None:
        print("Concorde Library not loaded!")
        return 0, []
    else:
        # We first create a pointer to an integer array
        problem = load_problem(fname)
        tour = np.zeros(problem.dimension, dtype=ctypes.c_int)
        iptr = ctypes.POINTER(ctypes.c_int)
        ptour = tour.ctypes.data_as(iptr)
        # Redirect output from Concorde?
        if logFile is None:
            logPtr = ctypes.c_char_p(0)
        else:
            logPtr = ctypes.c_char_p(logFile.encode('utf-8'))
            old_out = sys.stdout

        # Initialize other parameters of c-function solve_TSLPlib
        seed = ctypes.c_int(int(time.time()))
        status = ctypes.c_int(0)
        tiLim = ctypes.c_double(0.0)
        n = ctypes.c_int(0)
        fnmeptr = ctypes.c_char_p(fname.encode('utf-8'))
        LKonly = ctypes.c_char(1 - int(exact))
        __CC_Lib.solve_TSPlib.restype = ctypes.c_double
        tLen    = __CC_Lib.solve_TSPlib( LKonly, fnmeptr, seed, tiLim,\
                      logPtr, ptour, ctypes.byref(status) )
        routeLen = tLen
        nodeLst = [node for node in problem.get_nodes()]
        route = [nodeLst[i] for i in tour]

        # Following is safer when on Windows
        if not logFile is None: sys.stdout = old_out

        return routeLen, route
コード例 #8
0
def read_tsp_file(file_name_input):
    tsp_problem = tsp.load_problem(file_name_input)
    G = tsp_problem.get_graph()
    n = len(G.nodes())
    network = {}
    network['number_of_nodes'] = n
    matrix = nx.to_numpy_matrix(G)
    network['matrix'] = matrix
    return network
コード例 #9
0
def readTSP(file_name_input):
    tsp_problem = tsp.load_problem(file_name_input)
    G = tsp_problem.get_graph()
    n = len(G.nodes())
    net = {}
    net['noNodes'] = n
    matrix = nx.to_numpy_matrix(G)
    net['mat'] = matrix
    return net
コード例 #10
0
def WczytajProblem(sciezkaDoPliku):
    import tsplib95
    import numpy as np
    problem = tsplib95.load_problem(sciezkaDoPliku)
    lista = list(problem.get_edges())
    #problem.wfunc(1,2)
    tab = []
    for x, y in lista:
        tab.append(problem.wfunc(x, y))
    tab2 = np.array(tab)
    return tab2.reshape(x, y)
コード例 #11
0
def solve_aco_tsp(resPath):

    print(resPath)
    solver = acopy.Solver(rho=.03, q=.5)
    colony = acopy.Colony(alpha=1, beta=3)

    problem = tsplib95.load_problem(resPath)
    G = problem.get_graph()

    tour = solver.solve(G, colony, limit=100)

    return tour
コード例 #12
0
    def __readData(self):
        data = tsplib95.load_problem(self.__filename)
        #networkx graph
        graph = data.get_graph()
        noNodes = graph.number_of_nodes()
        #numpy distance matrix
        matrix = networkx.to_numpy_matrix(graph)

        params = {}
        params["noNodes"] = noNodes
        params["matrix"] = matrix

        return params
コード例 #13
0
    def load_instance(self, name: str) -> None:
        problem: Problem = load_problem(Instance.PATH.format(name))
        coords: OrderedDict = problem.node_coords
        d = problem.dimension

        self.adjacency_matrix = np.zeros(shape=(d, d), dtype=np.int)
        for i in range(d):
            for j in range(d):
                self.adjacency_matrix[i,
                                      j] = euclidean(coords[i + 1],
                                                     coords[j + 1])

        self.city_coords: np.ndarray = np.array(list(coords.values()))
コード例 #14
0
def load_instance_tsplib(path):
    problem = load_problem(path)
    coords = problem.node_coords
    d = problem.dimension

    dimension_matrix = np.zeros(shape=(d, d), dtype=np.int)
    for i in range(d):
        for j in range(d):
            dimension_matrix[i, j] = int(
                round(euclidean(coords[i + 1], coords[j + 1])))

    final_coords = np.array(list(coords.values()))
    return final_coords, dimension_matrix
コード例 #15
0
def init():
    global problem
    global dimension
    # 载入TSP问题数据(load_problem 需要指定一个 distance function)
    problem = tsplib95.load_problem("../tc/d198.tsp", special=cal_distance)
    # 初始化变量
    dimension = problem.dimension
    generate_matrix()
    init_popu()
    print("初始路径长度:{0}".format(distances))
    # 打开交互模式,非阻塞画图
    plt.figure(figsize=(8, 6), dpi=80)
    plt.ion()
コード例 #16
0
def run(memetic):

    # Set the seed
    random.seed(seed)

    # Receive the problem
    problem = tsplib95.load_problem("data/" + instance)
    nr_of_nodes = len(list(problem.get_nodes()))

    # Create the problem in DEAP
    creator.create("FitnessMin", base.Fitness, weights=(-1.0, ))
    creator.create("Individual", list, fitness=creator.FitnessMin)

    toolbox = base.Toolbox()

    toolbox.register("indices", random.sample, range(nr_of_nodes), nr_of_nodes)
    toolbox.register("individual", tools.initIterate, creator.Individual,
                     toolbox.indices)
    toolbox.register("population", tools.initRepeat, list, toolbox.individual)

    toolbox.register("evaluate", path_length, data=problem)
    toolbox.register("mate", tools.cxOrdered)
    toolbox.register("mutate",
                     reverse_sequence_mutation,
                     memetic=memetic,
                     data=problem,
                     icls=creator.Individual)
    toolbox.register("select", tools.selTournament, tournsize=2)

    stats = tools.Statistics(lambda ind: ind.fitness.values)
    stats.register("avg", numpy.mean)
    stats.register("min", numpy.min)

    pop = toolbox.population(n=300)

    start_time = time.time()

    pop, out = algorithms.eaSimple(pop,
                                   toolbox,
                                   cxpb=0.5,
                                   mutpb=1,
                                   ngen=100,
                                   stats=stats)

    print("Memetic: %r" % memetic)
    print("Execution time: %s seconds" % (time.time() - start_time))

    return out
コード例 #17
0
def main():
    def euclidean_float(a, b):
        x1, y1 = a
        x2, y2 = b
        dist = math.sqrt((x1 - x2)**2 + (y1 - y2)**2)
        return dist

    Q = 1
    rho = 0.8
    alfa = 1
    beta = 4
    n_iter_max = 50
    best_ant = Ant(None, alfa, beta)
    best_ant.path_dist = 99999999

    n_exec = 0
    n_exec_max = 1

    problem = tsplib95.load_problem('st70.tsp', special=euclidean_float)
    while (n_exec < n_exec_max):
        print("Execution number: ", n_exec)
        graph = problem.get_graph()
        n_ants = graph.number_of_nodes()

        for e in graph.edges:
            graph[e[0]][e[1]]['feromonio'] = 1

        n_iter = 0
        while (n_iter < n_iter_max):
            ants_list = [Ant(graph, alfa, beta) for x in range(n_ants)]
            for a in ants_list:
                a.find_path(graph)

            for e in graph.edges:
                graph[e[0]][e[1]]['feromonio'] *= (1 - rho)

            for a in ants_list:
                for e in a.edges:
                    graph[e[0]][e[1]]['feromonio'] += Q / a.path_dist

            best_ant_aux = sorted(ants_list, key=lambda a: a.path_dist)[0]
            if (best_ant_aux.path_dist < best_ant.path_dist):
                best_ant = best_ant_aux
                print("Improved")

            n_iter = n_iter + 1
        n_exec += 1
    print("Best result: ", best_ant)
コード例 #18
0
def readFileHard(filename):
    network = {}
    tsp_file = tsp.load_problem(filename)
    g = tsp_file.get_graph()
    nrCities = len(g.nodes())
    network['nrCities'] = nrCities
    matrix = nx.to_numpy_matrix(g)
    graph = []
    for i in range(nrCities):
        graph.append([])
        for j in range(nrCities):
            value = matrix.item((i, j))
            if value == 0:
                value += 1
            graph[i].append(value)
    print(nrCities)
    print(graph)
    network['mat'] = graph
    return network
コード例 #19
0
    def __init__(self,
                 tsp_file,
                 ant_number,
                 rho=0.5,
                 alpha=0.5,
                 beta=0.5,
                 q=1,
                 iterations=100,
                 plot_interval=10,
                 two_opt=True):
        """Initializes a new instance of the `ACOProblem` class.

        Arguments:  \r
        `tsp_file`   -- Path of the tsp file that shall be loaded  \r
        `ant_number` -- Number of ants used for solving

        Keyword arguments:  \r
        `rho`           -- Evaporation rate (default 0.5)  \r
        `alpha`         -- Relative importance of the pheromone (default 0.5)  \r
        `beta`          -- Relative importance of the heuristic information (default 0.5)  \r
        `q`             -- Constant Q. Used to calculate the pheromone, laid down on an edge (default 1)  \r
        `iterations`    -- Number of iterations to execute (default 100)  \r
        `plot_interval` -- Plot intermediate result after this amount of iterations (default 10) \r
        `two_opt`       -- Additionally use 2-opt local search after each iteration (default true)
        """

        self.__graph = Graph(tsplib95.load_problem(tsp_file))
        LOGGER.info('Loaded tsp problem="%s"', tsp_file)
        self.rho = rho  # evaporation rate
        self.alpha = alpha  # used for edge detection
        self.beta = beta  # used for edge detection
        self.Q = q  # Hyperparameter Q
        self.ant_number = ant_number  # Number of ants
        self.num_iterations = iterations  # Number of iterations
        self.plot_iter = plot_interval  # plot intervall
        self.__stop_event = Event()  # Event used to stop the plotting thread
        self.__result_queue = Queue()
        self.__last_result = None
        self.best_path = None
        self.shortest_distance = None
        self.__use_2_opt = two_opt
コード例 #20
0
def cuttingplanes(filename, tlim):

    problem = tsplib95.load_problem("benchmarks/" + filename)

    print("-------------------")
    print("Group : Devys, Dugeon, Guyard, Hourman, Prejean")
    print("Problem :", problem.comment)
    print("-------------------")

    status, optimal_value, optimal_path, solving_time, cuts_added = solve(
        problem, tlim)

    print("-------------------")
    print("Problem :", problem.comment)
    print("Number of cities :", len(list(problem.get_nodes())))
    print("Method : Cutting planes")
    print("Status :", status)
    if status == "Optimal":
        print("Optimal value :", round(optimal_value))
        print("Optimal tour :", optimal_path[0])
        print("Solving time :", solving_time)
        print("Cuts added :", cuts_added)
    print("-------------------")
コード例 #21
0
ファイル: TSP_from_MST.py プロジェクト: AntoineBarone/IGI_G3
                    return path(graph, nodes_visited, edges_visited,
                                path_nodes + [i])


# -------------------------------------------------------------------------------------------------

# Loading a TSP problem
#-------------------------------------------------------------------------------------------------------
# Work on berlin52:
#----------------------------------------------------------------------------------------------------
# problem = tsplib95.load_problem('./TSPData/berlin52.tsp')

#----------------------------------------------------------------------------------------------------
# Work on berlin10:
#----------------------------------------------------------------------------------------------------
problem = tsplib95.load_problem('./TSPData/berlin10.tsp')

#----------------------------------------------------------------------------------------------------
# Work on a280 :
#----------------------------------------------------------------------------------------------------
# problem = tsplib95.load_problem('./TSPData/a280.tsp')

#-----------------------------------------------------------------------------------------------------
# Solution TSP
#------------------------------------------------------------------------------------------------------
orig_graph = TSPlib_to_networkx(problem)

tsp_solution, edges_d = TSP_from_MST(orig_graph)

print(problem.name)
print(problem.type)
コード例 #22
0
ファイル: test_acopy.py プロジェクト: Ganariya/kiacopy
import os
from logging import getLogger, StreamHandler, DEBUG

import acopy
import kiacopy
import tsplib95

from kiacopy.parameter import Parameter

logger = getLogger()
logger.addHandler(StreamHandler())
logger.setLevel(DEBUG)

graph_name: str = 'gr17.tsp'
problem = tsplib95.load_problem(graph_name)
G = problem.get_graph()

solver = acopy.Solver()
colony = acopy.Colony()

solver.solve(G, colony, limit=300)

config_path = os.path.join(os.path.dirname(__file__), 'config', 'normal.yaml')
parameter: Parameter = Parameter.create(config_path)

solver = kiacopy.Solver(parameter=parameter)
recorder = kiacopy.plugins.StatsRecorder('results')
plotter = kiacopy.utils.plot.Plotter(stats=recorder.stats)
# drawer = kiacopy.plugins.DrawGraph(problem=problem, is_each=True, is_label=True, is_consecutive=True)
converter = kiacopy.plugins.ConvertStateToJson(save_path='results')
solver.add_plugins(recorder, converter)
コード例 #23
0
ファイル: TSP_db.py プロジェクト: ellisrourke/tsp-problem
import mysql.connector
import tsplib95
import tsp
import sys

connection = mysql.connector.connect(host='mysql.ict.griffith.edu.au',
                                     user='******',
                                     password='******',
                                     database='s5057468db')
mycursor = connection.cursor()
prob = tsplib95.load_problem(sys.argv[1] + ".tsp")

if sys.argv[2] == "ADD":

    dim = prob.dimension
    print(dim)
    tour = list(range(0, dim + 1))

    #print(prob.get_display(tour[0])[i])

    sql = "INSERT IGNORE INTO problem (name, dimention, description) VALUES (%s, %s, %s)"

    #WHERE NOT EXISTS (SELECT name FROM problem WHERE name = %s)
    val = (sys.argv[1], dim, "NULL")
    try:
        mycursor.execute(sql, val)
    except:
        print("error occured")

#add all cities to city table
    for i in range(1, dim + 1):
コード例 #24
0
#! /usr/bin/env python
# -*- coding: utf-8 -*-
# vim:fenc=utf-8
#
# Copyright © 2019 haroldo <haroldo@viper>
#
# Distributed under terms of the MIT license.

from sys import argv
from os.path import basename
import tsplib95 as tsp_data

P = tsp_data.load_problem(argv[1])

iname = basename(argv[1])

if iname.endswith('.tsp'):
    iname = iname.split('.tsp')[0]

N = set([i for i in P.get_nodes()])

fo = open('%s.dist' % iname, 'w')
for i in N:
    for j in N:
        fo.write('%d\n' % P.wfunc(i, j))
fo.close()
コード例 #25
0
 def read_tsp_file(self):
     tsp_problem = tsp.load_problem(self.__filename + ".txt")
     G = tsp_problem.get_graph()
     n = len(G.nodes())
     matrix = nx.to_numpy_matrix(G)
     return (n, matrix)
コード例 #26
0
ファイル: tsp-lazy.py プロジェクト: tommyod/python-mip
                    cut = xsum(1.0 * v for v, fm in arcsInS) <= len(S) - 1
                    cp.add(cut)
                    if len(cp.cuts) > 256:
                        for cut in cp.cuts:
                            model.add_cut(cut)
                        return
        for cut in cp.cuts:
            model.add_cut(cut)
        return


if len(argv) <= 1:
    print('enter instance name.')
    exit(1)

inst = tsplib95.load_problem(argv[1])
N = [n for n in inst.get_nodes()]
n = len(N)
A = dict()
for (i, j) in inst.get_edges():
    if i != j:
        A[(i, j)] = inst.wfunc(i, j)

# set of edges leaving a node
OUT = defaultdict(set)

# set of edges entering a node
IN = defaultdict(set)

# an arbitrary initial point
n0 = min(i for i in N)
コード例 #27
0
import tsplib95

from functions import distance_on_unit_sphere
from plotSprawko import plot

problem = tsplib95.load_problem('./data/ulysses16.tsp',
                                distance_on_unit_sphere)
problem.special = distance_on_unit_sphere
G = problem.get_graph()

points: list = []
for i in range(1, G.number_of_nodes() + 1):
    points.append(G.nodes[i].get('coord'))

path = [3, 2, 4, 8, 1, 16, 14, 13, 12, 7, 6, 15, 5, 11, 9, 10]

plot(points, path)

############################################################

problem = tsplib95.load_problem('./data/att48.tsp')
G = problem.get_graph()

points: list = []
for i in range(1, G.number_of_nodes() + 1):
    points.append(G.nodes[i].get('coord'))

path = [
    17, 19, 37, 6, 27, 43, 30, 28, 7, 18, 36, 44, 31, 38, 9, 1, 8, 40, 15, 33,
    46, 12, 11, 23, 13, 25, 14, 34, 3, 22, 16, 41, 29, 2, 26, 4, 35, 45, 24,
    10, 42, 48, 5, 39, 32, 21, 47, 20
 def load_problem(self):
     if self._problem is None:
         self._problem = tsp.load_problem(self.inp_abs_path)
     return self._problem
コード例 #29
0
def load_instance(path):
    """
    :param path:
    :return:
    """
    return load_problem(path)
コード例 #30
0
    #plt.figure(figsize=figsize)
    plt.title(title)
    plt.savefig(savename)
    plt.cla()


if __name__ == "__main__":

    DATA_PATH = Path("data")
    assert DATA_PATH.exists()
    NAME = "berlin52"
    NAME = "ulysses16"
    PROBLEM_PATH = DATA_PATH / f"{NAME}.tsp"
    SOLUTION_PATH = DATA_PATH / f"{NAME}.opt.tour"

    p = tsp.load_problem(PROBLEM_PATH)
    s = tsp.load_solution(SOLUTION_PATH)

    print(f"Optimal tour: {s.tours}")
    print(f"Optimal tour: {p.trace_tours(s)}")
    g = p.get_graph()
    draw(g, s.tours[0])

#def get_colors(
#    graph, edges, default='b', highlight='r',
#):
#    c = np.full(len(graph.edges), default)
#    w = np.ones(len(graph.edges))
#
#    for i, edge in enumerate(graph.edges):
#        if edge in edges:
コード例 #31
0
ファイル: data.py プロジェクト: rhgrant10/Pants
def read_tsplib95(path):
    problem = tsplib95.load_problem(path)
    return problem.get_graph()