Example #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
 def __init__(self, population_size, initialise, cities=None):
     self._tours = [None] * population_size
     if initialise:
         for i in xrange(population_size):
             new_tour = Tour()
             new_tour.generate(cities)
             self.save_tour(i, new_tour)
Example #3
0
def crossover(parent_1, parent_2):
    """ crossover subsections of parent 1 and left over cities from parent2 """
    from random import random

    child = Tour(parent_1.tour_manager)

    start_pos = (int)(random() * parent_1.size())
    end_pos = (int)(random() * parent_2.size())

    if start_pos > end_pos:
        temp_pos = start_pos
        start_pos = end_pos
        end_pos = temp_pos

    for i in range(0, child.size()):
        if i > start_pos and i < end_pos:
            child.set_city(i, parent_1.get_city(i))

    for i in range(0, parent_2.size()):
        if not child.contains_city(parent_2.get_city(i)):
            for j in range(0, child.size()):
                if child.get_city(j) is None:
                    child.set_city(j, parent_2.get_city(i))
                    break

    return child
Example #4
0
    def __init__(self, tourmanager, populationSize, initialise):
        self.tours = []
        for i in range(0, populationSize):
            self.tours.append(None)

        if initialise:
            for i in range(0, populationSize):
                newTour = Tour(tourmanager)
                newTour.generateIndividual()
                self.saveTour(i, newTour)
def crossover(parent_1, parent_2):
    """ crossover subsections of parent 1 and left over cities from parent2 """
    from random import random
    
    child = Tour(parent_1.tour_manager)
    
    start_pos = (int) (random() * parent_1.size())
    end_pos = (int) (random() * parent_2.size())
    
    if start_pos > end_pos:
        temp_pos = start_pos
        start_pos = end_pos
        end_pos = temp_pos
    
    for i in range(0, child.size()):
        if i > start_pos and i < end_pos:
            child.set_city(i, parent_1.get_city(i))
    
    for i in range(0, parent_2.size()):
        if not child.contains_city(parent_2.get_city(i)):
            for j in range(0, child.size()):
                if child.get_city(j) is None:
                    child.set_city(j, parent_2.get_city(i))
                    break
    
    return child
 def __init__(self, size, initialize, tour_manager):
     self._tours = []
     self.tour_manager = tour_manager
     
     if initialize:
         for i in range(0, size):
             tour = Tour(tour_manager)
             tour.generate_individual()
             self._tours.append(tour)
     else:
         for i in range(0, size):
             self._tours.append(None)
    def __init__(self, size, initialize, tour_manager):
        self._tours = []
        self.tour_manager = tour_manager

        if initialize:
            for i in range(0, size):
                tour = Tour(tour_manager)
                tour.generate_individual()
                self._tours.append(tour)
        else:
            for i in range(0, size):
                self._tours.append(None)
Example #8
0
 def gen_random_tours(self):
     tours = []
     tour = [i for i in range(self.number_of_towns)]
     for i in range(self.number_of_tours):
         shuffle(tour)
         tours.append(
             Tour(tour=tour, good_view=False, dist_matrix=self.dist_matrix))
     return tours
Example #9
0
    def __init__(self, population_size, graph, initialise=True):
        self.tours = []

        for _ in range(0, population_size):
            newTour = Tour(graph.number_of_cities())
            self.tours.append(newTour)
        if initialise:
            for tour in self.tours:
                tour.generate_individual(graph)
Example #10
0
 def __init__(self, tourcount, stadtcount):
     self.tourlist = []
     self.stadtlist = []
     self.stadtcount = stadtcount
     self.createStadtlist()
     self.minTour = self.minDist()
     self.maxTour = self.maxDist()
     for i in range(tourcount):
         self.addTour(Tour(deepcopy(self.stadtlist), self.maxTour))
Example #11
0
 def load(self, f):
     """Loads in the import data and returns a Tour instance"""
     open_file = open(f, "r")
     self.contents = open_file.read()
     # clean up and extrace the base data
     self.clean_up()
     # put together the src-dst array map
     self.parse_nodes()
     return Tour(self.tour_name, self.tour_nodes)
class EuropaTour(ConstructorTour):
    def construir_tour(self):
        self.tour = Tour("Europa")

    def agregar_hoteles(self):
        self.tour.add_hotel("Paris Inn")

    def agregar_lugares(self):
        self.tour.add_place("Torre Eiffel")
        self.tour.add_place("Louvre")
        self.tour.add_place("Arc de Triomphe")
