-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.py
299 lines (273 loc) · 10.8 KB
/
main.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
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
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
import numpy as np
import random
import copy
import matplotlib.pyplot as plt
global numberOfColors
global populationSize
global tournamentSize
global cut
global mutationRate
global numberOfNodes
global numberOfGenerations
# you have to set number of colors and population size here
numberOfColors = 4
populationSize = 100
# this is the number of selecting parents using tournament selection
tournamentSize = 2
# this is the number that belongs to te cutter of the crossover
cut = 10
# this is mutation rate
mutationRate = 0.02
# this is number of steps that we had to take to get our expected answer
numberOfGenerations = 500
graph = {
'WAzer': ['kordestan', 'EAzer', 'zanjan'],
'EAzer': ['WAzer', 'zanjan', 'ardabil'],
'ardabil': ['zanjan', 'gilan', 'EAzer'],
'zanjan': ['WAzer', 'EAzer', 'gilan', 'ardabil', 'kordestan'],
'gilan': ['ardabil', 'zanjan'],
'kordestan': ['EAzer', 'zanjan'],
'kermanshah': ['kordestan', 'hamedan', 'lorestan', 'ilam'],
'hamedan': ['kordestan', 'kermanshah', 'lorestan', 'markazi', 'qazvin', 'zanjan'],
'qazvin': ['hamedan', 'markazi', 'alborz', 'mazandaran', 'gilan', 'zanjan'],
'mazandaran': ['gilan', 'qazvin', 'alborz', 'tehran', 'semnan', 'golestan'],
'alborz': ['qazvin', 'markazi', 'tehran', 'mazandaran'],
'tehran': ['alborz', 'markazi', 'qom', 'semnan', 'mazandaran'],
'markazi': ['hamedan', 'lorestan', 'esfahan', 'qom', 'tehran', 'alborz', 'qazvin'],
'qom': ['markazi', 'esfahan', 'semnan', 'tehran'],
'lorestan': ['kermanshah', 'ilam', 'khuzestan', 'chaharmahal', 'esfahan', 'markazi', 'hamedan'],
'ilam': ['kermanshah', 'lorestan', 'khuzestan'],
'khuzestan': ['ilam', 'lorestan', 'chaharmahal', 'kohgiluye', 'bushehr'],
'chaharmahal': ['khuzestan', 'kohgiluye', 'esfahan', 'lorestan'],
'esfahan': ['qom', 'markazi', 'lorestan', 'chaharmahal', 'kohgiluye', 'fars', 'yazd', 'SKhorasan', 'semnan'],
'semnan': ['mazandaran', 'tehran', 'qom', 'esfahan', 'SKhorasan', 'RKhorasan', 'NKhorasan', 'golestan'],
'golestan': ['mazandaran', 'semnan', 'NKhorasan'],
'NKhorasan': ['golestan', 'semnan', 'RKhorasan'],
'RKhorasan': ['NKhorasan', 'semnan', 'SKhorasan'],
'SKhorasan': ['RKhorasan', 'semnan', 'esfahan', 'yazd', 'kerman', 'sistan'],
'yazd': ['esfahan', 'fars', 'kerman', 'SKhorasan'],
'fars': ['kohgiluye', 'bushehr', 'hormozgan', 'kerman', 'yazd', 'esfahan'],
'kohgiluye': ['khuzestan', 'bushehr', 'fars', 'esfahan', 'chaharmahal'],
'bushehr': ['khuzestan', 'kohgiluye', 'fars', 'hormozgan'],
'hormozgan': ['bushehr', 'fars', 'kerman', 'sistan'],
'kerman': ['yazd', 'fars', 'hormozgan', 'sistan', 'SKhorasan'],
'sistan': ['hormozgan', 'kerman', 'SKhorasan']
}
color = {
'WAzer': [random.randint(1, numberOfColors)],
'EAzer': [random.randint(1, numberOfColors)],
'ardabil': [random.randint(1, numberOfColors)],
'zanjan': [random.randint(1, numberOfColors)],
'gilan': [random.randint(1, numberOfColors)],
'kordestan': [random.randint(1, numberOfColors)],
'kermanshah': [random.randint(1, numberOfColors)],
'hamedan': [random.randint(1, numberOfColors)],
'qazvin': [random.randint(1, numberOfColors)],
'mazandaran': [random.randint(1, numberOfColors)],
'alborz': [random.randint(1, numberOfColors)],
'tehran': [random.randint(1, numberOfColors)],
'markazi': [random.randint(1, numberOfColors)],
'qom': [random.randint(1, numberOfColors)],
'lorestan': [random.randint(1, numberOfColors)],
'ilam': [random.randint(1, numberOfColors)],
'khuzestan': [random.randint(1, numberOfColors)],
'chaharmahal': [random.randint(1, numberOfColors)],
'esfahan': [random.randint(1, numberOfColors)],
'semnan': [random.randint(1, numberOfColors)],
'golestan': [random.randint(1, numberOfColors)],
'NKhorasan': [random.randint(1, numberOfColors)],
'RKhorasan': [random.randint(1, numberOfColors)],
'SKhorasan': [random.randint(1, numberOfColors)],
'yazd': [random.randint(1, numberOfColors)],
'fars': [random.randint(1, numberOfColors)],
'kohgiluye': [random.randint(1, numberOfColors)],
'bushehr': [random.randint(1, numberOfColors)],
'hormozgan': [random.randint(1, numberOfColors)],
'kerman': [random.randint(1, numberOfColors)],
'sistan': [random.randint(1, numberOfColors)]
}
def heapify(arr, n, i):
largest = i # Initialize largest as root
l = 2 * i + 1 # left = 2*i + 1
r = 2 * i + 2 # right = 2*i + 2
# See if left child of root exists and is
# greater than root
if l < n:
pathi, costi = arr[i]
pathl, costl = arr[l]
if costi < costl:
largest = l
# See if right child of root exists and is
# greater than root
if r < n:
pathLarge, costLarge = arr[largest]
pathr, costr = arr[r]
if costLarge < costr:
largest = r
# Change root, if needed
if largest != i:
arr[i], arr[largest] = arr[largest], arr[i] # swap
# Heapify the root.
heapify(arr, n, largest)
# The main function to sort an array of given size
def heapSort(arr):
n = len(arr)
# Build a maxheap.
for i in range(n, -1, -1):
heapify(arr, n, i)
# One by one extract elements
for i in range(n - 1, 0, -1):
arr[i], arr[0] = arr[0], arr[i] # swap
heapify(arr, i, 0)
# this is the function that validates the state that you give to it
# state is an array that looks like your graph, the graph is my model of the all adjacent nodes
def evaluation(colorVal, graphVal):
# this is the total number edges * 2
count = 0
# this is the total number of edges that connect vertices which have not same colors
notConflict = 0
# here is the for that visits all nodes and counts the conflict number between all adjacent nodes
for node in graphVal:
for adjacent in graphVal.get(node, []):
# here i will find the color of each node and each adjacent
colorAdjacent = colorVal.get(adjacent, [])
colorNode = colorVal.get(node, [])
count += 1
if colorNode[0] != colorAdjacent[0]:
notConflict += 1
return notConflict * 2 / count
# here we generate the first population
def firstChoromosome(firstGraph, firstGraphSize, colorFirst):
list = []
for x in range(populationSize):
dicTemp = copy.deepcopy(colorFirst)
listTemp = []
for u in range(firstGraphSize):
listTemp.append(random.randint(1, numberOfColors))
i = 0
for u in dicTemp:
dicTemp[u][0] = listTemp[i]
i += 1
firstScore = evaluation(dicTemp, firstGraph)
list.append((dicTemp, firstScore))
#print((listTemp, firstScore))
listTemp.clear()
return list
def crossOver(firstPopulation, first, second, child):
father, fatherScore = firstPopulation.__getitem__(first)
mother, motherScore = firstPopulation.__getitem__(second)
i = 0
tmpChild = []
dicTemp = copy.deepcopy(color)
# here i make a child using a simple change in father(i take first "cut" number of mother
for x in mother:
if i == cut:
break
i += 1
for y in mother.get(x, []):
tmpChild.append(y)
i = 0
for x in father:
for y in father.get(x, []):
if i < cut:
i += 1
continue
tmpChild.append(y)
i = 0
for u in dicTemp:
dicTemp[u][0] = tmpChild[i]
i += 1
score = evaluation(dicTemp, graph)
child.append((dicTemp, score))
def mutation(noneMutatedPopulation):
# this is the number of mutated genomes
mutatedGenomes = noneMutatedPopulation.__len__() * numberOfNodes * mutationRate
for x in range(int(mutatedGenomes)):
member = random.randint(0, noneMutatedPopulation.__len__() - 1)
genome = random.randint(1, numberOfNodes)
path, score = noneMutatedPopulation[member]
for mufind in graph:
if genome == 0:
break
genome -= 1
# here mutation occurs
last = path[mufind][0]
new = random.randint(1, numberOfColors)
while last == new:
new = random.randint(1, numberOfColors)
path[mufind][0] = new
score = evaluation(path, graph)
noneMutatedPopulation[member] = path, score
def newGeneration(lastPopulation):
child = []
for i in range(lastPopulation.__len__()):
x = random.randint(0, lastPopulation.__len__() - 1)
y = random.randint(0, lastPopulation.__len__() - 1)
crossOver(lastPopulation, x, y, child)
mutation(child)
return child
# here i cluster the population in groups of tournament size
def parentSelection(choroSomeList):
parentList = []
group = []
# while choroSomeList:
for t in range (populationSize):
for x in range(tournamentSize):
# here i randomly choose one set of colors
rand = random.randint(0, choroSomeList.__len__() - 1)
# print("rand : " + str(rand))
# print(choroSomeList[rand])
# group.append(choroSomeList.pop(rand)) #########################################################
group.append(choroSomeList[rand])
heapSort(group)
#print("group : ")
#print(group)
#print()
parentList.append(group.pop(-1))
#print("parents list : ")
#print(parentList)
#print()
group.clear()
return parentList
if __name__ == "__main__":
# plt.plot([1, 20, 30, 40], [1, 4, 9, 16])
# plt.ylabel('some numbers')
# plt.show()
minList = []
maxList = []
avgList = []
minScore = 10
maxScore = 0
avgScore = 0
numberOfNodes = graph.__len__()
population = firstChoromosome(graph, numberOfNodes, color)
#parents = parentSelection(population)
#population = newGeneration(parents)
#print(population.__len__())
for p in range(1, numberOfGenerations + 1):
parents = parentSelection(population)
population = newGeneration(parents)
for pop in population:
path, score = pop
avgScore = avgScore + score
if score > maxScore:
maxScore = score
if score < minScore:
minScore = score
avgtemp = avgScore / (p * populationSize)
minList.append(minScore)
maxList.append(maxScore)
avgList.append(avgtemp)
avgScore = avgScore / (numberOfGenerations * populationSize)
print("MAX : " + str(maxScore))
print("MIN : " + str(minScore))
print("AVG : " + str(avgScore))
t = np.arange(0., 5., 0.1)
# red dashes, blue squares and green triangles
plt.subplot(212)
plt.plot(minList, minList, 'r--')
plt.subplot(221)
plt.plot(maxList, maxList, 'b--')
plt.subplot(222)
plt.plot(avgList, avgList, 'g--')
plt.show()