-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcomplete.py
More file actions
271 lines (203 loc) · 8.45 KB
/
complete.py
File metadata and controls
271 lines (203 loc) · 8.45 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
import tsplib95
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import time
from ortools.sat.python import cp_model
from ortools.constraint_solver import routing_enums_pb2
from ortools.constraint_solver import pywrapcp
OPTIMUMS = {
'burma14': 3323,
'eil51': 426,
'kroA100': 21282,
}
def charger_instance(fichier):
"""Charge un fichier TSPLIB"""
probleme = tsplib95.load(fichier)
villes = list(probleme.get_nodes())
n = len(villes)
distances = np.zeros((n, n), dtype=int)
for i, vi in enumerate(villes):
for j, vj in enumerate(villes):
if i != j:
distances[i][j] = int(probleme.get_weight(vi, vj))
else:
distances[i][j] = 999999999
nom = fichier.replace('.tsp', '').split('/')[-1].split('\\')[-1]
return {
'nom': nom,
'n': n,
'distances': distances,
'optimum': OPTIMUMS.get(nom, None)
}
class SolveursComplets:
def __init__(self, distances):
self.dist = np.array(distances)
self.n = len(distances)
def cpsat(self, temps_limite=300, workers=1):
"""
CP-SAT : Solveur de Programmation par Contraintes
Paramètres :
- temps_limite : temps maximum de recherche (secondes)
- workers : nombre de threads (1 = séquentiel, 8 = parallèle)
"""
model = cp_model.CpModel()
arcs = {}
for i in range(self.n):
for j in range(self.n):
if i != j:
arcs[i, j] = model.NewBoolVar(f'arc_{i}_{j}')
model.AddCircuit([(i, j, arcs[i, j]) for i, j in arcs])
model.Minimize(sum(self.dist[i][j] * arcs[i, j] for i, j in arcs))
solveur = cp_model.CpSolver()
solveur.parameters.max_time_in_seconds = temps_limite
solveur.parameters.num_search_workers = workers
debut = time.time()
statut = solveur.Solve(model)
duree = time.time() - debut
return {
'methode': f'CP-SAT (workers={workers})',
'parametres': {'temps_limite': temps_limite, 'workers': workers},
'temps': duree,
'statut': solveur.StatusName(statut),
'distance': int(solveur.ObjectiveValue()) if statut in [cp_model.OPTIMAL, cp_model.FEASIBLE] else None,
'optimal': statut == cp_model.OPTIMAL
}
def nearest_neighbor(self, temps_limite=300):
manager = pywrapcp.RoutingIndexManager(self.n, 1, 0)
routing = pywrapcp.RoutingModel(manager)
dist = self.dist
def callback(i, j):
return int(dist[manager.IndexToNode(i)][manager.IndexToNode(j)])
idx = routing.RegisterTransitCallback(callback)
routing.SetArcCostEvaluatorOfAllVehicles(idx)
params = pywrapcp.DefaultRoutingSearchParameters()
params.first_solution_strategy = routing_enums_pb2.FirstSolutionStrategy.PATH_CHEAPEST_ARC
params.time_limit.seconds = temps_limite
debut = time.time()
solution = routing.SolveWithParameters(params)
duree = time.time() - debut
return {
'methode': 'Plus Proche Voisin',
'parametres': {'strategie': 'PATH_CHEAPEST_ARC', 'temps_limite': temps_limite},
'temps': duree,
'distance': int(solution.ObjectiveValue()) if solution else None,
'statut': 'OK' if solution else 'NO_SOLUTION',
'optimal': False
}
def guided_local_search(self, temps_limite=300):
manager = pywrapcp.RoutingIndexManager(self.n, 1, 0)
routing = pywrapcp.RoutingModel(manager)
dist = self.dist
def callback(i, j):
return int(dist[manager.IndexToNode(i)][manager.IndexToNode(j)])
idx = routing.RegisterTransitCallback(callback)
routing.SetArcCostEvaluatorOfAllVehicles(idx)
params = pywrapcp.DefaultRoutingSearchParameters()
params.first_solution_strategy = routing_enums_pb2.FirstSolutionStrategy.PATH_CHEAPEST_ARC
params.local_search_metaheuristic = routing_enums_pb2.LocalSearchMetaheuristic.GUIDED_LOCAL_SEARCH
params.time_limit.seconds = temps_limite
debut = time.time()
solution = routing.SolveWithParameters(params)
duree = time.time() - debut
return {
'methode': 'Guided Local Search',
'parametres': {'metaheuristique': 'GLS', 'temps_limite': temps_limite},
'temps': duree,
'distance': int(solution.ObjectiveValue()) if solution else None,
'statut': 'OK' if solution else 'NO_SOLUTION',
'optimal': False
}
def executer_benchmark(fichiers_tsp, temps_limite=60):
resultats = []
for fichier in fichiers_tsp:
print(f"\n{'='*60}")
print(f" {fichier}")
print('='*60)
try:
instance = charger_instance(fichier)
except Exception as e:
print(f"❌ Erreur : {e}")
continue
nom = instance['nom']
n = instance['n']
optimum = instance['optimum']
print(f"Villes : {n} | Optimum connu : {optimum}")
print("-" * 40)
solveur = SolveursComplets(instance['distances'])
methodes = [
lambda: solveur.cpsat(temps_limite=temps_limite, workers=8),
lambda: solveur.nearest_neighbor(temps_limite=temps_limite),
lambda: solveur.guided_local_search(temps_limite=temps_limite),
]
for methode in methodes:
res = methode()
res['instance'] = nom
res['n'] = n
res['optimum'] = optimum
if res['distance'] and optimum:
res['gap'] = ((res['distance'] - optimum) / optimum) * 100
else:
res['gap'] = None
resultats.append(res)
dist = res['distance'] if res['distance'] else 'N/A'
gap = f"{res['gap']:.2f}%" if res['gap'] is not None else '-'
opt = "✓ OPTIMAL" if res.get('optimal') else ""
print(f" {res['methode']:25} | {dist:>8} | gap: {gap:>8} | {res['temps']:.2f}s {opt}")
return pd.DataFrame(resultats)
def generer_rapport(df):
print("\n" + "="*60)
print("📊 RAPPORT")
print("="*60)
print("\nTABLEAU RÉCAPITULATIF\n")
tableau = df.pivot_table(
values=['distance', 'gap', 'temps'],
index='instance',
columns='methode',
aggfunc='first'
)
print(tableau.round(2).to_string())
# Graphiques
fig, axes = plt.subplots(1, 2, figsize=(12, 5))
# Gap
ax = axes[0]
pivot = df.pivot_table(values='gap', index='instance', columns='methode')
pivot.plot(kind='bar', ax=ax, color=['#2ecc71', '#3498db', '#e74c3c'])
ax.set_title('Gap par rapport à l\'optimum (%)', fontweight='bold', fontsize=12)
ax.set_ylabel('Gap (%)')
ax.set_xlabel('')
ax.legend(title='', fontsize=9)
ax.tick_params(axis='x', rotation=0)
ax.axhline(y=0, color='green', linestyle='--', alpha=0.5)
# Temps
ax = axes[1]
pivot = df.pivot_table(values='temps', index='instance', columns='methode')
pivot.plot(kind='bar', ax=ax, color=['#2ecc71', '#3498db', '#e74c3c'])
ax.set_title('Temps d\'exécution (secondes)', fontweight='bold', fontsize=12)
ax.set_ylabel('Temps (s)')
ax.set_xlabel('')
ax.legend(title='', fontsize=9)
ax.tick_params(axis='x', rotation=0)
plt.tight_layout()
plt.savefig('resultats.png', dpi=150)
print("\nGraphique sauvegardé : resultats.png")
plt.show()
# Classement
print("\nCLASSEMENT (par gap moyen)")
classement = df.groupby('methode')['gap'].mean().sort_values()
for rang, (m, g) in enumerate(classement.items(), 1):
print(f" {rang}. {m}: {g:.2f}%")
if __name__ == "__main__":
FICHIERS = [
'tsplib-master/burma14.tsp',
'tsplib-master/eil51.tsp',
'tsplib-master/kroA100.tsp',
]
TEMPS_LIMITE = 60
print("BENCHMARK TSP - MÉTHODES COMPLÈTES")
print("="*60)
df = executer_benchmark(FICHIERS, TEMPS_LIMITE)
df.to_csv('resultats.csv', index=False)
print("\nCSV sauvegardé : resultats.csv")
generer_rapport(df)
print("\nTERMINÉ !")