def main():
    w = stdio.readInt()
    h = stdio.readInt()
    tour = Tour()
    while not stdio.isEmpty():
        x = stdio.readFloat()
        y = stdio.readFloat()
        p = Point(x, y)
        tour.insertSmallest(p)
    tour.show()
    stdio.writef('Tour distance = %f\n', tour.distance())
    stdio.writef('Number of points = %d\n', tour.size())
Example #14
0
    def create_piece(self):
        # pion
        y = 76
        x = 1
        for pion in range(8):
            pion = Pion("assets/pion_b.png", x, y)
            x += 75
            self.pion_b.append(pion)
        y = 451
        x = 1
        for pion in range(8):
            pion = Pion("assets/pion_n.png", x, y)
            x += 75
            self.pion_n.append(pion)

        # tour
        self.tour_b.append(Tour("assets/tour_b.png", 1, 1))
        self.tour_b.append(Tour("assets/tour_b.png", 526, 1))
        self.tour_n.append(Tour("assets/tour_n.png", 1, 526))
        self.tour_n.append(Tour("assets/tour_n.png", 526, 526))

        # cavalier
        self.cavalier_b.append(Cavalier("assets/cavalier_b.png", 76, 1))
        self.cavalier_b.append(Cavalier("assets/cavalier_b.png", 451, 1))
        self.cavalier_n.append(Cavalier("assets/cavalier_n.png", 76, 526))
        self.cavalier_n.append(Cavalier("assets/cavalier_n.png", 451, 526))

        # fou
        self.fou_b.append(Fou("assets/fou_b.png", 151, 1))
        self.fou_b.append(Fou("assets/fou_b.png", 376, 1))
        self.fou_n.append(Fou("assets/fou_n.png", 151, 526))
        self.fou_n.append(Fou("assets/fou_n.png", 376, 526))

        # roi
        self.roi_b.append(Roi("assets/roi_b.png", 226, 1))
        self.roi_n.append(Roi("assets/roi_n.png", 301, 526))

        # reine
        self.reine_b.append(Reine("assets/reine_b.png", 301, 1))
        self.reine_n.append(Reine("assets/reine_n.png", 226, 526))
Example #15
0
def path_search(path,
                added,
                deleted,
                lk_max_search_roads,
                lk_verbose=False,
                lk_depth_limit=None):
    """ Recursive part of search for an improved TSP solution. """
    depth = len(added)  # also = len(deleted)
    (old_tour_length, old_cities) = (path.tour_length(), path.city_sequence())
    results = [(old_tour_length, old_cities)]
    mods = path.find_lk_mods(lk_max_search_roads, added, deleted)

    if lk_verbose:
        print " " * depth + "  -- path_search " + \
              " depth=%i, path=%f, tour=%f, n_mods=%i " % \
              (depth, path.length, old_tour_length, len(mods))

    for (city, road_add, road_rm) in mods:

        if lk_verbose:
            print " " * depth + "  -> (city, road_add, road_rm) = (%s, %s, %s) " % \
                                (str(city), str(road_add), str(road_rm))

        path.modify(city, road_add, road_rm)

        if lk_verbose:
            print " " * depth + "  -> modified path %s " % str(path)

        added.append(road_add)
        deleted.append(road_rm)

        if lk_depth_limit and depth > lk_depth_limit:
            result_path = path
        else:
            result_path = path_search(path, list(added), list(deleted),
                                      lk_max_search_roads, lk_verbose,
                                      lk_depth_limit)
        results.append(
            (result_path.tour_length(), result_path.city_sequence()))

        if lk_verbose:
            print " " * depth + "  -> result path=%f; tour=%f" % \
                                (result_path.length, result_path.tour_length())

        added.pop()
        deleted.pop()

        path.unmodify(city, road_add, road_rm)

    # Finished breadth search at this depth ; return best result
    (best_length, best_city_seq) = min(results)
    return Tour(best_city_seq)
Example #16
0
 def __init__(self,tourcount,stadtcount):
     self.tourlist=[]
     self.stadtlist=[]
     self.stadtcount=stadtcount
     self.createStadtlist()
     self.minDist()
     self.maxDist()
     self.minTour=self.minDist()
     self.maxTour=self.maxDist()
     for i in range(tourcount):
         self.addTour(Tour(self.stadtlist))
     #neu
     print(self.fitness())
