a3-algorithmique-avancee/tests/02_cluster_recuit_live_animation.py

108 lines
3.8 KiB
Python

from sklearn.cluster import KMeans
import matplotlib.pyplot as plt
import numpy as np
import random, time, math
from clustering import split_tour_across_clusters
random.seed(1)
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)
def total_distance(cities):
return sum([distance(cities[i - 1], cities[i]) for i in range(len(cities))])
previous_route = None
def draw_cities(cities, previous_route, color='b', title=' '):
plt.title(title)
# If there's a previous route, we remove it.
if previous_route is not None:
previous_route.remove()
x = [city[0] for city in cities]
y = [city[1] for city in cities]
x.append(x[0])
y.append(y[0])
# We plot the route with the specified color and keep a reference to the Line2D object.
previous_route, = plt.plot(x, y, color=color, marker='x', linestyle='-')
plt.draw()
plt.pause(0.005)
# We return the reference so we can remove this route when a new one is found.
return previous_route
def simulated_annealing(cities, color='b', temperature=100000, cooling_rate=0.9999, temperature_ok=0.001):
interration = 0
plt.ion()
current_solution = cities.copy()
best_solution = cities.copy()
previous_route = draw_cities(best_solution, None, color, 'Initial solution')
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
previous_route = draw_cities(best_solution, previous_route, color, 'Current best solution, total distance = ' + str(total_distance(best_solution)) + ', iteration = ' + str(interration))
# Cool down
temperature *= cooling_rate
interration += 1
plt.ioff()
return best_solution
nb_ville = 100
max_coords = 1000
nb_truck = 4
temperature = 10000
cooling_rate = 0.999
temperature_ok = 0.000001
start_time_generate = time.time()
cities = generate_cities(nb_ville, max_coords) # generate 100 cities
cities[0] = [max_coords/2, max_coords/2] # placing depot at the center
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 = ['b', 'g', 'r', 'c', 'm', 'y', 'k']
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 simulated_annealing avec la couleur choisie
best_route = simulated_annealing(cluster_cities, color, temperature, cooling_rate, temperature_ok)
print("Final solution for cluster ", i, ":", best_route)
print("Total distance: ", total_distance(best_route))
plt.show()