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)
예제 #2
0
    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()