Example #17
0
def Main(inputFile):
    # Setup up our variables
    writeFile = "mytour"  # + ".tour"
    numIterations = 20
    cities = ReadCityData(inputFile)
    # start = time.time()
    graph = Graph(cities)  # Each edge of the graph has its own pheromones
    # print(time.time() - start)
    bestTour = Tour(cities[0])
    bestTour.tourLength = float('inf')

    # This is our algorithm
    for n in range(0, numIterations):
        print("Iteration", n + 1, "of", numIterations)
        # New ants are placed at each city every iteration
        ants = [Ant(cities, startCity) for startCity in cities]
        for ant in ants:
            while ant.hasNotCompletedTour:
                ant.moveToNextCity(graph)
            bestTour = ReturnBestTour(ant.tour, bestTour)
        graph.updatePheromones(ants, cities)
    OutputData(writeFile, bestTour)
    plotTour(cities, bestTour)  #may comment it out when submitting to Canvas
def main():
    w = stdio.readInt()
    h = stdio.readInt()
    stddraw.setCanvasSize(w, h)
    stddraw.setXscale(0, w)
    stddraw.setYscale(0, h)
    stddraw.setPenRadius(.005)
    tour = Tour()
    while not stdio.isEmpty():
        x = stdio.readFloat()
        y = stdio.readFloat()
        p = Point(x, y)
        tour.insertSmallest(p)
    stdio.writef('Tour distance = %f\n', tour.distance())
    stdio.writef('Number of points = %d\n', tour.size())
    tour.draw()
    stddraw.show()
Example #19
0
	def start_scrape(self, link='https://www.efultimatebreak.com/explore'):
		self.link = link
		driver = self.chromedriver.get_driver(self.link)
		if driver is None:
			print('ChromeDriver Error: Could not load link.')
			self.chromedriver.quit_driver(driver)
			return
		self.num_pages = self.get_num_pages(driver)
		self.chromedriver.quit_driver(driver)
		tour_links_infos_futures = [self.get_tour_links_infos_from_page(n) 
								for n in range(self.num_pages)]
		tour_links_infos_by_page = [future.result() for future in tour_links_infos_futures]
		self.tour_links_infos = []
		for page in tour_links_infos_by_page:
			self.tour_links_infos += page
		self.tours = [Tour(tour_link, tour_info, self.chromedriver) for tour_link, tour_info in self.tour_links_infos]
		_ = [tour.start_scrape() for tour in self.tours]
Example #20
0
 def gen_tours(self, chance):
     close_towns = [
         self.get_closes(self.dist_matrix[i])
         for i in range(self.number_of_towns)
     ]
     tours = []
     for i in range(self.number_of_tours):
         tour = []
         this = randint(0, self.number_of_towns - 1)
         tour.append(this)
         for _ in range(self.number_of_towns - 1):
             town = self.get_next_town(chance, close_towns[this], tour)
             tour.append(town)
         print(tour)
         tours.append(
             Tour(tour=tour, good_view=False, dist_matrix=self.dist_matrix))
     return tours
Example #21
0
class TwoOpt:
    def __init__(self, xy):
        self.tour = Tour(xy)

    def sequence(self, start=0):
        return range(start, self.tour.n)

    def improve_once(self):
        for si in self.sequence():
            igain = self.tour.next_length(si)
            for sj in self.sequence(si + 2):
                jgain = self.tour.next_length(sj)
                cost = self.tour.length(si, sj) + self.tour.length(
                    si + 1, sj + 1)
                improvement = igain + jgain - cost
                if improvement > 0:
                    #print("before: " + str(si) + ", " + str(sj))
                    #print("before: " + str(igain) + ", " + str(jgain))
                    #self.tour.plot()
                    #self.tour.plot_seq()
                    self.tour.swap(si, sj)
                    #print("after: " + str(cost))
                    #self.tour.plot("r^:")
                    #self.tour.show()
                    #sys.exit()
                    return improvement
        return 0

    def optimize(self):
        original = self.tour.tour_length()
        improvement = self.improve_once()
        while improvement > 0:
            improvement = self.improve_once()
        optimized = self.tour.tour_length()
        improvement = original - optimized
        assert (improvement >= 0)
        return improvement
Example #22
0
from boulet import Boulet

pygame.init()  # initialisation de pygame
gameDisplay = pygame.display.set_mode(
    (800, 600))  # Création de la fenetre de jeu
pygame.display.set_caption('Tower')  # Affectation du nom de la fenetre

clock = pygame.time.Clock()  # Démarrage de timer

#tour1 =Tour(10,10,gameDisplay)                      # création d une tour
#tour2=Tour(710,470,gameDisplay)                     # création d une tour
# création d un troll
boulets = []  # liste des boulets vide au départ
#les_explosions =[]
tours = []
une_tour = Tour(0, 0, gameDisplay)
image_fond = pygame.image.load("fond.png")

troll = Pion(16, 142, gameDisplay, image_fond)

fin = False

