Beispiel #1
0
def main():
    v1 = Vertex("1")
    v1.pos = (1, 0)
    v2 = Vertex("2")
    v2.pos = (0, 1)
    rw = TspRW()
    A = BNB([v1, v2])

    print("Testing read_file in TspRW class..")
    rw.read_file("tsp-test.tsp")
    test(
        rw.header
        == [
            "NAME: tsp-test.tsp\n",
            "COMMENT: agarwali and ramax. 6 vertices. Note that vertex 1 is at (1, 5); vertex 2 is at (3, 7), etc.\n",
            "TYPE: TSP\n",
            "DIMENSION: 6\n",
            "EDGE_WEIGHT_TYPE: EUC_2D\n",
            "NODE_COORD_SECTION\n",
        ]
    )
    test(rw.coordinates == [v1, v2])

    print("Testing explore in BNB class.. ")
    A.explore()
    test(A.tour == [v1, v2])

    print("Testing chop in BNB class.. ")
    test(A.chop() == None)

    print("Testing distance in BNB class..")
    test(A.distance(v1, v2) == sqrt(2))

    print("Testing compute_bound in BNB class..")
    test(A.compute_bound(v2) == float("inf"))  # resets self.best_tour to an empty graph containing vertices
Beispiel #2
0
def main():
    v1 = Vertex('1')
    v1.pos = (1, 0)
    v2 = Vertex('2')
    v2.pos = (0, 1)
    rw = TspRW()
    A = BNB([v1, v2])

    print('Testing read_file in TspRW class..')
    rw.read_file('tsp-test.tsp')
    test(rw.header == [
        'NAME: tsp-test.tsp\n',
        'COMMENT: agarwali and ramax. 6 vertices. Note that vertex 1 is at (1, 5); vertex 2 is at (3, 7), etc.\n',
        'TYPE: TSP\n', 'DIMENSION: 6\n', 'EDGE_WEIGHT_TYPE: EUC_2D\n',
        'NODE_COORD_SECTION\n'
    ])
    test(rw.coordinates == [v1, v2])

    print('Testing explore in BNB class.. ')
    A.explore()
    test(A.tour == [v1, v2])

    print('Testing chop in BNB class.. ')
    test(A.chop() == None)

    print('Testing distance in BNB class..')
    test(A.distance(v1, v2) == sqrt(2))

    print('Testing compute_bound in BNB class..')
    test(A.compute_bound(v2) == float(
        'inf'))  # resets self.best_tour to an empty graph containing vertices
Beispiel #3
0
def main():
    read_write = TspRW()  # create a read_write object
    read_write.read_file(
        raw_input('Enter file to read from: '
                  ))  # reads all the coordinates of citties from an ASCII file
    l = read_write.labels
    c = read_write.coordinates
    handle = Nearest_Neighbour(
        l, c)  # create a Nearest_neigbour class from the given vertices

    # for each vertex
    for i in handle.vertices:
        handle.mark_unvisited_cities()  # mark all the citites unvisited
        handle.empty_tour()  # empties the tour
        handle.startcity = i  # set the city to start city
        handle.currentcity = handle.startcity  # sets the start city to current city
        handle.mark_visited()  # marks the city visited

        # while there is an unvisited city
        while len(handle.coordinates) != 0:
            handle.calculate_nearneighbor(
            )  # find the nearest neighbour for the current city
            handle.add_currcity_tour()  # adds the current city to the tour
            handle.add_tourCost()  # adds the cost to the tour
            handle.currentcity = handle.nearestcity  # sets nearest city to current city
            handle.mark_visited()  # marks the current city visited
        e = Edge(handle.currentcity, handle.startcity
                 )  # creates the last edge between the current and start city
        handle.best_tour.add_edge(e)  # add that last edge to best tour

        # updates best_tour_so_far if the last tour was lest costly
        if handle.cost_of_tour < handle.cost_of_best_tour_so_far:
            handle.cost_of_best_tour_so_far = handle.cost_of_tour
            handle.best_tour_so_far = handle.best_tour
            handle.best_label_so_far = handle.best_label
            handle.best_coordinates_so_far = handle.best_coordinates

    # write the coordinates to an ASCII file with .tour extension
    read_write.coordinates = handle.best_coordinates_so_far
    read_write.labels = handle.best_label_so_far
    read_write.write_file()

    # print handle.best_tour_so_far
    # print handle.cost_of_best_tour_so_far
    # print handle.best_label_so_far
    # print handle.best_coordinates_so_far

    # for i in range(len(handle.best_label_so_far)):
    #     handle.best_label_so_far[i].pos = handle.best_coordinates_so_far

    # The following two lines allows to swtich the layout of the graph displayed
    layout = CartesianLayout(handle.best_tour_so_far)
    # layout = RandomLayout(handle.best_tour_so_far)

    # draw the graph
    gw = GraphWorld()
    gw.show_graph(handle.best_tour_so_far, layout)
    gw.mainloop()
