-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.py
More file actions
277 lines (192 loc) · 6.42 KB
/
Copy pathmain.py
File metadata and controls
277 lines (192 loc) · 6.42 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
272
273
274
275
276
277
# -*- coding: utf-8 -*-
"""GeneticAlgorithmForTSP.ipynb
Automatically generated by Colaboratory.
Original file is located at
https://colab.research.google.com/drive/17lhnkDCZtWyCoFsKOwoa5jUi9QUTs5qv
**Genetic algorithm for Traveling Salesman Problem - TSP**
1. Load Data
"""
def read_file(file_name:str):
file = open(file_name)
num_of_points = int(file.readline())
distance_matrix = [[0 for _ in range(num_of_points)] for _ in range(num_of_points)]
for i_row in range(num_of_points):
dist_list = file.readline().split()
dist_list = list(map(int, dist_list))
for i_col in range(len(dist_list)):
distance_matrix[i_row][i_col] = dist_list[i_col]
distance_matrix[i_col][i_row] = dist_list[i_col]
file.close()
return distance_matrix
"""2. Create and manage the population"""
from random import shuffle
def new_individual(m:int) -> list:
ind = list(range(m))
shuffle(ind)
return ind
def new_population(n:int, m:int) -> list:
pop = []
for _ in range(n):
pop.append(new_individual(m))
return pop
def print_individual(ind, fit):
print("-".join(map(str, ind)), fit)
def print_population(pop, fitness=None):
if not fitness:
fitness = ["none" for _ in range(len(pop))]
for ind, fit in zip(pop, fitness):
print_individual(ind, fit)
def evaluate_individual(ind,dm):
m = len(ind)
fit = 0
for i_gene in range(m-1):
gene_1 = ind[i_gene]
gene_2 = ind[i_gene+1]
fit += dm[gene_1][gene_2]
gene_1 = ind[-1]
gene_2 = ind[0]
fit += dm[gene_1][gene_2]
return fit
def evaluate_population(pop, dm):
fitness = []
for ind in pop:
eval_ind = evaluate_individual(ind, dm)
fitness.append(eval_ind)
return fitness
def find_best_individual_index(fitness):
index = 0
for i in range(1,len(fitness)):
if fitness[i] < fitness[index]:
index = i
return index
"""3. Tournament selection and crossover"""
from random import randint
def tournament_selection(pop, fitness, k):
n = len(pop)
new_pop = []
for _ in range(n):
best_ind_index = randint(0,n-1)
for _ in range(k):
random_ind_index = randint(0,n-1)
if fitness[random_ind_index] < fitness[best_ind_index]:
best_ind_index = random_ind_index
new_pop.append(pop[best_ind_index][:])
return new_pop
from random import random
def fix_PMX(parent, self_mid, second_mid):
fix = []
for gene in parent:
while gene in self_mid:
pos = self_mid.index(gene)
gene = second_mid[pos]
fix.append(gene)
return fix
def crossover_PMX(parent_1, parent_2):
m = len(parent_1)
cut_1 = randint(0,m)
cut_2 = randint(cut_1+1,m+1)
cut_2 += 1
child_1_middle = parent_1[cut_1:cut_2]
child_2_middle = parent_2[cut_1:cut_2]
child_1_prefix = fix_PMX(parent_2[:cut_1], child_1_middle, child_2_middle)
child_2_prefix = fix_PMX(parent_1[:cut_1], child_2_middle, child_1_middle)
child_1_sufix = fix_PMX(parent_2[cut_2:], child_1_middle, child_2_middle)
child_2_sufix = fix_PMX(parent_1[cut_2:], child_2_middle, child_1_middle)
child_1 = child_1_prefix + child_1_middle + child_1_sufix
child_2 = child_2_prefix + child_2_middle + child_2_sufix
return child_1, child_2
def crossover(pop, pc):
new_population = []
for i in range(0,len(pop),2):
parent_1 = pop[i]
parent_2 = pop[i+1]
if pc > random():
child_1, child_2 = crossover_PMX(parent_1, parent_2)
else:
child_1, child_2 = parent_1, parent_2
new_population.append(child_1)
new_population.append(child_2)
return new_population
"""4. Mutation"""
from random import randint
def inv_mutation(ind):
m = len(ind)
cut_1 = randint(0,m)
cut_2 = randint(cut_1+1,m+1)
cut_2 += 1
mid = ind[cut_1:cut_2]
ind[cut_1:cut_2] = mid[::-1]
def mutation(pop, pm):
for ind in pop:
if pm > random():
inv_mutation(ind)
"""5. Results graphical presentation"""
import matplotlib.pyplot as plt
def draw_graph(best_results,best_in_population,avg_pop,worst_pop):
plt.plot(best_results)
plt.plot(best_in_population)
plt.plot(avg_pop)
plt.plot(worst_pop)
plt.show()
"""6. Algorithm exec"""
#parameters
problem = "problems/pr107.txt"
num_of_eras = 2 #parameters
num_of_generations = 2700
all_time_best_result_score = 100000000
debug_print = False
m = None
n = 500 #population size
k = 3 #tournament selection comparisons for each individual
pc = 0.7 #crossover chance in percentage for each (two at once) individual
pm = 0.05 #mutation chance in percentage for each individual
bcc = 2 #break condition count
#exec
distance_matrix = read_file(problem)
m = len(distance_matrix)
for _ in range(num_of_eras):
pop_P = new_population(n,m)
fitness = evaluate_population(pop_P, distance_matrix)
best_index = find_best_individual_index(fitness)
best_ind = (pop_P[best_index][:], fitness[best_index])
print("Initial path length: " + str(best_ind[1]))
best_results = [best_ind[1]]
best_in_population = [best_ind[1]]
avg_pop = [sum(fitness)/len(fitness)]
worst_pop = [max(fitness)]
#additional variables for break conditions
last_result_score = 0;
current_result_count = 0;
for i in range(num_of_generations):
pop_T = tournament_selection(pop_P, fitness, k)
pop_O = crossover(pop_T, pc)
mutation(pop_O, pm)
fitness = evaluate_population(pop_O, distance_matrix)
best_index = find_best_individual_index(fitness)
if fitness[best_index] < best_ind[1]:
best_ind = (pop_O[best_index][:], fitness[best_index])
best_results.append(best_ind[1])
best_in_population.append(fitness[best_index])
avg_pop.append(sum(fitness)/len(fitness))
worst_pop.append(max(fitness))
pop_P = pop_O
if i % 200 == 0:
if best_ind[1] == last_result_score:
current_result_count += 1
else:
last_result_score = best_ind[1]
current_result_count = 0
if(current_result_count > bcc-1):
break
if(best_ind[1] < all_time_best_result_score):
all_time_best_result_score = best_ind[1]
if(debug_print):
print(best_ind[1], end='\n')
print_individual(best_ind[0],best_ind[1])
print(" ", end='\n')
#progressbar
print("=", end="")
print("\n" + "Final path length: " + str(best_ind[1]))
print_individual(best_ind[0],best_ind[1])
print("All time best result: " + str(all_time_best_result_score), end='\n\n')
draw_graph(best_results,best_in_population,avg_pop,worst_pop)