mode = "normal"

while not fin:  # boulcle du jeu

    for event in pygame.event.get():  # traitement des evenements
        if event.type == QUIT:
            fin = True
        elif event.type == MOUSEBUTTONDOWN:
Example #23
0
 def __init__(self, xy):
     self.tour = Tour(xy)
class CundinamarcaTour(ConstructorTour):
    def construir_tour(self):
        self.tour = Tour("Cundinamarca")

    def agregar_hoteles(self):
        self.tour.add_hotel("Bogotá Inn")
        self.tour.add_hotel("La Mesa Inn")
        self.tour.add_hotel("Zipa Inn")

    def agregar_lugares(self):
        self.tour.add_place("Bogotá")
        self.tour.add_place("La Mesa")
        self.tour.add_place("Zipaquirá")
Example #25
0
    def crossover(self, parent1, parent2):
        child = Tour(deepcopy(parent1.liste), self.maxTour)
        for i in range(child.getTourSize()):
            child.setStadt(None, i)

        startPos = randint(0, parent1.getTourSize() - 1)
        endPos = randint(0, parent1.getTourSize() - 1)

        for i in range(parent1.getTourSize()):
            if startPos < endPos and i > startPos and i < endPos:
                child.setStadt(parent1.getStadt(i), i)
            elif startPos > endPos:
                if not i < startPos and i > endPos:
                    child.setStadt(parent1.getStadt(i), i)
        for i in range(parent2.getTourSize()):
            if not child.istStadtvorhanden(parent2.getStadt(i)):
                for ii in range(parent1.getTourSize()):
                    if child.getStadt(ii) == None:
                        child.setStadt(parent2.getStadt(i), ii)
                        break
        return child
Example #26
0
 def generate_random_population(size, cities):
     random_population = Population()
     for i in range(size):
         random_population.add(Tour.generate_random_tour(cities))
     return random_population
 def construir_tour(self):
     self.tour = Tour("Cundinamarca")
 def construir_tour(self):
     self.tour = Tour("Europa")
Example #29
0
    def crossover(self, parent1, parent2):
        child = Tour(self.tourmanager)

        startPos = int(random.random() * parent1.tourSize())
        endPos = int(random.random() * parent1.tourSize())

        for i in range(0, child.tourSize()):
            if startPos < endPos and i > startPos and i < endPos:
                child.setCity(i, parent1.getCity(i))
            elif startPos > endPos:
                if not (i < startPos and i > endPos):
                    child.setCity(i, parent1.getCity(i))

        for i in range(0, parent2.tourSize()):
            if not child.containsCity(parent2.getCity(i)):
                for ii in range(0, child.tourSize()):
                    if child.getCity(ii) == None:
                        child.setCity(ii, parent2.getCity(i))
                        break

        return child
    def __init__(self, window, cities_list, show_window=True):
        if show_window:
            self.ini = window.figure.add_subplot(211)
            self.end = window.figure.add_subplot(212)

        self._cities_list = cities_list

        current_solution = Tour()
        current_solution.generate(self._cities_list)
        if show_window:
            self.plt_reload(211, current_solution.get_tour(), self._temp)

        print 'Initial distance: ', current_solution.get_distance()
        self.x_graph.append(0)
        self.y_graph.append(current_solution.get_distance())

        best = Tour(current_solution)

        while self._temp > 1:
            new_solution = Tour(current_solution)

            # swap cities
            self.swap_solution(new_solution)

            # reverse slide of list
            self.reverse_solution(new_solution)

            # translate slice of list
            self.translate_solution(new_solution)

            current_energy = current_solution.get_distance()
            neighbour_energy = new_solution.get_distance()

            if self.acceptance_probability(current_energy, neighbour_energy, self._temp) > random():
                current_solution = new_solution

            if current_solution.get_distance() < best.get_distance():
                best = current_solution
                if show_window:
                    self.plt_reload(212, new_solution.get_tour(), self._temp)
                self.x_graph.append(self.x_graph[-1] + 1)
                self.y_graph.append(new_solution.get_distance())

            self._temp *= (1 - self._cooling_rate)

        print 'Final distance: %.4f' % (best.get_distance())
        if show_window:
            self.plt_reload(212, best.get_tour(), self._temp)
        self.x_graph.append(self.x_graph[-1] + 1)
        self.y_graph.append(best.get_distance())
        self.best_distance = best.get_distance()
