-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathTSP_toStudents.py
193 lines (161 loc) · 5.27 KB
/
TSP_toStudents.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
"""
Author:
file:
Rename this file to TSP_x.py where x is your student number
"""
import random
from Individual import *
import sys
myStudentNum = 12345 # Replace 12345 with your student number
random.seed(myStudentNum)
class BasicTSP:
def __init__(self, _fName, _popSize, _mutationRate, _maxIterations):
"""
Parameters and general variables
"""
self.population = []
self.matingPool = []
self.best = None
self.popSize = _popSize
self.genSize = None
self.mutationRate = _mutationRate
self.maxIterations = _maxIterations
self.iteration = 0
self.fName = _fName
self.data = {}
self.readInstance()
self.initPopulation()
def readInstance(self):
"""
Reading an instance from fName
"""
file = open(self.fName, 'r')
self.genSize = int(file.readline())
self.data = {}
for line in file:
(cid, x, y) = line.split()
self.data[int(cid)] = (int(x), int(y))
file.close()
def initPopulation(self):
"""
Creating random individuals in the population
"""
for i in range(0, self.popSize):
individual = Individual(self.genSize, self.data,[])
individual.computeFitness()
self.population.append(individual)
self.best = self.population[0].copy()
for ind_i in self.population:
if self.best.getFitness() > ind_i.getFitness():
self.best = ind_i.copy()
print ("Best initial sol: ",self.best.getFitness())
def updateBest(self, candidate):
if self.best == None or candidate.getFitness() < self.best.getFitness():
self.best = candidate.copy()
print ("iteration: ",self.iteration, "best: ",self.best.getFitness())
def randomSelection(self):
"""
Random (uniform) selection of two individuals
"""
indA = self.matingPool[ random.randint(0, self.popSize-1) ]
indB = self.matingPool[ random.randint(0, self.popSize-1) ]
return [indA, indB]
def binaryTournamentSelection(self):
"""
Your stochastic universal sampling Selection Implementation
"""
pass
def uniformCrossover(self, indA, indB):
"""
Your Uniform Crossover Implementation
"""
pass
def order1Crossover(self, indA, indB):
"""
Your Order-1 Crossover Implementation
"""
pass
def scrambleMutation(self, ind):
"""
Your Scramble Mutation implementation
"""
pass
def inversionMutation(self, ind):
"""
Your Inversion Mutation implementation
"""
pass
def crossover(self, indA, indB):
"""
Executes a dummy crossover and returns the genes for a new individual
"""
midP=int(self.genSize/2)
cgenes = indA.genes[0:midP]
for i in range(0, self.genSize):
if indB.genes[i] not in cgenes:
cgenes.append(indB.genes[i])
child = Individual(self.genSize, self.data, cgenes)
return child
def mutation(self, ind):
"""
Mutate an individual by swaping two cities with certain probability (i.e., mutation rate)
"""
if random.random() > self.mutationRate:
return
indexA = random.randint(0, self.genSize-1)
indexB = random.randint(0, self.genSize-1)
tmp = ind.genes[indexA]
ind.genes[indexA] = ind.genes[indexB]
ind.genes[indexB] = tmp
ind.computeFitness()
self.updateBest(ind)
def updateMatingPool(self):
"""
Updating the mating pool before creating a new generation
"""
self.matingPool = []
for ind_i in self.population:
self.matingPool.append( ind_i.copy() )
def newGeneration(self):
"""
Creating a new generation
1. Selection
2. Crossover
3. Mutation
"""
for i in range(0, len(self.population)):
"""
Depending of your experiment you need to use the most suitable algorithms for:
1. Select two candidates
2. Apply Crossover
3. Apply Mutation
"""
parent1, parent2 = self.randomSelection()
child = self.crossover(parent1,parent2)
self.mutation(child)
def GAStep(self):
"""
One step in the GA main algorithm
1. Updating mating pool with current population
2. Creating a new Generation
"""
self.updateMatingPool()
self.newGeneration()
def search(self):
"""
General search template.
Iterates for a given number of steps
"""
self.iteration = 0
while self.iteration < self.maxIterations:
self.GAStep()
self.iteration += 1
print ("Total iterations: ", self.iteration)
print ("Best Solution: ", self.best.getFitness())
if len(sys.argv) < 2:
print ("Error - Incorrect input")
print ("Expecting python BasicTSP.py [instance] ")
sys.exit(0)
problem_file = sys.argv[1]
ga = BasicTSP(sys.argv[1], 300, 0.1, 500)
ga.search()