def evaluate(self, individual): ratios = self.decoder(individual, self.code_division) datlist_list = [fc.read_datfile(file) for file in self.datfiles] datlist_shaped_list = [ fc.shape_dat(datlist) for datlist in datlist_list ] newdat = fc.interpolate_dat(datlist_shaped_list, ratios) foil_para = fc.get_foil_para(newdat) datx = np.array([ax[0] for ax in newdat]) daty = np.array([ax[1] for ax in newdat]) newfoil = Airfoil(x=datx, y=daty) mt, mta, mc, mca, s = foil_para penalty = 0 for g, p in zip(self.gs, self.penalties): if (not g): penalty += p xf = XFoil() xf.airfoil = newfoil xf.Re = self.re xf.max_iter = 60 print(self.assigns, self.datfiles) scope = locals() exec(self.assigns, scope) #---------------------------------- #目的値 #---------------------------------- try: obj1, obj2, obj3 = [eval(o) for o in self.Os] except IndexError as e: obj1, obj2, obj3 = [1.0] * self.NOBJ traceback.print_exc() except SyntaxError as e: raise ValueError("invalid objection") if (np.isnan(obj1) or obj1 > 1): obj1 = 1 if (np.isnan(obj2) or obj2 > 1): obj2 = 1 if (np.isnan(obj3) or obj3 > 1): obj3 = 1 obj1 += penalty obj2 += penalty obj3 += penalty return [obj1, obj2, obj3]
def setup_plot(self): #プロット先をgroupBox_4に設定 self.canvas = MplCanvas(self, width=3, height=2, dpi=100) toolbar = NavigationToolbar(self.canvas, self) layout = QtWidgets.QVBoxLayout() layout.addWidget(self.canvas) layout.addWidget(toolbar) self.groupBox_4.setLayout(layout) self.canvas2 = MplCanvas(self, width=3, height=2, dpi=100) toolbar2 = NavigationToolbar(self.canvas2, self) layout2 = QtWidgets.QVBoxLayout() layout2.addWidget(self.canvas2) layout2.addWidget(toolbar2) self.groupBox_3.setLayout(layout2) ratios = [0.4, 0.1, 0.1, 0.3] datlist_list = [fc.read_datfile(file) for file in self.foilfiles] datlist_shaped_list = [ fc.shape_dat(datlist) for datlist in datlist_list ] newdat = fc.interpolate_dat(datlist_shaped_list, ratios) self.datx = [dat[0] for dat in newdat] self.daty = [dat[1] for dat in newdat] print(self.datx) print(self.daty) self.canvas2.axes.set_xlim(0, 1) self.canvas2.axes.set_ylim(-0.5, 0.5) self.canvas2.axes.set_title('gen1') self.canvas2.axes.plot(self.datx, self.daty, 'r') self.canvas2.draw() #プロットデータ設定 n_data = 50 self.xdata = list(range(n_data)) self.ydata = [random.randint(0, 10) for i in range(n_data)] self.update_plot() #プロット更新頻度設定 self.timer = QtCore.QTimer() self.timer.setInterval(100) self.timer.timeout.connect(self.update_plot) self.timer.start()
def main(self,seed=None): self.setup() #同時並列数(空白にすると最大数になる) self.pool = Pool(self.thread) self.toolbox.register("map", self.pool.map) random.seed(seed) # Initialize statistics object stats = tools.Statistics(lambda ind: ind.fitness.values) stats.register("avg", np.mean, axis=0) stats.register("std", np.std, axis=0) stats.register("min", np.min, axis=0) stats.register("max", np.max, axis=0) logbook = tools.Logbook() logbook.header = "gen", "evals", "std", "min", "avg", "max" #初期化(個体生成のこと) pop = self.toolbox.population(n=self.MU) #描画準備 plt.ion() #進化の始まり # Begin the generational process for gen in range(self.NGEN): if(gen == 0): #0世代目の評価 # Evaluate the individuals with an invalid fitness invalid_ind = [ind for ind in pop if not ind.fitness.valid] fitnesses = self.toolbox.map(self.toolbox.evaluate, invalid_ind) for ind, fit in zip(invalid_ind, fitnesses): ind.fitness.values = fit #0世代目の統計 # Compile statistics about the population record = stats.compile(pop) logbook.record(gen=0, evals=len(invalid_ind), **record) else: offspring = algorithms.varAnd(pop, self.toolbox, self.CXPB, self.MUTPB) #評価 # Evaluate the individuals with an invalid fitness invalid_ind = [ind for ind in offspring if not ind.fitness.valid] fitnesses = self.toolbox.map(self.toolbox.evaluate, invalid_ind) for ind, fit in zip(invalid_ind, fitnesses): ind.fitness.values = fit #淘汰 # Select the next generation population from parents and offspring pop = self.toolbox.select(pop + offspring, self.MU) #評価 pop_fit = np.array([ind.fitness.values for ind in pop]) #---------------------------------- #途中経過プロット #---------------------------------- #1世代ごとに翼型をファイルに書き出す k = 0 for ind in pop[:10]: ratios = self.decoder(ind,self.code_division) try: k += 1 datlist_list = [fc.read_datfile(file) for file in self.datfiles] datlist_shaped_list = [fc.shape_dat(datlist) for datlist in datlist_list] newdat = fc.interpolate_dat(datlist_shaped_list,ratios) fc.write_datfile(datlist=newdat,newfile_name = "newfoil"+str(k)+str(".dat")) except Exception as e: print("message:{0}".format(e)) # ##翼型それぞれの評価値を出力する k = 0 for ind, fit in zip(pop, pop_fit): try: k += 1 print(k) print("individual:" + str(ind) + "\nfit:" + str(fit)) except Exception as e: print("message:{0}".format(e)) # plt.cla()#消去 ##新翼型の描画 datlist_list = [fc.read_datfile(file) for file in self.datfiles] datlist_shaped_list = [fc.shape_dat(datlist) for datlist in datlist_list] newdat = fc.interpolate_dat(datlist_shaped_list,self.decoder(pop[0],self.code_division)) fc.write_datfile(datlist=newdat,newfile_name = "./foil_dat_gen/newfoil_gen"+str(gen)+str(".dat")) plt.title('generation:'+str(gen)) newdat_x = [dat[0] for dat in newdat] newdat_y = [dat[1] for dat in newdat] plt.xlim([0,1]) plt.ylim([-0.5,0.5]) plt.plot(newdat_x,newdat_y) plt.savefig("./newfoil_gen/newfoil_gen"+str(gen)+".png") plt.draw()#描画 plt.pause(0.1)#描画待機 ##評価値のプロット fig = plt.figure(figsize=(7, 7)) ax = fig.add_subplot(111, projection="3d") p = [ind.fitness.values for ind in pop] p1 = [i[0] for i in p] p2 = [j[1] for j in p] p3 = [k[2] for k in p] ax.set_xlim(0,self.obj1_max) ax.set_ylim(0,self.obj2_max) ax.set_zlim(0,self.obj3_max) ax.scatter(p1, p2, p3, marker="o", s=24, label="Final Population") ref = tools.uniform_reference_points(self.NOBJ, self.P) ax.scatter(ref[:, 0], ref[:, 1], ref[:, 2], marker="o", s=24, label="Reference Points") ax.view_init(elev=11, azim=-25) #ax.autoscale(tight=True) plt.legend() plt.title("nsga3_gen:"+str(gen)) plt.tight_layout() plt.savefig("./nsga3_gen/nsga3_gen"+str(gen)+".png") plt.close() #====================================================== # Compile statistics about the new population record = stats.compile(pop) logbook.record(gen=gen, evals=len(invalid_ind), **record) with SetIO('stats2.log'): #stas.logに統計データを出力 print(logbook.stream) return pop, logbook def __getstate__(self): self_dict = self.__dict__.copy() del self_dict['pool'] return self_dict def __setstate__(self, state): self.__dict__.update(state)
def evaluate(self,individual): #---------------------------------- #遺伝子に基づいて新翼型を生成 #---------------------------------- #遺伝子をデコード ratios = self.decoder(individual, self.code_division) #遺伝子に基づき翼型を混合して、新しい翼型を作る datlist_list = [fc.read_datfile(file) for file in self.datfiles] datlist_shaped_list = [fc.shape_dat(datlist) for datlist in datlist_list] newdat = fc.interpolate_dat(datlist_shaped_list,ratios) #翼型の形に関する情報を取得する #foilpara == [最大翼厚、最大翼厚位置、最大キャンバ、最大キャンバ位置、S字の強さ] foil_para = fc.get_foil_para(newdat) #新しい翼型をAerofoilオブジェクトに適用 datx = np.array([ax[0] for ax in newdat]) daty = np.array([ax[1] for ax in newdat]) newfoil = Airfoil(x = datx, y = daty) mt, mta, mc, mca, s = foil_para #---------------------------------- #翼の形に関する拘束条件 #---------------------------------- """ penalty = 0 for g, p in zip(self.gs, self.penalties): if(not g): penalty += p """ penalty = 0 print('===================') if(mc<0): print("out of the border") print("reverse_cmaber") penalty -= mc if(mt<0.08): print("out of the border") print("too_thin") penalty += 0.08-mt if(mt>0.11): print("out of the border") print("too_fat") penalty += mt-0.11 #if(foil_para[4]>0.03): # print("out of the border") # print("peacock") # print('===================') # return (1.0+(foil_para[4]-0.03),)*NOBJ if(mta<0.23): print("out of the border") print("Atama Dekkachi!") penalty += 0.23 - mta if(mta>0.3): print("out of the border") print("Oshiri Dekkachi!") penalty += mta - 0.3 #---------------------------------- #新翼型の解析 #---------------------------------- xf = XFoil() xf.airfoil = newfoil #レイノルズ数の設定 xf.Re = self.re #境界要素法計算時1ステップにおける計算回数 xf.max_iter = 60 #print("hi") #print(vars) #scope = locals() #var0, var1, var2, var3, var4, var5, var6, var7 = [0 if var == None or var == '' else eval(var,scope) for var in self.vars] #計算結果格納 a, cl, cd, cm, cp = xf.cseq(0.4, 1.1, 0.1) lr = [l/d for l, d in zip(cl,cd)] #---------------------------------- #目的値 #---------------------------------- """ try: obj1,obj2,obj3 = [eval(o) for o in Os] except Exception as e: obj1,obj2,obj3=[1.0]*self.NOBJ traceback.print_exc() """ try: #揚抗比の逆数を最小化 obj1 = 1/lr[1] #揚抗比のピークを滑らかに(安定性の最大化) maxlr = max(lr) maxlr_index = lr.index(maxlr) obj2 = abs(maxlr - lr[maxlr_index+1]) #下面の反りを最小化(製作再現性の最大化) obj3 = s except Exception as e: obj1,obj2,obj3=[1.0]*self.NOBJ traceback.print_exc() if (np.isnan(obj1) or obj1 > 1): obj1 = 1 if (np.isnan(obj2) or obj2 > 1): obj2 = 1 if (np.isnan(obj3) or obj3 > 1): obj3 = 1 obj1 += penalty obj2 += penalty obj3 += penalty return [obj1, obj2, obj3]
try: pop, stats = ng.main() except KeyboardInterrupt: print("Ctrl + Cで停止しました") pass #最終世代の評価値取得 pop_fit = np.array([ind.fitness.values for ind in pop]) #10個の最適翼型候補をファイルに書き出す k = 0 for ind, fit in zip(pop[:10], pop_fit[:10]): try: k += 1 datlist_list = [fc.read_datfile(file) for file in datfiles] datlist_shaped_list = [fc.shape_dat(datlist) for datlist in datlist_list] newdat = fc.interpolate_dat(datlist_shaped_list,decoder(ind,code_division)) fc.write_datfile(datlist=newdat,newfile_name = "newfoil"+str(k)+str(".dat")) except Exception as e: print("message:{0}".format(e)) #10個の最適翼型候補の評価値を出力 k = 0 for ind, fit in zip(pop, pop_fit): try: k += 1 print(k) print("individual:" + str(ind) + "\nfit:" + str(fit)) except Exception as e: print("message:{0}".format(e))
def evaluate(individual): global code_division #---------------------------------- #遺伝子にも続いて新翼型を生成 #---------------------------------- #遺伝子をデコード ratios = decoder(individual, code_division) #遺伝子に基づき翼型を混合して、新しい翼型を作る datlist_list = [fc.read_datfile(file) for file in datfiles] datlist_shaped_list = [fc.shape_dat(datlist) for datlist in datlist_list] newdat = fc.interpolate_dat(datlist_shaped_list,ratios) #翼型の形に関する情報を取得する #foilpara == [最大翼厚、最大翼厚位置、最大キャンバ、最大キャンバ位置、S字の強さ] foil_para = fc.get_foil_para(newdat) #新しい翼型をAerofoilオブジェクトに適用 datx = np.array([ax[0] for ax in newdat]) daty = np.array([ax[1] for ax in newdat]) newfoil = Airfoil(x = datx, y = daty) mt, mta, mc, mca, s = foil_para #---------------------------------- #翼の形に関する拘束条件 #---------------------------------- penalty = 0 print('===================') if(mc<0): print("out of the border") print("reverse_cmaber") penalty -= mc if(mt<0.08): print("out of the border") print("too_thin") penalty += 0.08-mt if(mt>0.11): print("out of the border") print("too_fat") penalty += mt-0.11 #if(foil_para[4]>0.03): # print("out of the border") # print("peacock") # print('===================') # return (1.0+(foil_para[4]-0.03),)*NOBJ if(mta<0.23): print("out of the border") print("Atama Dekkachi!") penalty += 0.23 - mta if(mta>0.3): print("out of the border") print("Oshiri Dekkachi!") penalty += mta - 0.3 #---------------------------------- #新翼型の解析 #---------------------------------- xf = XFoil() xf.airfoil = newfoil #レイノルズ数の設定 xf.Re = 1.5e5 #境界要素法計算時1ステップにおける計算回数 xf.max_iter = 60 #座標整形 xf.repanel(n_nodes = 300) xf.print = False #計算結果格納 a, cl, cd, cm, cp = xf.cseq(0.4, 1.1, 0.1) lr = [l/d for l, d in zip(cl,cd)] #---------------------------------- #目的値 #---------------------------------- try: #揚抗比の逆数を最小化 obj1 = 1/lr[1] #揚抗比のピークを滑らかに(安定性の最大化) maxlr = max(lr) maxlr_index = lr.index(maxlr) obj2 = abs(maxlr - lr[maxlr_index+1]) #下面の反りを最小化(製作再現性の最大化) obj3 = foil_para[4] except Exception as e: obj1,obj2,obj3=[1.0]*NOBJ traceback.print_exc() if (np.isnan(obj1) or obj1 > 1): obj1 = 1 if (np.isnan(obj2) or obj2 > 1): obj2 = 1 if (np.isnan(obj3) or obj3 > 1): obj3 = 1 obj1 += penalty obj2 += penalty obj3 += penalty print("individual",individual) print("evaluate",obj1,obj2,obj3) print("max_thickness",foil_para[0]) print("at",foil_para[1]) print("max_camber",foil_para[2]) print("at",foil_para[3]) print("S",foil_para[4]) print('===================') return [obj1, obj2, obj3]
def evaluate(individual): global code_division ratios = decoder(individual, code_division) #=========================================== #翼型を混合し、新翼型のdatファイルを書き出す #========================================== datlist_list = [fc.read_datfile(file) for file in datfiles] datlist_shaped_list = [fc.shape_dat(datlist) for datlist in datlist_list] newdat = fc.interpolate_dat(datlist_shaped_list, ratios) #foilpara == [最大翼厚、最大翼厚位置、最大キャンバ、最大キャンバ位置、S字の強さ] foil_para = fc.get_foil_para(newdat) mt, mta, mc, mca, s = foil_para #print(obj1_max,obj2_max,obj3_max) #-------------------- #翼の形に関する拘束条件 penalty = 0 print('===================') if (mc < 0): print("out of the border") print("reverse_cmaber") penalty -= mc if (mt < 0.08): print("out of the border") print("too_thin") penalty += 0.08 - mt if (mt > 0.11): print("out of the border") print("too_fat") penalty += mt - 0.11 #if(foil_para[4]>0.03): # print("out of the border") # print("peacock") # print('===================') # return (1.0+(foil_para[4]-0.03),)*NOBJ if (mta < 0.23): print("out of the border") print("Atama Dekkachi!") penalty += 0.23 - mta if (mta > 0.3): print("out of the border") print("Oshiri Dekkachi!") penalty += mta - 0.3 if penalty > 0: return [1.0 + penalty] * NOBJ #-------------------- id = str(os.getpid()) dir_path = 'dump' try: os.makedirs(dir_path) except FileExistsError: pass newfile_name = 'newfoil' + id + '.dat' foilfile = fc.write_datfile(datlist=newdat, newfile_name=dir_path + '/' + newfile_name) #========================================== #新翼型の解析 #========================================== set1 = xa.XfoilAnalize(cseq=[0.4, 1.1, 0.1], foilfile=foilfile, polar="polar1" + id) #set2 = xa.XfoilAnalize(foilfile=newfile_name,polar="polar2" + id,Re=150000,cl=0.5) #set3 = xa.XfoilAnalize(foilfile=newfile_name,polar="polar3" + id,Re=100000,cl=0.5) try: Lrlist = set1.Cseq(timeout=9)["Lrlist"] maxLr = max(Lrlist) maxindex = Lrlist.index(maxLr) #========================================== #目的値 #========================================== obj1 = 1 / Lrlist[0] #揚抗比の最大化 obj2 = abs(Lrlist[maxindex] - Lrlist[maxindex + 1]) #揚抗比のピークを滑らかに(安定性の最大化) obj3 = foil_para[ 4] #下面の反りを最小化(製作再現性の最大化)#abs(set2.OneCL()["Alpha"]-set3.OneCL()["Alpha"]) #正規化 obj1 = obj1 if obj1 <= 1 else 1.0 #値域<1.0 obj2 = obj2 if obj2 <= 1 else 1.0 #値域<1.0 obj3 = obj3 if obj3 <= 1 else 1.0 #値域<1.0 print("individual", individual) print("evaluate", obj1, obj2, obj3) print("max_thickness", foil_para[0]) print("at", foil_para[1]) print("max_camber", foil_para[2]) print("at", foil_para[3]) print("S", foil_para[4]) print('===================') except Exception as e: obj1, obj2, obj3 = [1.0] * NOBJ traceback.print_exc() print("individual", individual) print("evaluate", obj1, obj2, obj3) print("max_thickness", foil_para[0]) print("at", foil_para[1]) print("max_camber", foil_para[2]) print("at", foil_para[3]) print("S", foil_para[4]) print('===================') return [obj1, obj2, obj3]
def main(seed=None): global obj1_max, obj2_max, obj3_max, CXPB, MUTPB pool = Pool(4) #同時並列数(空白にすると最大数になる) toolbox.register("map", pool.map) random.seed(seed) # Initialize statistics object stats = tools.Statistics(lambda ind: ind.fitness.values) stats.register("avg", numpy.mean, axis=0) stats.register("std", numpy.std, axis=0) stats.register("min", numpy.min, axis=0) stats.register("max", numpy.max, axis=0) logbook = tools.Logbook() logbook.header = "gen", "evals", "std", "min", "avg", "max" pop = toolbox.population(n=MU) #0世代目の評価 # Evaluate the individuals with an invalid fitness invalid_ind = [ind for ind in pop if not ind.fitness.valid] fitnesses = toolbox.map(toolbox.evaluate, invalid_ind) for ind, fit in zip(invalid_ind, fitnesses): ind.fitness.values = fit #0世代目の統計 # Compile statistics about the population record = stats.compile(pop) logbook.record(gen=0, evals=len(invalid_ind), **record) print(logbook.stream) #描画準備 plt.ion() #進化の始まり # Begin the generational process for gen in range(1, NGEN): offspring = algorithms.varAnd(pop, toolbox, CXPB, MUTPB) #評価 # Evaluate the individuals with an invalid fitness invalid_ind = [ind for ind in offspring if not ind.fitness.valid] fitnesses = toolbox.map(toolbox.evaluate, invalid_ind) for ind, fit in zip(invalid_ind, fitnesses): ind.fitness.values = fit #淘汰 # Select the next generation population from parents and offspring pop = toolbox.select(pop + offspring, MU) print("------objs_before-------") print(obj1_max, obj2_max, obj3_max) #最大値取得 pop_fit = numpy.array([ind.fitness.values for ind in pop]) fits1 = [obj[0] for obj in pop_fit] _obj1_max = max(fits1) fits2 = [obj[1] for obj in pop_fit] _obj2_max = max(fits2) fits3 = [obj[2] for obj in pop_fit] _obj3_max = max(fits3) #最大値に応じて正規化 if _obj1_max <= 1.0: obj1_max = _obj1_max if _obj2_max <= 1.0: obj2_max = _obj2_max if _obj3_max <= 1.0: obj3_max = _obj3_max print("------objs_after-------") print(obj1_max, obj2_max, obj3_max) #====================================================== #---------途中経過プロット---------- ##1世代ごとに翼型を書き出す k = 0 for ind in pop[:10]: global code_division ratios = decoder(ind, code_division) try: k += 1 datlist_list = [fc.read_datfile(file) for file in datfiles] datlist_shaped_list = [ fc.shape_dat(datlist) for datlist in datlist_list ] newdat = fc.interpolate_dat(datlist_shaped_list, ratios) fc.write_datfile(datlist=newdat, newfile_name="newfoil" + str(k) + str(".dat")) except Exception as e: print("message:{0}".format(e)) # ##翼型それぞれの評価値を出力する k = 0 for ind, fit in zip(pop, pop_fit): try: k += 1 print(k) print("individual:" + str(ind) + "\nfit:" + str(fit)) except Exception as e: print("message:{0}".format(e)) # plt.cla() #消去 ##新翼型の描画 datlist_list = [fc.read_datfile(file) for file in datfiles] datlist_shaped_list = [ fc.shape_dat(datlist) for datlist in datlist_list ] newdat = fc.interpolate_dat(datlist_shaped_list, decoder(pop[0], code_division)) fc.write_datfile(datlist=newdat, newfile_name="./foil_dat_gen/newfoil_gen" + str(gen) + str(".dat")) plt.title('generation:' + str(gen)) newdat_x = [dat[0] for dat in newdat] newdat_y = [dat[1] for dat in newdat] plt.xlim([0, 1]) plt.ylim([-0.5, 0.5]) plt.plot(newdat_x, newdat_y) plt.savefig("./newfoil_gen/newfoil_gen" + str(gen) + ".png") plt.draw() #描画 plt.pause(0.1) #描画待機 ##評価値のプロット fig = plt.figure(figsize=(7, 7)) ax = fig.add_subplot(111, projection="3d") p = [ind.fitness.values for ind in pop] p1 = [i[0] for i in p] p2 = [j[1] for j in p] p3 = [k[2] for k in p] ax.set_xlim(0, obj1_max) ax.set_ylim(0, obj2_max) ax.set_zlim(0, obj3_max) ax.scatter(p1, p2, p3, marker="o", s=24, label="Final Population") ref = tools.uniform_reference_points(NOBJ, P) ax.scatter(ref[:, 0], ref[:, 1], ref[:, 2], marker="o", s=24, label="Reference Points") ax.view_init(elev=11, azim=-25) #ax.autoscale(tight=True) plt.legend() plt.title("nsga3_gen:" + str(gen)) plt.tight_layout() plt.savefig("./nsga3_gen/nsga3_gen" + str(gen) + ".png") plt.close() #====================================================== # Compile statistics about the new population record = stats.compile(pop) logbook.record(gen=gen, evals=len(invalid_ind), **record) print(logbook.stream) return pop, logbook
if __name__ == "__main__": try: pop, stats = main() except KeyboardInterrupt: print("Ctrl + Cで停止しました") pass pop_fit = numpy.array([ind.fitness.values for ind in pop]) k = 0 for ind, fit in zip(pop[:10], pop_fit[:10]): try: k += 1 datlist_list = [fc.read_datfile(file) for file in datfiles] datlist_shaped_list = [ fc.shape_dat(datlist) for datlist in datlist_list ] newdat = fc.interpolate_dat(datlist_shaped_list, decoder(ind, code_division)) fc.write_datfile(datlist=newdat, newfile_name="newfoil" + str(k) + str(".dat")) except Exception as e: print("message:{0}".format(e)) k = 0 for ind, fit in zip(pop, pop_fit): try: k += 1 print(k) print("individual:" + str(ind) + "\nfit:" + str(fit)) except Exception as e: print("message:{0}".format(e))