Example #31
0
for i in range(50):
    print("iteration: " + str(i))
    new_edges = mst.get_new_mst_edges(t.tour, mst_edges)
    improved = False
    ee = random.sample(new_edges, simultaneous_edges)
    for e in ee:
        m = basic.midpoint(xy, e[0], e[1])
        t.tour.insert_new_node(m)
    t.optimize()
    for _ in ee:
        t.tour.remove_last_xy()
    t.optimize()
    new_length = t.tour.tour_length()
    if new_length < best_length:
        best_length = new_length
        best = t.tour.node_ids[:]
        print("best length: " + str(best_length))
        improved = True
    else:
        t.tour.reset(best)
    if not improved:
        opt_tour = Tour(xy)
        opt = reader.read_tour("input/berlin52.opt.tour")
        opt_tour.reset(opt)
        opt_tour.plot()
        #t.tour.plot()
        plot.plot_edges(t.tour, new_edges, "g:^")
        t.tour.show()

Example #32
0
    def crossover(self, parent1, parent2):
        child = Tour(len(self._cities_list))

        start_pos = int(random.random() * parent1.tour_size())
        end_pos = int(random.random() * parent1.tour_size())

        for i in xrange(child.tour_size()):
            if start_pos < end_pos and i > start_pos and i < end_pos:
                child.set_city(i, parent1.get_city(i))
            elif start_pos > end_pos:
                if not (i < start_pos and i > end_pos):
                    child.set_city(i, parent1.get_city(i))

        for i in xrange(parent2.tour_size()):
            if not child.contains_city(parent2.get_city(i)):
                for j in xrange(child.tour_size()):
                    if not child.get_city(j):
                        child.set_city(j, parent2.get_city(i))
                        break

        return child
    def crossover(self, parent1, parent2):
        child = Tour(len(self._cities_list))

        start_pos = int(random.random() * parent1.tour_size())
        end_pos = int(random.random() * parent1.tour_size())

        for i in xrange(child.tour_size()):
            if start_pos < end_pos and i > start_pos and i < end_pos:
                child.set_city(i, parent1.get_city(i))
            elif start_pos > end_pos:
                if not (i < start_pos and i > end_pos):
                    child.set_city(i, parent1.get_city(i))

        for i in xrange(parent2.tour_size()):
            if not child.contains_city(parent2.get_city(i)):
                for j in xrange(child.tour_size()):
                    if not child.get_city(j):
                        child.set_city(j, parent2.get_city(i))
                        break

        return child
Example #34
0
def knight():
    """The user interface function that creates an instance of the Tour class to modify the tour based
    on the users input

        :param          None
        :post           Uses the instance map1 to access the Tour class and its functions
        :complexity:    best case: O(1), worst case: O(n^3)"""
    map1 = Tour()
    while (True):
        try:
            userinput = int(
                input("[1] Position\n[2] Quit\n[3] Move\n[4] Undo\n"
                      "[5] Save\n[6] Load save\nInput: "))
        except ValueError:
            print("Error! You did not enter a proper integer")
            continue

        if userinput == 1:
            map1.show_tour()

        elif userinput == 2:
            return

        elif userinput == 3:
            validMove = False
            while validMove == False:
                try:
                    xinput = int(input("enter x "))
                    yinput = int(input("enter y "))
                except ValueError:
                    print("Error! You did not input a proper data type")
                    continue

                if map1.valid_move((xinput, yinput)) is True:
                    print('successful move')
                    map1.move_knight(xinput, yinput)
                    validMove = True
                else:
                    print('invalid move')

        elif userinput == 4:
            map1.undo()

        elif userinput == 5:
            saveData = map1.copy()
            #print(saveData.the_array)

        elif userinput == 6:
            try:
                map1.set(saveData)
            except UnboundLocalError:
                print("No save data!")
    return
Example #35
0
    if (new_energy < energy):
        return 1.0
    # Calculate an acceptance probability if the new solution is worse.
    return math.exp((energy - new_energy) / current_temp)


grid_size = 1000
number_of_cities = 48
temperature = 100000
cooling_rate = 0.003
stopping_temperature = 1e-4
stopping_iter = 100000
iteration_number = 1

# Initalize starting values
current_tour = Tour(number_of_cities, grid_size)
current_tour.init_city_list()
current_tour.init_tour_list()
best_solution = copy.deepcopy(current_tour)

distance_timeseries = [best_solution.tour_distance]
solution_timeseries = [best_solution.tour_list]

print("Initial tour distance: " + str(best_solution.tour_distance))

# Initalize figure and plot the points
fig1 = plt.figure(1)
ax = plt.axes(title="TSP", xlim=(0, grid_size), ylim=(0, grid_size))
plt.plot([t.x for t in best_solution.city_list],
         [t.y for t in best_solution.city_list], "ro")