Beispiel #4
0
def main():
    read_write = TspRW()    # create a read_write object
    read_write.read_file(raw_input('Enter file to read from: '))    # reads all the coordinates of citties from an ASCII file
    l = read_write.labels   
    c = read_write.coordinates
    handle = Nearest_Neighbour(l, c)    # create a Nearest_neigbour class from the given vertices
    
    # for each vertex
    for i in handle.vertices:
        handle.mark_unvisited_cities()  # mark all the citites unvisited
        handle.empty_tour() # empties the tour
        handle.startcity = i    # set the city to start city
        handle.currentcity = handle.startcity   # sets the start city to current city
        handle.mark_visited()   # marks the city visited
        
        # while there is an unvisited city
        while len(handle.coordinates)!= 0:  
            handle.calculate_nearneighbor() # find the nearest neighbour for the current city
            handle.add_currcity_tour()  # adds the current city to the tour
            handle.add_tourCost()   # adds the cost to the tour
            handle.currentcity = handle.nearestcity # sets nearest city to current city
            handle.mark_visited()   # marks the current city visited
        e = Edge(handle.currentcity, handle.startcity)  # creates the last edge between the current and start city
        handle.best_tour.add_edge(e)    # add that last edge to best tour
        
        # updates best_tour_so_far if the last tour was lest costly
        if handle.cost_of_tour < handle.cost_of_best_tour_so_far :  
            handle.cost_of_best_tour_so_far = handle.cost_of_tour
            handle.best_tour_so_far = handle.best_tour
            handle.best_label_so_far = handle.best_label
            handle.best_coordinates_so_far = handle.best_coordinates

    # write the coordinates to an ASCII file with .tour extension
    read_write.coordinates = handle.best_coordinates_so_far
    read_write.labels = handle.best_label_so_far
    read_write.write_file()

    # print handle.best_tour_so_far
    # print handle.cost_of_best_tour_so_far
    # print handle.best_label_so_far
    # print handle.best_coordinates_so_far

    # for i in range(len(handle.best_label_so_far)):
    #     handle.best_label_so_far[i].pos = handle.best_coordinates_so_far

    # The following two lines allows to swtich the layout of the graph displayed
    layout = CartesianLayout(handle.best_tour_so_far)
    # layout = RandomLayout(handle.best_tour_so_far)

    # draw the graph
    gw = GraphWorld()
    gw.show_graph(handle.best_tour_so_far, layout)
    gw.mainloop()
Beispiel #5
0
def main():

    time.clock()
    object = TwoOpt()   # create a two-opt object

    read_write = TspRW()    # create a read_write object
    read_write.read_file(raw_input('Enter file to read from: '))    # reads all the coordinates of citties from an ASCII file
    object.labels = read_write.labels   # store the labels in a list
    object.coordinates = read_write.coordinates      # store the coordinates in this list

    numRound = int(raw_input('Enter the number of random graphs you want to generate: '))
    roundTimes = int(raw_input('Enter the number of times you want to swap edges: '))

    for i in range(numRound):
        object.generate_rand_graph()    # generate a random graph
        for i in range(roundTimes):
            object.generate_rand_vertices()    # randomly generate two indices which have no common connection
            object.find_random_edge()   # generate two random edges from the given indices
            object.find_new_edge()  # find the new edge if swap were to happen.

            dx_oldtour = object.cal_distance_of_edge(object.edge1) + object.cal_distance_of_edge(object.edge2)  # difference in cost before swapping using two-opt
            dx_newtour = object.cal_distance_of_edge(object.new_edge1) + object.cal_distance_of_edge(object.new_edge2)    # difference in cost after adding two edges.
            if dx_newtour < dx_oldtour:
                object.remove_edges()
                object.add_edge_reversely()
        if object.costOfBestTour > object.costOfTour:
            bestTour = object.tour
            bestTour_vertices = object.tour_vertices
            object.costOfBestTour = object.costOfTour

    # write the tour in .tour ASCII file
    read_write.coordinates = []
    read_write.labels = []
    for i in bestTour_vertices:
        read_write.coordinates.append(i.pos)
    for i in bestTour_vertices:
        read_write.labels.append(i.label)
    read_write.write_file()

    print 'Run time: ', time.clock()

    # The following two lines allows to switch the layout of the graph displayed
    # layout = CartesianLayout(bestTour)
    layout = RandomLayout(bestTour)
    # layout = CircleLayout(bestTour)
    # draw the graph
    gw = GraphWorld()
    gw.show_graph(bestTour, layout)
    gw.mainloop()
