-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathNSGA2_ZDT6.py
279 lines (256 loc) · 10.3 KB
/
NSGA2_ZDT6.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
from deap.tools import mutPolynomialBounded
from pymoo.factory import get_crossover
from deap import tools
import numpy as np
from pymoo.interface import crossover
import pygmo as pg
import math
import random
import matplotlib.pyplot as plt
#First function to optimize
def zdt6(individual):
"""ZDT6 multiobjective function.
:math:`g(\\mathbf{x}) = 1 + 9 \\left[ \\left(\\sum_{i=2}^n x_i\\right)/(n-1) \\right]^{0.25}`
:math:`f_{\\text{ZDT6}1}(\\mathbf{x}) = 1 - \\exp(-4x_1)\\sin^6(6\\pi x_1)`
:math:`f_{\\text{ZDT6}2}(\\mathbf{x}) = g(\\mathbf{x}) \left[ 1 - (f_{\\text{ZDT6}1}(\\mathbf{x})/g(\\mathbf{x}))^2 \\right]`
"""
g = 1 + 9 * (sum(individual[1:]) / (len(individual)-1))**0.25
f1 = 1 - math.exp(-4*individual[0]) * math.sin(6*np.pi*individual[0])**6
f2 = g * (1 - (f1/g)**2)
return f1, f2
#Function to find index of list
def index_of(a,list):
for i in range(0,len(list)):
if list[i] == a:
return i
return -1
#Function to sort by values
def sort_by_values(list1, values):
sorted_list = []
while(len(sorted_list)!=len(list1)):
if index_of(min(values),values) in list1:
sorted_list.append(index_of(min(values),values))
values[index_of(min(values),values)] = math.inf
return sorted_list
#Function to carry out NSGA-II's fast non dominated sort
def fast_non_dominated_sort(values1, values2):
S=[[] for i in range(0,len(values1))]
front = [[]]
n=[0 for i in range(0,len(values1))]
rank = [0 for i in range(0, len(values1))]
for p in range(0,len(values1)):
S[p]=[]
n[p]=0
for q in range(0, len(values1)):
if (values1[p] > values1[q] and values2[p] > values2[q]) or (values1[p] >= values1[q] and values2[p] > values2[q]) or (values1[p] > values1[q] and values2[p] >= values2[q]):
if q not in S[p]:
S[p].append(q)
elif (values1[q] > values1[p] and values2[q] > values2[p]) or (values1[q] >= values1[p] and values2[q] > values2[p]) or (values1[q] > values1[p] and values2[q] >= values2[p]):
n[p] = n[p] + 1
if n[p]==0:
rank[p] = 0
if p not in front[0]:
front[0].append(p)
i = 0
while(front[i] != []):
Q=[]
for p in front[i]:
for q in S[p]:
n[q] =n[q] - 1
if( n[q]==0):
rank[q]=i+1
if q not in Q:
Q.append(q)
i = i+1
front.append(Q)
del front[len(front)-1]
return front
#Function to calculate crowding distance
def crowding_distance(values1, values2, front):
distance = [0 for i in range(0,len(front))]
sorted1 = sort_by_values(front, values1[:])
sorted2 = sort_by_values(front, values2[:])
distance[0] = 4444444444444444
distance[len(front) - 1] = 4444444444444444
for k in range(1,len(front)-1):
distance[k] = distance[k]+ (values1[sorted1[k+1]] - values2[sorted1[k-1]])/(max(values1)-min(values1))
for k in range(1,len(front)-1):
distance[k] = distance[k]+ (values1[sorted2[k+1]] - values2[sorted2[k-1]])/(max(values2)-min(values2))
return distance
#Function to carry out the crossover
def crossX(a,b):
r=random.random()
# print("nvfknf",len(a))
# print(len(b))
a = np.array(a)
a=a.reshape(-1,1)
b = np.array(b)
b = b.reshape(-1, 1)
# print(a)
# print(a.shape,b.shape)
res=crossover(get_crossover("real_sbx", prob=r,eta=20, prob_per_variable=1.0), a, b)
# print("res",res)
res_list=res.flatten().tolist()
# print("res", res_list)
# if r>0.5:
return res_list
# else:
# return mutation((a + b) / 2)
#Function to carry out the mutation operator
def mutation(solution):
mutation_prob = random.random()
mu_solution=mutPolynomialBounded(solution, 10, min_x, max_x, mutation_prob)
# if mutation_prob <1:
# solution = [min_x+(max_x-min_x)*random.random() for i in range(len(solution))]
return mu_solution
#Main program starts here
pop_size = 100
max_gen = 1001
#Initialization
min_x=0
max_x=1
# solution=[min_x+(max_x-min_x)*random.random() for i in range(0,pop_size)]
solution_all=[]
function1_values=[]
function2_values=[]
for j in range(0,pop_size):
solution = [min_x + (max_x - min_x) * random.random() for i in range(0, 10)]
solution_all.append(solution)
f1,f2=zdt6(solution)
function1_values.append(f1)
function2_values.append(f2)
# function1_values.append(f1)
# function2_values.append(f2)
print(function2_values)
print(function1_values)
plt.scatter(function1_values,function2_values,c="blue")
plt.xlabel('Function 1', fontsize=15)
plt.ylabel('Function 2', fontsize=15)
plt.title("first population of ZDT6")
plt.figure()
gen_no=0
while(gen_no<max_gen):
# function1_values , function2_values = [zdt2(solution_all[i])for i in range(0,pop_size)]
# function2_values = [zdt2(solution_all[i])for i in range(0,pop_size)]
# function1_values,function2_values=[zdt2(solution[i]) for i in range(0, pop_size)]
function1_values=[]
function2_values=[]
points=[]
points2=[]
for i in range(0,pop_size):
f1,f2=zdt6(solution_all[i])
function1_values.append(f1)
function2_values.append(f2)
points.append([f1,f2])
print("points",points)
# non_dominated_sorted_solution = fast_non_dominated_sort(function1_values[:],function2_values[:])
ndf, dl, dc, ndr = pg.fast_non_dominated_sorting(points = points)
print("The best front for Generation number ",gen_no, " is")
for valuez in ndf[0]:
solution_all[valuez]=[round(elem,3) for elem in solution_all[valuez]]
print(solution_all[valuez],end=" ")
print("\n")
print("\n")
crowding_distance_values=[]
f=[]
# print("ndf: ", ndf)
for i in range(0,len(ndf)):
# crowding_distance_values.append(crowding_distance(function1_values[:],function2_values[:],ndf[i][:]))
# print("ndf",ndf)
non_dominated=ndf[i][:]
# print(non_dominated)
# f2=[]
for i in range(len(non_dominated)):
f.append([function1_values[i],function1_values[i]])
# f2.append(function2_values[i][:])
# print(f)
crowding_distance_values.append(pg.crowding_distance(points=f))
# print("crowding_dis: ",crowding_distance_values)
solution2 = solution_all[:][:]
#Generating offsprings
while(len(solution2)!=2*pop_size):
a1 = random.randint(0,pop_size-1)
b1 = random.randint(0,pop_size-1)
result=crossX(solution_all[a1], solution_all[b1])
# print("result",len(result))
solution2.append(result[:10])
# function1_values2 , function2_values2 = [zdt2(solution2[i])for i in range(0,2*pop_size)]
# function2_values2 = [function2(solution2[i])for i in range(0,2*pop_size)]
function1_values2 = []
function2_values2 = []
# for i in range(0,pop_size):
# f1,f2=zdt2(solution2[i])
# function1_values.append(f1)
# function2_values.append(f2)
# points.append([f1,f2])
#
for i in range(0,2*pop_size):
f1_2,f2_2=zdt6(solution2[i])
function1_values2.append(f1_2)
function2_values2.append(f2_2)
points2.append([f1_2,f2_2])
print("points2", points2)
# non_dominated_sorted_solution = fast_non_dominated_sort(function1_values[:],function2_values[:])
ndf_2, dl_2, dc_2, ndr_2 = pg.fast_non_dominated_sorting(points=points2)
# non_dominated_sorted_solution2 = fast_non_dominated_sort(function1_values2[:],function2_values2[:])
crowding_distance_values2=[]
# f_2 = []
print("ndf_2: ", ndf_2)
for i in range(0, len(ndf_2)):
# crowding_distance_values.append(crowding_distance(function1_values[:],function2_values[:],ndf[i][:]))
# print("ndf",ndf)
non_dominated = ndf_2[i][:]
print(non_dominated)
f_2=[]
for i in non_dominated:
f_2.append(points2[i])
# f2.append(function2_values[i][:])
print("f_2",f_2)
# print(len(f_2))
if len(non_dominated)==1:
crowding_distance_values2.append(np.array([0]))
else:
crowding_distance_values2.append(pg.crowding_distance(points=f_2))
print("crowding_dis: ",pg.crowding_distance(points=f_2))
# for i in range(0,len(non_dominated_sorted_solution2)):
# crowding_distance_values2.append(crowding_distance(function1_values2[:],function2_values2[:],non_dominated_sorted_solution2[i][:]))
new_solution= []
# best=pg.select_best_N_mo(points=f_2, N=80)
# print("select best",pg.select_best_N_mo(points=f_2, N=80))
for i in range(0,len(ndf_2)):
# print("ndf_2",ndf_2)
non_dominated_sorted_solution2_1 = [index_of(ndf_2[i][j],ndf_2[i] ) for j in range(0,len(ndf_2[i]))]
print("hello",non_dominated_sorted_solution2_1)
print("hello2",crowding_distance_values2[i][:])
sort_indexes = np.argsort(crowding_distance_values2[i][:])
# front22 = sort_by_values(non_dominated_sorted_solution2_1[:], crowding_distance_values2[i][:])
print("sorted",sort_indexes)
print("ndf",ndf_2)
front = [ndf_2[i][sort_indexes[j]] for j in range(0,len(ndf_2[i]))]
print("frint",front)
front.reverse()
print("front",front)
for value in front:
new_solution.append(value)
if(len(new_solution)==pop_size):
break
if (len(new_solution) == pop_size):
break
solution_all=[]
for x in new_solution:
print(x)
solution_all.append(solution2[x])
print(len(solution2[x]))
print(solution2[x])
# solution = [solution2[i] for i in front]
# print(len(solution),len(solution[1]))
# print("solutions",solution)
gen_no = gen_no + 1
#Lets plot the final front now
function1 = [i for i in function1_values]
function2 = [j for j in function2_values]
plt.xlabel('Function 1', fontsize=15)
plt.ylabel('Function 2', fontsize=15)
plt.scatter(function1, function2,c="blue")
plt.title("Non-dominated solutions with NSGA2 after 1000 iteration ")
plt.show()