-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathgenetic_tsp.py
213 lines (158 loc) · 4.41 KB
/
genetic_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
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
from random import randint
import math
import time
def genes(len_paths):
global GENES
GENES = ""
for i in range(len_paths):
GENES += chr(65+i)
# starting point
START = 0
# Initial population size for the algorithm
POP_SIZE = 10
class Individual:
def __init__(self) -> None:
self.gnome = ""
self.fitness = 0
def __lt__(self, other):
return self.fitness < other.fitness
def __gt__(self, other):
return self.fitness > other.fitness
def rand_num(start, end):
return randint(start, end-1)
# Function to check if the character
# has already occurred in the string
def repeat(gnome, ch):
'''
Args:
gnome: The current gene
ch: The character being added to the new gene
Return: Boolean True or False
'''
for i in range(len(gnome)):
if gnome[i] == ch:
return True
return False
def crossover(gnome, path_length):
'''
Args:
gnome: GNOME is a string
path_length: Length of paths 2 adjacency matrix that you get from A* or Dijkstra
Returns:
mutated GNOME
'''
gnome = list(gnome)
while True:
r = rand_num(1, path_length)
r1 = rand_num(1, path_length)
if r1 != r:
temp = gnome[r]
gnome[r] = gnome[r1]
gnome[r1] = temp
break
return ''.join(gnome)
# Function to return a valid GNOME string
# required to create the population
def create_gnome(path_length):
'''
Args:
path_length: Length of paths 2 adjacency matrix that you get from A* or Dijkstra
Returns:
The created genome
'''
gnome = "0"
while True:
if len(gnome) == path_length:
gnome += gnome[0]
break
temp = rand_num(1, path_length)
if not repeat(gnome, chr(temp + 48)):
gnome += chr(temp + 48)
return gnome
# Function to return the fitness value of a gnome.
# The fitness value is the path length
# of the path represented by the GNOME.
def cal_fitness(gnome, paths):
'''
Args:
gnome: The gene, a string which represents the order of cities
paths: Paths is a 2 adjacency matrix that you get from A* or Dijkstra
Returns: Fitness value for that gene
'''
fitness = 0
for i in range(len(gnome) - 1):
fitness += paths[ord(gnome[i]) - 48][ord(gnome[i + 1]) - 48]
return fitness
# This function is a stopping condition for the genetic algorithm
# Otherwise the genetic algorithm will keep on running
def cooldown(temp):
'''
Args:
temp: Current temperature
Returns: Cooldown Temperature
'''
return (99 * temp) / 100
def genetic_search(paths):
'''
Args:
paths: The 2d adj matrix which contains all the path lengths
Returns: None
'''
start_time = time.time()
genes(len(paths))
# To keep track of minimum path length
min_path = math.inf
track = 0
# Generation Number
gen = 1
# Number of Gene Iterations
gen_thres = 5000
population = []
temp = Individual()
# Create initial pop and check their fitness
for i in range(POP_SIZE):
temp.gnome = create_gnome(len(paths))
temp.fitness = cal_fitness(temp.gnome, paths)
population.append(temp)
# print("\nInitial population: \nGNOME FITNESS VALUE\n")
# for i in range(POP_SIZE):
# print(population[i].gnome, population[i].fitness)
# print()
# Initial temperature, hyperparameter can be tuned
temperature = 10000000
# Perform genetic mutation
while temperature > 1000 and gen <= gen_thres:
population.sort()
# print("\nCurrent temp: ", temperature)
new_population = []
for i in range(POP_SIZE):
p1 = population[i]
while True:
child = crossover(p1.gnome, len(paths))
new_gnome = Individual()
new_gnome.gnome = child
new_gnome.fitness = cal_fitness(new_gnome.gnome, paths)
if new_gnome.fitness <= population[i].fitness:
new_population.append(new_gnome)
break
else:
# allowing a worse child to get into the population for mutation
prob = math.exp(-1*((new_gnome.fitness-population[i].fitness)/temperature))
if prob > 0.5:
new_population.append(new_gnome)
break
temperature = cooldown(temperature)
population = new_population
# print("Generation", gen)
# print("GNOME FITNESS VALUE")
for i in range(POP_SIZE):
# print(population[i].gnome, population[i].fitness)
if min_path > population[i].fitness:
min_path = population[i].fitness
track = gen
f_time = time.time()-start_time
gen += 1
# print('--------------------------')
print(f'Final path length, traversal order and corresponding generation it was found at are {min_path, track}')
print(f'The time it took for genetic algorithm is {f_time}')
print('----------------------------------')