def main():
    rw = TspRW()
    A = Nearest_Neighbour(['1', '2'], [(1, 0), (0, 1)])

    print ('Testing read_file in TspRW class..')
    rw.read_file('tsp-test.tsp')
    test(rw.header == ['NAME: tsp-test.tsp\n',
                       'COMMENT: agarwali and ramax. 6 vertices. Note that vertex 1 is at (1, 5); vertex 2 is at (3, 7), etc.\n',
                       'TYPE: TSP\n', 'DIMENSION: 6\n', 'EDGE_WEIGHT_TYPE: EUC_2D\n', 'NODE_COORD_SECTION\n'])
    test(rw.coordinates == [(1, 0), (0, 1)])
    test(rw.labels == ['1', '2'])

    print('Testing mark_unvisited_cities ..')
    A.mark_unvisited_cities()
    test(A.coordinates ==  [(1, 0), (0, 1)] )
    test(A.vertices == [Vertex('1'), Vertex('2')])

    print('Testing empty_tour ..')
    A.empty_tour()
    test(A.best_tour == Graph(A.vertices))  # resets self.best_tour to an empty graph containing vertices
    test(A.best_label == [])  # empties self.best_label
    test(A.best_coordinates ==[])   # epmties self.best_coordinates
    
    A.startcity = A.vertices[0]    # set the city to start city
    A.currentcity = A.startcity 
    
    print('Testing mark_visited ..')    
    A.mark_visited()
    test(A.currentcity_coordinate == (1,0))   # gets the coordinate for current city before removing it from the list
    test(A.vertices == [Vertex('2')])    # removes the vertex of current city from the self.vertices
    test(A.coordinates == [(0, 1)])# removes the cooordinate of current city from self.coordinates
    test(A.best_label == ['1']) # adds the current cities label to the best_label
    test(A.best_coordinates == [(1,0)])# adds the current city to the list of best_coordinates
    
    print('Testing calculate_nearneighbor ..')
    A.calculate_nearneighbor()
    test(A.cost_to_nearest_city == 2**0.5)    # if distance is less the update cost 
    test(A.nearestcity == Vertex('2'))     # upade nearest city
                

    print ('Testing add_currcity_tour..')
    A.add_currcity_tour()
    test(A.best_tour.__str__() == "Graph([Vertex('2'), Vertex('1')], set([Edge(Vertex('1'), Vertex('2'))]))")

    print('Testing add_tourCost ..')
    A.add_tourCost()
    test(A.cost_of_tour == 2**0.5)
Beispiel #7
0
def main():
    
    read_write = TspRW()    # create a read_write object
    read_write.read_file(raw_input('Enter file to read from: '))    # reads all the coordinates of citties from an ASCII file

    # solver is an BNB object
    solver = BNB(read_write.coordinates)
    solver.explore()    # explores all the vertex using BNB algorithm

    # write the tour in .tour ASCII file
    read_write.coordinates = solver.tour
    read_write.write_file()
    
    # The following two lines allows to switch the layout of the graph displayed
    layout = CartesianLayout(solver.tourGraph)
    # layout = RandomLayout(solver.tourGraph)
    # layout = CircleLayout(solver.tourGraph)
    # draw the graph
    gw = GraphWorld()
    gw.show_graph(solver.tourGraph, layout)
    gw.mainloop()
Beispiel #8
0
def main():

    read_write = TspRW()  # create a read_write object
    read_write.read_file(
        raw_input('Enter file to read from: '
                  ))  # reads all the coordinates of citties from an ASCII file

    # solver is an BNB object
    solver = BNB(read_write.coordinates)
    solver.explore()  # explores all the vertex using BNB algorithm

    # write the tour in .tour ASCII file
    read_write.coordinates = solver.tour
    read_write.write_file()

    # The following two lines allows to switch the layout of the graph displayed
    layout = CartesianLayout(solver.tourGraph)
    # layout = RandomLayout(solver.tourGraph)
    # layout = CircleLayout(solver.tourGraph)
    # draw the graph
    gw = GraphWorld()
    gw.show_graph(solver.tourGraph, layout)
    gw.mainloop()
