class SimulatedAnnealing: def __init__(self, destinations, initial_temperature=1000, cooling_rate=0.003, use_heuristic=True): self.use_heuristic = use_heuristic self.dictionary = {} self.route_controller = destinations self.route = Route(destinations) self.route.generate_route() self.best = self.route self.temperature = initial_temperature self.cooling_rate = cooling_rate self.iterations = 0 def acceptance_function(self, energy_delta): if energy_delta < 0: return True elif random.random() <= math.exp(-(energy_delta) / self.temperature): return True return False def new_route(self): new_route = Route(self.route_controller, self.route) pos1 = random.randint(1, self.route.route_lenght() - 1) pos2 = random.randint(1, self.route.route_lenght() - 1) cord1 = new_route.get_cord(pos1) cord2 = new_route.get_cord(pos2) new_route.set_Coordinate(pos2, cord1) new_route.set_Coordinate(pos1, cord2) actual_energy = self.route.get_distance(self.dictionary, self.use_heuristic) new_energy = new_route.get_distance(self.dictionary, self.use_heuristic) delta = new_energy - actual_energy if self.acceptance_function(delta): self.route = new_route if new_route.get_distance(self.dictionary, self.use_heuristic) < self.best.get_distance( self.dictionary, self.use_heuristic): self.best = new_route print(new_route.get_distance(), self.use_heuristic) def run(self): print("Corriendo algoritmo") while self.temperature > 1: self.iterations = self.iterations + 1 self.new_route() self.temperature *= 1 - self.cooling_rate print("La cantidad de iteraciones que dio es de : ", self.iterations) self.resetDictionary() print("Termino algoritmo") def resetDictionary(self): self.dictionary = {}