Beispiel #1
0
def tour_improve(tour,
                 lk_max_search_roads,
                 lk_verbose=False,
                 lk_depth_limit=None):
    """ loop over roads ; convert tour to path
        and then start Lin-Kernighan-ish algorithm. """
    (best_length, best_cities) = (tour.tour_length(), tour.city_sequence())

    loop_roads = set(tour)  # loop over a duplicate; tour will be modified.
    print "===== starting tour_improve with %i paths to check" % (
        2 * len(loop_roads))
    i = 0
    best_iteration = 0
    for road in loop_roads:
        for backward in (True, False):
            i += 1
            tour.revert()
            tour.tour2path(road, backward)
            print "---- calling %i path_search on %s " % (i, str(tour))
            tour2 = path_search(tour, [], [], lk_max_search_roads, lk_verbose,
                                lk_depth_limit)
            print "---- done path_search; found length=%f" % tour2.tour_length(
            )
            if tour2.tour_length() < best_length:
                best_length = tour2.tour_length()
                best_cities = tour2.city_sequence()
                best_iteration = i
            best_tour = Tour(best_cities)
            best_tour.plot_paths(i, best_iteration)
    print "===== finished tour_improve; best is %s " % str(best_tour)
    return best_tour, best_iteration
Beispiel #2
0
cmdopt = vars(args)
neighbors = cmdopt.get('neighbors')
dsfile = cmdopt.get('file')
depth = cmdopt.get('depth')
verbose = cmdopt.get('verbose')

cities = []
with open(dsfile) as datasetFile:
    dataset = csv.reader(datasetFile, delimiter=',')
    for row in dataset:
        cities.append(City(row[0], int(row[1]), int(row[2])))
random.shuffle(cities)
Tour.init_roads(cities)
tour = Tour(cities)
answer = 'Y'
while answer in ['Yes', 'yes', 'YES', 'y', 'Y']:
    tour.plot_cities()
    begin = time.time()
    tour, iteration = tour_improve(tour, neighbors, verbose, depth)
    end = time.time()
    duration = end - begin
    print "Iterations took ", duration, " seconds."
    tour.plot_paths(2 * len(tour), iteration, True, True)
    answer = raw_input("Try to improve this tour ? [Y/N] (default No) : ")
    if answer in ['Yes', 'yes', 'YES', 'y', 'Y']:
        neighbors_in = raw_input(
            "Set a new value for neighbors count (default = actual = " +
            str(neighbors) + ') : ')
        if neighbors_in:
            neighbors = int(neighbors_in)