Beispiel #9
0
def main():
    rw = TspRW()
    A = Nearest_Neighbour(['1', '2'], [(1, 0), (0, 1)])

    print('Testing read_file in TspRW class..')
    rw.read_file('tsp-test.tsp')
    test(rw.header == [
        'NAME: tsp-test.tsp\n',
        'COMMENT: agarwali and ramax. 6 vertices. Note that vertex 1 is at (1, 5); vertex 2 is at (3, 7), etc.\n',
        'TYPE: TSP\n', 'DIMENSION: 6\n', 'EDGE_WEIGHT_TYPE: EUC_2D\n',
        'NODE_COORD_SECTION\n'
    ])
    test(rw.coordinates == [(1, 0), (0, 1)])
    test(rw.labels == ['1', '2'])

    print('Testing mark_unvisited_cities ..')
    A.mark_unvisited_cities()
    test(A.coordinates == [(1, 0), (0, 1)])
    test(A.vertices == [Vertex('1'), Vertex('2')])

    print('Testing empty_tour ..')
    A.empty_tour()
    test(A.best_tour == Graph(A.vertices)
         )  # resets self.best_tour to an empty graph containing vertices
    test(A.best_label == [])  # empties self.best_label
    test(A.best_coordinates == [])  # epmties self.best_coordinates

    A.startcity = A.vertices[0]  # set the city to start city
    A.currentcity = A.startcity

    print('Testing mark_visited ..')
    A.mark_visited()
    test(A.currentcity_coordinate == (
        1, 0
    ))  # gets the coordinate for current city before removing it from the list
    test(A.vertices == [
        Vertex('2')
    ])  # removes the vertex of current city from the self.vertices
    test(A.coordinates == [
        (0, 1)
    ])  # removes the cooordinate of current city from self.coordinates
    test(A.best_label == ['1'
                          ])  # adds the current cities label to the best_label
    test(A.best_coordinates == [
        (1, 0)
    ])  # adds the current city to the list of best_coordinates

    print('Testing calculate_nearneighbor ..')
    A.calculate_nearneighbor()
    test(A.cost_to_nearest_city == 2**
         0.5)  # if distance is less the update cost
    test(A.nearestcity == Vertex('2'))  # upade nearest city

    print('Testing add_currcity_tour..')
    A.add_currcity_tour()
    test(
        A.best_tour.__str__() ==
        "Graph([Vertex('2'), Vertex('1')], set([Edge(Vertex('1'), Vertex('2'))]))"
    )

    print('Testing add_tourCost ..')
    A.add_tourCost()
    test(A.cost_of_tour == 2**0.5)
Beispiel #10
0
def main():

    time.clock()
    object = TwoOpt()  # create a two-opt object

    read_write = TspRW()  # create a read_write object
    read_write.read_file(
        raw_input('Enter file to read from: '
                  ))  # reads all the coordinates of citties from an ASCII file
    object.labels = read_write.labels  # store the labels in a list
    object.coordinates = read_write.coordinates  # store the coordinates in this list

    numRound = int(
        raw_input('Enter the number of random graphs you want to generate: '))
    roundTimes = int(
        raw_input('Enter the number of times you want to swap edges: '))

    for i in range(numRound):
        object.generate_rand_graph()  # generate a random graph
        for i in range(roundTimes):
            object.generate_rand_vertices(
            )  # randomly generate two indices which have no common connection
            object.find_random_edge(
            )  # generate two random edges from the given indices
            object.find_new_edge()  # find the new edge if swap were to happen.

            dx_oldtour = object.cal_distance_of_edge(
                object.edge1) + object.cal_distance_of_edge(
                    object.edge2
                )  # difference in cost before swapping using two-opt
            dx_newtour = object.cal_distance_of_edge(
                object.new_edge1) + object.cal_distance_of_edge(
                    object.new_edge2
                )  # difference in cost after adding two edges.
            if dx_newtour < dx_oldtour:
                object.remove_edges()
                object.add_edge_reversely()
        if object.costOfBestTour > object.costOfTour:
            bestTour = object.tour
            bestTour_vertices = object.tour_vertices
            object.costOfBestTour = object.costOfTour

    # write the tour in .tour ASCII file
    read_write.coordinates = []
    read_write.labels = []
    for i in bestTour_vertices:
        read_write.coordinates.append(i.pos)
    for i in bestTour_vertices:
        read_write.labels.append(i.label)
    read_write.write_file()

    print 'Run time: ', time.clock()

    # The following two lines allows to switch the layout of the graph displayed
    # layout = CartesianLayout(bestTour)
    layout = RandomLayout(bestTour)
    # layout = CircleLayout(bestTour)
    # draw the graph
    gw = GraphWorld()
    gw.show_graph(bestTour, layout)
    gw.mainloop()