diff --git a/tests/05_cluster_ant_colony_recuit_no_animation.py b/tests/05_cluster_ant_colony_recuit_no_animation.py new file mode 100644 index 0000000..53b4db1 --- /dev/null +++ b/tests/05_cluster_ant_colony_recuit_no_animation.py @@ -0,0 +1,166 @@ +from sklearn.cluster import KMeans +import matplotlib.pyplot as plt +import numpy as np +import random, time, math +from libs.clustering import split_tour_across_clusters + +random.seed(3) + +def generate_cities(nb, max_coords=1000): + return [random.sample(range(max_coords), 2) for _ in range(nb)] + +def distance(city1, city2): + return math.sqrt((city1[0] - city2[0]) ** 2 + (city1[1] - city2[1]) ** 2) + 1e-10 + +def total_distance(cities): + return sum([distance(cities[i - 1], cities[i]) for i in range(len(cities))]) + +class AntColony: + def __init__(self, cities, n_ants, alpha=1, beta=2, evaporation=0.5, intensification=2, max_time=0.1): + self.cities = cities + self.n = len(cities) + self.n_ants = n_ants + self.alpha = alpha + self.beta = beta + self.evaporation = evaporation + self.intensification = intensification + self.max_time = max_time + self.pheromones = [[1 / self.n for _ in range(self.n)] for __ in range(self.n)] + + def choose_next_city(self, ant): + unvisited_cities = [i for i in range(self.n) if i not in ant] + probabilities = [self.pheromones[ant[-1]][i] ** self.alpha * ((1 / distance(self.cities[ant[-1]], self.cities[i])) ** self.beta) for i in unvisited_cities] + total = sum(probabilities) + if total == 0: + probabilities = [1 / len(unvisited_cities) for _ in unvisited_cities] + else: + probabilities = [p / total for p in probabilities] + return np.random.choice(unvisited_cities, p=probabilities) + + def update_pheromones(self, ant): + pheromones_delta = self.intensification / total_distance([self.cities[i] for i in ant]) + for i in range(len(ant) - 1): + self.pheromones[ant[i]][ant[i+1]] += pheromones_delta + + def run(self): + best_ant = [] + best_distance = float('inf') + start_time = time.time() + while time.time() - start_time < self.max_time: + ants = [[random.randint(0, self.n - 1)] for _ in range(self.n_ants)] + for ant in ants: + for _ in range(self.n - 1): + ant.append(self.choose_next_city(ant)) + ant_distance = total_distance([self.cities[i] for i in ant]) + if ant_distance < best_distance: + best_distance = ant_distance + best_ant = ant.copy() + self.update_pheromones(ant) + self.pheromones = [[(1 - self.evaporation) * p for p in row] for row in self.pheromones] + return [self.cities[i] for i in best_ant] + +def simulated_annealing(cities, temperature=10000, cooling_rate=0.9999, temperature_ok=0.1): + interration = 0 + current_solution = cities.copy() + best_solution = cities.copy() + while temperature > temperature_ok: + new_solution = current_solution.copy() + # Swap two cities in the route + i = random.randint(0, len(new_solution) - 1) + j = random.randint(0, len(new_solution) - 1) + new_solution[i], new_solution[j] = new_solution[j], new_solution[i] + # Calculate the acceptance probability + current_energy = total_distance(current_solution) + new_energy = total_distance(new_solution) + delta = new_energy - current_energy + if delta < 0 or random.random() < math.exp(-delta / temperature): + current_solution = new_solution + if total_distance(current_solution) < total_distance(best_solution): + best_solution = current_solution + # Cool down + temperature *= cooling_rate + interration += 1 + return best_solution + +nb_ville = 50 +max_coords = 1000 +nb_truck = 2 +max_time = 3 +nb_ants = 10 + +max_time_per_cluster = max_time / nb_truck + +start_time_generate = time.time() +cities = generate_cities(nb_ville, max_coords) +cities[0] = [max_coords/2, max_coords/2] +stop_time_generate = time.time() + +start_time_split = time.time() +clusters = split_tour_across_clusters(cities, nb_truck) +stop_time_split = time.time() + +for cluster in clusters.values(): + print(len(cluster)) +print("\n---- TIME ----") +print("generate cities time: ", stop_time_generate - start_time_generate) +print("split cities time: ", stop_time_split - start_time_split) + +# create new figure for annealing paths +plt.figure() +colors = [ + '#1f77b4', # Bleu moyen + '#ff7f0e', # Orange + '#2ca02c', # Vert + '#d62728', # Rouge + '#9467bd', # Violet + '#8c564b', # Marron + '#e377c2', # Rose + '#7f7f7f', # Gris + '#bcbd22', # Vert olive + '#17becf', # Turquoise + '#1b9e77', # Vert Teal + '#d95f02', # Orange foncé + '#7570b3', # Violet moyen + '#e7298a', # Fuchsia + '#66a61e', # Vert pomme + '#e6ab02', # Jaune or + '#a6761d', # Bronze + '#666666', # Gris foncé + '#f781bf', # Rose clair + '#999999', # Gris moyen +] + +best_routes = [] + +for i, cluster_indices in enumerate(clusters.values()): + # Sélection d'une couleur pour le cluster + color = colors[i % len(colors)] + + # Récupération des coordonnées de la ville + cluster_cities = [cities[index] for index in cluster_indices] + + # Appel de la fonction AntColony.run + ant_colony = AntColony(cluster_cities, n_ants=nb_ants, max_time=max_time_per_cluster) + best_route = ant_colony.run() + best_route = simulated_annealing(best_route) + best_routes.append((best_route, color)) + + print("Total distance for cluster", i, ": ", total_distance(best_route)) + +# calculate total distance for all clusters +full_total_distance = 0 +for route, color in best_routes: + full_total_distance += total_distance(route) + +print("Total distance for all clusters: ", full_total_distance) + +for i, (route, color) in enumerate(best_routes): + x = [city[0] for city in route] + y = [city[1] for city in route] + x.append(x[0]) + y.append(y[0]) + plt.plot(x, y, color=color, marker='x', linestyle='-', label=f"Cluster {i}") + # add title with nb_ville, nb_truck and max_time + plt.title(f"nb_ville = {nb_ville}, nb_truck = {nb_truck}, max_time = {max_time}") + +plt.show() \ No newline at end of file