-
Notifications
You must be signed in to change notification settings - Fork 0
/
traveling_salesman5.py
230 lines (184 loc) · 5.33 KB
/
traveling_salesman5.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
# Python implementation of solution to the Traveling
# Salesman Problem using a genetic algorithm (GA).
# Genetic algorithms are heuristic search algorithms
# inspired by the process of random mutation followed
# by evolution by natural selection. The algorithm
# is designed to replicate the natural selection
# process through suceeding generations. Standard
# genetic algorithms are divided into five phases:
# namely:
# 1) Creating initial population.
# 2) Calculating fitness,
# 3) Selecting the best genes.
# 4) Crosssing over.
# 5) Mutating to introduce variations.
# These algorithms can be implemented to find a
# solution to various kinds of optimization problems
# such as the TSP.
#
# In the following implementation, cities are taken
# as genes, the strings generated using these characters
# are called chromosomes, while a fitness score which
# is equal to the path length of all the cities mentioned
# is used to target a population. The Fitness score is
# defined as the length of the path described by the gene.
# The smaller the path length, the fitter the gene. The
# fittest of all the genes in the gene pool survive the
# population test and move to the next iteration. The number
# of iterations depends on the value of the cooling variable.
# The value of the cooling variable keeps decreasing with
# each iteration and reaches a threshold after a certain
# number of iterations. The time complexity is O(n^2) since
# two nested loops are used to calculate the fitness value
# of each gnome in the population.
from random import randint
INT_MAX = 2147483647
# Number of cities in TSP
V = 5
# Names of the cities
GENES = "ABCDE"
# Starting Node Value
START = 0
# Initial population size for the algorithm
POP_SIZE = 10
# Structure of a GNOME
# defines the path traversed
# by the salesman while the fitness value
# of the path is stored in an integer
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
# Function to return a random number
# from start and end
def rand_num(start, end):
return randint(start, end-1)
# Function to check if the character
# has already occurred in the string
def repeat(s, ch):
for i in range(len(s)):
if s[i] == ch:
return True
return False
# Function to return a mutated GNOME
# Mutated GNOME is a string
# with a random interchange
# of two genes to create variation in species
def mutatedGene(gnome):
gnome = list(gnome)
while True:
r = rand_num(1, V)
r1 = rand_num(1, V)
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():
gnome = "0"
while True:
if len(gnome) == V:
gnome += gnome[0]
break
temp = rand_num(1, V)
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):
mp = [
[0, 2, INT_MAX, 12, 5],
[2, 0, 4, 8, INT_MAX],
[INT_MAX, 4, 0, 3, 3],
[12, 8, 3, 0, 10],
[5, INT_MAX, 3, 10, 0],
]
f = 0
for i in range(len(gnome) - 1):
if mp[ord(gnome[i]) - 48][ord(gnome[i + 1]) - 48] == INT_MAX:
return INT_MAX
f += mp[ord(gnome[i]) - 48][ord(gnome[i + 1]) - 48]
return f
# Function to return the updated value
# of the cooling element.
def cooldown(temp):
return (90 * temp) / 100
# Comparator for GNOME struct.
# def lessthan(individual t1,
# individual t2)
# :
# return t1.fitness < t2.fitness
# Utility function for TSP problem.
def TSPUtil(mp):
# Generation Number
gen = 1
# Number of Gene Iterations
gen_thres = 5
population = []
temp = individual()
# Populating the GNOME pool.
for i in range(POP_SIZE):
temp.gnome = create_gnome()
temp.fitness = cal_fitness(temp.gnome)
population.append(temp)
print("\nInitial population: \nGNOME FITNESS VALUE\n")
for i in range(POP_SIZE):
print(population[i].gnome, population[i].fitness)
print()
found = False
temperature = 10000
# Iteration to perform
# population crossing and gene 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:
new_g = mutatedGene(p1.gnome)
new_gnome = individual()
new_gnome.gnome = new_g
new_gnome.fitness = cal_fitness(new_gnome.gnome)
if new_gnome.fitness <= population[i].fitness:
new_population.append(new_gnome)
break
else:
# Accepting the rejected children at
# a possible probability above threshold.
prob = pow(
2.7,
-1
* (
(float)(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)
gen += 1
if __name__ == "__main__":
mp = [
[0, 2, INT_MAX, 12, 5],
[2, 0, 4, 8, INT_MAX],
[INT_MAX, 4, 0, 3, 3],
[12, 8, 3, 0, 10],
[5, INT_MAX, 3, 10, 0],
]
TSPUtil(mp)