-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.py
331 lines (250 loc) · 10.8 KB
/
main.py
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
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
import math
import time
import random
import pandas
import matplotlib.pyplot as plt
from copy import deepcopy
def generation(n): # Generate a list of random coordinates (nodes) with a specified length.
gen = []
while len(gen) != n:
node = (random.randint(0, 200), random.randint(0, 200))
if node not in gen:
gen.append(node)
gen.append(gen[0])
return gen
def plot_start(name): # Initialize a new plot for visualization.
plt.ion()
plt.figure(figsize=(8, 8), num=name)
def plot_update(data, specific): # Update the plot with specified data.
x2, y2, y3, y4, road = zip(*data)
for i in range(len(road)):
x1, y1 = zip(*(road[i]))
plt.clf()
plt.subplot(2, 2, 1)
plt.scatter(x1, y1)
plt.plot(x1, y1, color='red')
plt.title(f'TOWNS: {len(x1) - 1}')
plt.subplot(2, 2, 2)
plt.plot(x2[:i+1], y2[:i+1], color='red')
plt.title(f'DISTANCE: {y2[i]}')
plt.xlabel('ITERATION')
plt.ylabel('DISTANCE')
plt.subplot(2, 2, 3)
plt.plot(x2[:i+1], y3[:i+1], color='red')
plt.title(f'{specific}: {y3[i]}')
plt.xlabel('ITERATION')
plt.ylabel(specific)
plt.subplot(2, 2, 4)
plt.plot(x2[:i+1], y4[:i+1], color='red')
plt.title(f'THRESHOLD: {y4[i]}')
plt.xlabel('ITERATION')
plt.ylabel('THRESHOLD')
plt.tight_layout()
plt.pause(0.01)
plt.draw()
plt.pause(10)
plt.close()
def distance(path): # Calculate the total distance of a path connecting a series of points.
dist = 0
for j in range(1, len(path)):
dist = dist + math.sqrt((path[j][0] - path[j - 1][0]) ** 2 + (path[j][1] - path[j - 1][1]) ** 2)
return dist
def tabu(path, max_threshold=25, tabu_size=25): # Solve the Traveling Salesman Problem using Tabu Search.
def neighborhood_swap(entry): # Inner function for generating list of all neighbors solutions by swapping cities
neighbor_list = []
for i in range(1, len(entry) - 1):
for j in range(i + 1, len(entry) - 1):
swap = deepcopy(entry)
swap[i], swap[j] = swap[j], swap[i]
neighbor_list.append(swap)
return neighbor_list
def neighborhood_2opt(entry): # Inner function for generating list of all neighbors solutions using 2-opt technique
neighbor_list = []
for i in range(1, len(entry) - 2):
for j in range(i + 2, len(entry)):
opt = entry[:i] + entry[i:j][::-1] + entry[j:]
neighbor_list.append(opt)
return neighbor_list
threshold = 0
tabu_list = [path]
best_solution, best_candidate = path, path
data = [(1, round(distance(best_solution), 3), len(tabu_list), threshold, best_solution)]
while threshold < max_threshold:
if random.random() > 0.5:
neighbors = neighborhood_swap(best_candidate)
else:
neighbors = neighborhood_2opt(best_candidate)
best_candidate = neighbors[0]
for neighbor in neighbors:
if (neighbor not in tabu_list) and (distance(neighbor) < distance(best_candidate)):
best_candidate = neighbor
if distance(best_candidate) < distance(best_solution):
best_solution = best_candidate
threshold = 0
else:
threshold += 1
tabu_list.append(best_candidate)
if len(tabu_list) > tabu_size:
tabu_list.pop(0)
data.append((len(data) + 1, round(distance(best_solution), 3), len(tabu_list), threshold, best_solution))
return data
def simulated_annealing(path, alpha=0.995, temperature=3): # Solve the Traveling Salesman Problem using Simulated Annealing.
def random_neighbor_swap(entry): # Inner function for generating a new path by swapping two random cities.
new_path = deepcopy(entry)
x, y = 0, 0
while x == y:
x = random.randint(1, len(entry) - 2)
y = random.randint(1, len(entry) - 2)
new_path[x], new_path[y] = new_path[y], new_path[x]
return new_path
def random_neighbor_shuffle(entry): # Inner function for generating a new path by shuffling a random segment of cities.
new_path = deepcopy(entry)
x, y = 0, 0
while x == y:
x = random.randint(1, len(entry) - 2)
y = random.randint(1, len(entry) - 2)
shuffle = new_path[min(x, y):max(x, y) + 1]
random.shuffle(shuffle)
return new_path[:min(x, y)] + shuffle + new_path[max(x, y) + 1:]
def random_neighbor_inverse(entry): # Inner function for generating a new path by inverting the order of a random segment of cities.
new_path = deepcopy(entry)
x, y = 0, 0
while x == y:
x = random.randint(1, len(entry) - 2)
y = random.randint(1, len(entry) - 2)
new_path[min(x, y):max(x, y) + 1] = new_path[min(x, y):max(x, y) + 1][::-1]
return new_path
def random_neighbor_insert(entry): # Inner function for generating a new path by inserting a random city at a random position.
new_path = deepcopy(entry)
x, y = 0, 0
while x == y:
x = random.randint(1, len(entry) - 2)
y = random.randint(1, len(entry) - 2)
temp = new_path[x]
new_path.pop(x)
new_path.insert(y, temp)
return new_path
threshold = 0
max_threshold = 8 * len(path)
max_one_temp = 18 * len(path)
best_solution = path
data = [(1, round(distance(best_solution), 3), round(temperature, 3), threshold, best_solution)]
while threshold < max_threshold:
choice = random.choice([1, 2, 3, 4])
if choice == 1:
candidate = random_neighbor_swap(best_solution)
elif choice == 2:
candidate = random_neighbor_insert(best_solution)
elif choice == 3:
candidate = random_neighbor_shuffle(best_solution)
else:
candidate = random_neighbor_inverse(best_solution)
delta = distance(best_solution) - distance(candidate)
for i in range(max_one_temp):
if delta > 0:
best_solution = candidate
threshold = 0
elif delta < 0:
prob = math.exp(delta/temperature)
if random.random() < prob:
best_solution = candidate
threshold = 0
if len(data) > 0:
if data[-1][1] == round(distance(best_solution), 3):
threshold += 1
temperature *= alpha
data.append((len(data) + 1, round(distance(best_solution), 3), round(temperature, 3), threshold, best_solution))
return data
def ask_number(n): # Prompt the user to input an iteration number.
while True:
try:
decision_number = int(input("What iteration to choose: ")) - 1
except ValueError:
print("Enter integer")
continue
if n > decision_number >= 0:
return decision_number
else:
print("Integer out of range")
def avg(lst, n): # Calculate the average of a list of values.
temp = 0
for i in range(n):
temp += lst[i][1]
return temp/n
def test(n, towns, incremental=False): # Perform multiple iterations of solving the Traveling Salesman Problem and provide analysis.
results = []
for i in range(n):
start = generation(towns)
time_start1 = time.time()
data1 = tabu(start)
time_end1 = time.time()
time_start2 = time.time()
data2 = simulated_annealing(start)
time_end2 = time.time()
results.append((data1, round(time_end1 - time_start1, 3), data2, round(time_end2 - time_start2, 3)))
if incremental:
print(towns)
towns += 1
df = pandas.DataFrame(results, columns=["tabu", "tabu_time", "sa", "sa_time"])
df.to_csv('output/results.csv', index=False)
tabu_df = []
sa_df = []
for i in range(0, n):
tabu_df.append([pandas.DataFrame(df.tabu.at[i], columns=['iteration', 'distance', 'tabu_list', 'threshold', 'path']), df.tabu_time.at[i]])
sa_df.append([pandas.DataFrame(df.sa.at[i], columns=['iteration', 'distance', 'temperature', 'threshold', 'path']), df.sa_time.at[i]])
print("ANIMATION | STATS | HELP")
while True:
decision = input("Action: ").lower()
if decision == "animation":
iteration = ask_number(n)
plot_start("Tabu Search algorithm")
plot_update(tabu_df[iteration][0].values.tolist(), "TABU LIST SIZE")
plot_start("Simulated Annealing algorithm")
plot_update(sa_df[iteration][0].values.tolist(), "TEMPERATURE")
elif decision == "stats":
iteration = ask_number(n)
print(f"Analysis of {iteration + 1}. iteration of Tabu search algorithm values\n")
print(tabu_df[iteration][0].iloc[:, 1:].describe())
print(f"\nTime of {iteration + 1}. iteration of Tabu search algorithm: {tabu_df[iteration][1]} s")
print(f"Average time of Tabu search algorithm: {round(avg(tabu_df, n), 3)} s")
print(f"\nAnalysis of {iteration + 1}. iteration of Simulated Annealing algorithm values\n")
print(sa_df[iteration][0].iloc[:, 1:].describe())
print(f"\nTime of {iteration + 1}. iteration of Simulated Annealing algorithm: {sa_df[iteration][1]} s")
print(f"Average time of Simulated Annealing algorithm: {round(avg(sa_df, n), 3)} s\n")
elif decision == "help":
print("animation returns visualization about certain solution")
print("stats returns statistical values about certain solution")
print("exit will end the program\n")
elif decision == "exit":
break
else:
print("Wrong input")
print("SAME | INCREMENTAL | HELP ")
while True:
testik = input("Type test: ").lower()
if testik == "incremental" or testik == "same":
break
elif testik == "help":
print("same starts repeated test with constant of towns")
print("incremental starts incremental test with incrementing towns")
else:
print("Wrong input")
while True:
try:
if testik == "same":
town_number = int(input("How many towns to choose: "))
times = int(input("How many iterations of problem to choose: "))
else:
town_number = 4
times = int(input("Max number of towns to choose: ")) - 3
except ValueError:
print("Enter integer")
continue
if town_number > 0 and times > 0:
if testik == "same":
test(times, town_number)
else:
test(times, town_number, True)
break
else:
print("Enter at least 4 towns and 1 iteration")