-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathGA for TSP.py
196 lines (160 loc) · 6.57 KB
/
GA for TSP.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
import pygame
import random
import csv
import math
from collections import Counter
import time
class SolveTSP:
def __init__(self):
self.visuals = True
self.mutation_rate = 0.01
pop_size = 1000
with open('oliver30.csv', newline='') as csvfile:
data = list(csv.reader(csvfile))
for row in data:
row[1] = float(row[1])
row[0] = float(row[0])
self.cities = [tuple(x) for x in data]
print(self.cities)
self.popln = [None] * pop_size
l_population = len(self.popln)
i = 0
while i < l_population:
random.shuffle(self.cities)
self.popln[i] = self.cities[:]
i+=1
self.fit = [0] * pop_size
self.present_best = {"length": float('inf'),"path": self.popln[0]}
self.countofgen = 0
def start(self):
self.stamp = time.time()
if self.visuals:
pygame.init()
pygame.font.init()
self.font = pygame.font.SysFont('Arial', 32)
self.screen = pygame.display.set_mode((801, 851))
size = (450, 850)
self.surface = pygame.Surface(size)
self.main_loop()
else:
while True:
self.countofgen = 1 + self.countofgen
self.calc_fit()
self.generate_new_popln()
def main_loop(self):
rbg_max = 255
current_generation_text = self.font.render("Initialising", False, (rbg_max, rbg_max, rbg_max))
alltime_best_text = self.font.render("Initialising", False, (rbg_max, rbg_max, rbg_max))
min_fn = (0, 0, 0)
while True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
quit()
self.surface.fill(min_fn)
self.screen.fill(min_fn)
self.draw_cities()
self.countofgen += 1
self.calc_fit()
self.generate_new_popln()
max_idx = self.fit.index(max(self.fit))
current_gen_best = self.popln[max_idx]
self.draw_path(current_gen_best, (rbg_max, rbg_max, rbg_max), 1, 0)
self.draw_path(self.present_best["path"], (rbg_max, rbg_max, rbg_max), 1, 1)
current_generation_text = self.font.render("Generation {0} best".format(self.countofgen), False,
(rbg_max, rbg_max, rbg_max))
alltime_best_text = self.font.render("Current best: {0}".format(math.floor(self.present_best["length"])),
False, (rbg_max, rbg_max, rbg_max))
self.screen.blit(self.surface, (101, 101))
self.screen.blit(current_generation_text, (451, 101))
self.screen.blit(alltime_best_text, (451, 501))
pygame.display.update()
def generate_new_popln(self):
length_popln = len(self.popln)
new_pop = [None] * length_popln
i = 0
while i < length_popln:
parentA, parentB = None, None
iter_limit = 0
while parentA == parentB:
parentB = self.select_GA()
parentA = self.select_GA()
iter_limit += 1
if iter_limit > 50000:
break
new_pop[i] = self.crossover(parentB, parentA)
new_pop[i] = self.mutate(new_pop[i])
i+=1
self.popln = new_pop
def select_GA(self):
max_fit = max(self.fit)
l_population = len(self.popln)-1
idx = random.randint(0, l_population)
while self.fit[idx] < random.uniform(0, max_fit):
idx = random.randint(0, l_population)
return self.popln[idx]
def crossover(self, pB, pA):
rand = random.randint(0, len(pA) - 1)
offspring = pA[:rand]
intersect = Counter(offspring) & Counter(pB)
pB = (Counter(pB) - intersect).elements()
pB = list(pB)
offspring = offspring + pB[:]
return offspring
def mutate(self, p):
l_p = len(p)
i=0
while i < l_p:
if random.random() < self.mutation_rate:
l_cities = len(self.cities) - 1
idx = random.randint(0, l_cities)
p[i], p[idx] = p[idx], p[i]
i+=1
return p
def calc_dist(self, p):
total = 0
length_p = len(p) - 1
i = 0
while i < length_p:
x = (p[i + 1][0] - p[i][0]) ** 2
y = (p[i + 1][1] - p[i][1]) ** 2
total += pow(x + y, 1 / 2)
i += 1
x = (p[-1][0] - p[0][0]) ** 2
y = (p[-1][1] - p[0][1]) ** 2
total = total + math.sqrt(x + y)
return total
def calc_fit(self):
total_fit = 0
length_ga = len(self.fit)
i = 0
while i < length_ga:
self.fit[i] = self.calc_dist(self.popln[i])
time_var = time.time() - self.stamp
if (self.fit[i] < self.present_best["length"]):
print("New best path is found: {0} after {1} generations and {2:5.2f} seconds.".format(self.fit[i],
self.countofgen,
time_var))
self.present_best["path"] = self.popln[i]
self.present_best["length"] = self.fit[i]
self.fit[i] = 1 / self.fit[i]
total_fit = total_fit + self.fit[i]
i+=1
def draw_cities(self):
length_cities = len(self.cities)
i = 0
rbg_max=255
while i < length_cities:
pygame.draw.circle(self.surface, (rbg_max, rbg_max, rbg_max), (self.cities[i][0], self.cities[i][1]), 3)
pygame.draw.circle(self.surface, (rbg_max, rbg_max, rbg_max), (self.cities[i][0], self.cities[i][1] + 400), 3)
i+=1
def draw_path(self, p, colour, width, y_multi):
offset = 400 * y_multi
len_p = len(p) - 1
i = 0
while i < len_p:
pygame.draw.line(self.surface, colour, (p[i][0], p[i][1] + offset), (p[i + 1][0], p[i + 1][1] + offset),
width)
i+=1
pygame.draw.line(self.surface, colour, (p[-1][0], p[-1][1] + offset), (p[0][0], p[0][1] + offset), width)
tsp = SolveTSP()
tsp.start()