def optimize(results, dir): pg.mp_bfe.init_pool(50) prob = pg.problem(MotGunOptimizationProblem(dir)) bfe = pg.bfe(pg.mp_bfe()) nsga2 = pg.nsga2() nsga2.set_bfe(bfe) algo = pg.algorithm(nsga2) pop = pg.population(prob=prob, size=256, b=bfe) iteration = 1 while True: print(f"\033[31mITERATION: {iteration}\033[m") plt.title(f'Iteration {iteration}') plt.xlabel('Emittance (nm)') plt.ylabel('Charge (fC)') pg.plot_non_dominated_fronts(pop.get_f()) plt.savefig(results / f'{iteration}.png', dpi=300) plt.clf() assert len(pop.get_x()) == len(pop.get_f()) with open(results / f'iteration_{iteration}.txt', 'w+') as f: f.write( '[Mot Z Offset (mm), Phase (deg)] -> [Emittance 4D sqrt (nm), Charge (fC)]\n' ) for i in range(len(pop.get_x())): f.write('{} -> {}\n'.format(pop.get_x()[i], pop.get_f()[i])) pop = algo.evolve(pop) iteration += 1
def plot_2d_evo(popi): magnet_dim = len(popi.get_x()[0]) ndf, dl, dc, ndl = pg.fast_non_dominated_sorting(popi.get_f()) print(pg.sort_population_mo(popi.get_f())) ndf_champ = [] # for j in range(2,200): print(pg.ideal(popi.get_f())[0]) x = np.linspace(pg.ideal(popi.get_f())[0],0) y = np.zeros(50)+(1) for j in range(2,100): plt.cla() plt.plot(x,y,linestyle="dashed",color="red") print(ndf[0]) ndf_champ.append([popi.get_f()[i] for i in ndf[j]]) # ax = pg.plot_non_dominated_fronts(ndf_champ[0],comp=[0,j]) # ax.plot(color="C{}".format(j)) ax = pg.plot_non_dominated_fronts(popi.get_f()[0:j]) ax.set_xlabel('resolution') ax.set_ylabel('xangle_e_min') ax.set_ylim(1e-3,1000) ax.set_yscale('log') # print(ndf_champ, ndf[0]) # print(ndf) plt.savefig("popi{}".format(j)) return
def plot_2d_evo(popi): magnet_dim = len(popi.get_x()[0]) ndf, dl, dc, ndl = pg.fast_non_dominated_sorting(popi.get_f()[:, :2]) # print(pg.sort_population_mo(popi.get_f())) ndf_champ = [] # for j in range(2,200): # print(pg.ideal(popi.get_f())[0]) print(ndf) # x = np.linspace(pg.ideal(popi.get_f())[0],0) # y = np.zeros(50)+(1) old_ndf, new_ndf = np.zeros(1), np.zeros(1) n_plots = 0 for j in range(2, len(popi.get_f())): # print(x,y) # plt.plot(x,y,linestyle="dashed",color="red") # print(ndf) # ndf_champ.append([popi.get_f()[i] for i in ndf[j]]) # ax = pg.plot_non_dominated_fronts(ndf_champ[0],comp=[0,1]) # ax.plot(color="C{}".format(j)) ndf, dl, dc, ndl = pg.fast_non_dominated_sorting(popi.get_f()[0:j, :2]) # print(ndf) new_ndf = np.array(ndf[0]) if not np.array_equal(new_ndf, old_ndf): if len(ndf[0]) <= 1: continue n_plots += 1 plt.cla() ax = pg.plot_non_dominated_fronts(popi.get_f()[ndf[0]], comp=[0, 1]) ax.set_ylabel(fNames[1]) ax.set_xlabel(fNames[0]) ax.set_ylim(1e-1, 1e1) ax.set_yscale('log') ax.set_xlim(0.1, 10.0) ax.set_xscale('log') ax.axvline(x=fNom[0], linestyle="dashed", color="red") # axs[plot_y].axvline(x=best_point[0],linestyle="dotted",color="blue") ax.axhline(y=1.0, linestyle="dashed", color="red") # ax.set_xlabel('resolution') # ax.set_ylabel('xangle_e_min') # ax.set_ylim(1e-3,1000) # ax.set_yscale('log') # pri nt(ndf_champ, ndf[0]) # pri nt(ndf) plt.savefig("popi{}".format(n_plots)) old_ndf = np.array(ndf[0]) return
def getBestResult(self, dim_importance=(1,1), percentil=.9, plot=False): self.optimizationData = pickle.load(open("../data/optimizationPopulation.dat", "rb")) # choose best_index #normalize: take into account that it goes the other way round best_fitnesses_norm = self.optimizationData['best_fitnesses'] - np.max(self.optimizationData['best_fitnesses'], axis=0) best_fitnesses_norm = best_fitnesses_norm/np.min(best_fitnesses_norm, axis=0) best_fitnesses_norm = best_fitnesses_norm*dim_importance/np.sum(dim_importance) best_fitnesses_norm_aux = np.sum(best_fitnesses_norm, axis=1) best_index = np.argsort(best_fitnesses_norm_aux) aux = int(np.floor(len(best_index)*(percentil))) if aux >= len(best_index): aux = aux - 1 best_index = best_index[aux] best_portfolioAllocation = self.optimizationData['best_portfolioAllocations'][best_index] best_portfolioAllocationDirection = self.optimizationData['best_portfolioAllocationDirections'][best_index] best_portfolioAllocationFitness = self.optimizationData['best_fitnesses'][best_index] if plot: pygmo.plot_non_dominated_fronts(self.optimizationData['best_fitnesses']) plt.plot( best_portfolioAllocationFitness[0], best_portfolioAllocationFitness[1], 'ro', markersize=10) plt.show() return best_portfolioAllocation, best_portfolioAllocationDirection
def finish(self): if self.optimizer == "brute": self.modelparms.write("\n") self.modelprediction.write("\n") self.modeldiff.write("\n") self.modelparms.close() self.modelprediction.close() self.modeldiff.close() return 1 self.x = np.array(self.x) self.f_A = np.array(self.f_A) self.rmsd_A = np.array(self.rmsd_A) self.f_B = np.array(self.f_B) self.rmsd_B = np.array(self.rmsd_B) self.R2_A = np.array(self.R2_A) self.R2_B = np.array(self.R2_B) ### Write out best result for selection A ### ------------------------------------- if self.fitter.decomp: ### ndf (list of 1D NumPy int array): the non-dominated fronts ### dl (list of 1D NumPy int array): the domination list ### dc (1D NumPy int array) : the domination count ### ndr (1D NumPy int array) : the non-domination ranks ndf, dl, dc, ndr = pygmo.fast_non_dominated_sorting(self.f_A) ax_A = pygmo.plot_non_dominated_fronts(self.f_A) ax_A.figure.savefig("%spareto.selectionA.png" % self.prefix, dpi=1000) ax_A.figure.clear("all") ordered_ndf = list() for front in ndf: ordered_ndf.append(pygmo.sort_population_mo(self.f_A[front])) else: ordered_ndf = np.argsort(self.f_A, axis=0) self.modelparms.write("### Best result (A)\n") self.modelprediction.write("### Best result (A)\n") self.modeldiff.write("### Best result (A)\n") for front_count, front in enumerate(ordered_ndf): for solution_i in front: step = self.step[solution_i] x = self.x[solution_i] f_A = self.f_A[solution_i] f_B = self.f_B[solution_i] rmsd_A = self.rmsd_A[solution_i] rmsd_B = self.rmsd_B[solution_i] R2_A = self.R2_A[solution_i] R2_B = self.R2_B[solution_i] self.modelparms.write("%d/%d " % (step, front_count)) self.modelprediction.write("%d/%d " % (step, front_count)) self.modeldiff.write("%d/%d " % (step, front_count)) self.fitter.gist_functional(x) self.fitter._f_process(x) if self.mode in [0, 3, 5]: for i in self.parmidx: self.modelparms.write("%6.3f " % x[i]) self.modelparms.write("%6.3f " % f_A[0]) self.modelparms.write("%6.3f " % f_B[0]) self.modelparms.write("%6.3f " % R2_A) self.modelparms.write("%6.3f " % R2_B) self.modelparms.write("%6.3f " % rmsd_A) self.modelparms.write("%6.3f " % rmsd_B) elif self.mode in [1, 4, 6, 7]: ### Energy Output for i in self.parmidx: self.modelparms.write("%6.3f " % x[i]) self.modelparms.write("%6.3f " % f_A[0]) self.modelparms.write("%6.3f " % f_B[0]) self.modelparms.write("%6.3f " % R2_A[0]) self.modelparms.write("%6.3f " % R2_B[0]) self.modelparms.write("%6.3f " % rmsd_A[0]) self.modelparms.write("%6.3f " % rmsd_B[0]) self.modelparms.write("\n") ### Entropy Output self.modelparms.write("%d/%d " % (step, front_count)) for i in self.parmidx: self.modelparms.write("%6.3f " % x[i]) self.modelparms.write("%6.3f " % f_A[1]) self.modelparms.write("%6.3f " % f_B[1]) self.modelparms.write("%6.3f " % R2_A[1]) self.modelparms.write("%6.3f " % R2_B[1]) self.modelparms.write("%6.3f " % rmsd_A[1]) self.modelparms.write("%6.3f " % rmsd_B[1]) else: mode_error(self.mode) if self.mode in [0, 3, 5]: for i in range(self.N_len): self.modelprediction.write("%6.3f " % self.fitter._f[i]) diff = self.fitter._exp_data[i] - self.fitter._f[i] self.modeldiff.write("%6.3f " % diff) elif self.mode in [1, 4, 6, 7]: for i in range(self.N_len): self.modelprediction.write("%6.3f " % self.fitter._f[i, 0]) diff = self.fitter._exp_data[i, 0] - self.fitter._f[i, 0] self.modeldiff.write("%6.3f " % diff) self.modelprediction.write("\n") self.modelprediction.write("%d/%d " % (step, front_count)) self.modeldiff.write("\n") self.modeldiff.write("%d/%d " % (step, front_count)) for i in range(self.N_len): self.modelprediction.write("%6.3f " % self.fitter._f[i, 1]) diff = self.fitter._exp_data[i, 1] - self.fitter._f[i, 1] self.modeldiff.write("%6.3f " % diff) else: mode_error(self.mode) self.modelparms.write("\n") self.modelprediction.write("\n") self.modeldiff.write("\n") self.modelparms.write("\n") self.modelprediction.write("\n") self.modeldiff.write("\n") self.modelparms.close() self.modelprediction.close() self.modeldiff.close()
def get_nobj(self): return 2 def get_name(self): return "Custom Function" def get_extra_info(self): return "\tDimensions: " + str(self.dim) prob = pg.problem(sphere_function(3)) #print(prob) algo = pg.algorithm(pg.moead(gen = 1)) #algo = pg.algorithm(pg.bee_colony(gen=20, limit=20)) pop = pg.population(prob=prob, size=100) pop = algo.evolve(pop) #print(pop.get_f()) from matplotlib import pyplot as plt ax = pg.plot_non_dominated_fronts(pop.get_f()) #plt.plot(ax) #plt.ylabel('Traveled path $l_1$') #plt.xlabel('Lateral velocity $l_2$') #plt.title("Objective space with a Pareto front") #plt.savefig('pareto_solutions.png')
def plot_4d(popi,filename,df): pop = None for i_cluster in range(10): df_i = df.loc[(df['kcluster'] == i_cluster)] magnet_dim = 15 p_optimizeRes = pg.problem(optimizeRes(magnet_dim)) nobj = p_optimizeRes.get_nobj() if pop == None: pop = pg.population(p_optimizeRes) nrow, ncol = df_i.shape for i in df_i.index: append=True xs = [] for j in range(1,magnet_dim+1): xs.append(df_i["q"+str(j)][i]) xs = np.asarray(xs) fs = [] for j in range(magnet_dim,magnet_dim+nobj): # if i == 0: # print(df.iloc[i,magnet_dim:magnet_dim+p_optimizeRes.get_nobj()]) fs.append(df.iloc[i,j]) if append: pop.push_back(xs,f=fs) popi = pop sort_param = 3 good_results=0 magnet_dim = len(popi.get_x()[0]) hv = pg.hypervolume(popi) ref_point = np.zeros(optimized_params)+1e10 ndf, dl, dc, ndl = pg.fast_non_dominated_sorting(popi.get_f()) plot_x, plot_y = 0,0 fig, axs = plt.subplots(optimized_params-1,sharex=True) fig.suptitle('Pareto Fronts of each parameter vs. BeamSpotSize at FP4') axs[optimized_params-2].set_xlabel(fNames[sort_param]) reduced_ndf = [] first = True # df_closest = df.loc[(df['kcluster'] == i_cluster)] for j in range(0,optimized_params-1): ndf_champ = [] axs[plot_y].axvline(x=fNom[0],linestyle="dashed",color="red") axs[plot_y].axhline(y=1.0,linestyle="dashed",color="red") for i in ndf[0]: check_val=1e9 if np.all(np.array(popi.get_f()[i]) < check_val) == True: good_results+=1 # print(filename[-6:-4], good_results, popi.get_f()[i]) ndf_champ.append(popi.get_f()[i]) reduced_ndf.append(i) try: pg.plot_non_dominated_fronts(ndf_champ,comp=[sort_param,j],axes=axs[plot_y]) # if j == 1: # print(filename[-6:-4], len(ndf_champ)) except: print(filename[-6:-4], "no better than nominal solutions") return if "closest" in df_i.columns: df_closest = df_i.loc[df['closest']==True] df_closest = df_closest.reset_index(drop=True) # print(df_closest.iloc[:,15:19]) for i_closest in df_closest.index: axs[plot_y].text(df_closest.iloc[:,18][i_closest],df_closest.iloc[:,15+j][i_closest],str(df_closest['kcluster'][0]+1),color='red') axs[plot_y].set_ylabel(fNames[j]) axs[plot_y].set_yscale('log') axs[plot_y].set_xscale('log') plot_y += 1 fig.tight_layout() fig.savefig(filename+"{}_paretos.png".format(i_cluster)) plt.cla() fig2, axs2 = plt.subplots(4,4) plot_x, plot_y = 0,0 reduced_qs = np.array(popi.get_x())[reduced_ndf] ycolumns = [] for i in range(magnet_dim): ycolumns.append('y{}'.format(i)) df_i = pd.DataFrame(reduced_qs, columns = ycolumns) qNom = np.zeros(magnet_dim) for i in range(magnet_dim): if plot_x > 3: plot_x, plot_y = 0, plot_y+1 axs2[plot_y,plot_x] = df_i['y{0}'.format(i)].plot.hist(ax=axs2[plot_y,plot_x],bins=100,range=(-2,2)) # axs2[plot_y,plot_x].axvline( x = qNom[i], ymin=0,ymax=20,color='red',linestyle='dashed') # axs[plot_y,plot_x].axvline( x = max_y[i], ymin=0,ymax=20,color='green',linestyle='dashed') axs2[plot_y,plot_x].axes.yaxis.set_visible(False) # axs2[plot_y,plot_x].axes.set_yscale("log") # axs2[plot_y,plot_x].axes.set_ylim(0.1,20) xlower, xupper = popi.problem.get_bounds() xlower, xupper = np.min(xlower), np.max(xupper) axs2[plot_y,plot_x].axes.set_xlim(xlower,xupper) axs2[plot_y,plot_x].set_title("q{0}".format(i+1)) y_min, y_max = axs2[plot_y,plot_x].get_ylim() df_closest['yplot'] = pd.Series(df_closest['kcluster'][0]).apply(lambda x: x/(10)*(y_max-y_min)+y_min) # print(df_closest.iloc[:,:15]) # if "closest" in df.columns: for i_closest in df_closest.index: axs2[plot_y,plot_x].text(df_closest["q{0}".format(i+1)][i_closest],df_closest['yplot'][i_closest],str(df_closest['kcluster'][0]+1),color='red') plot_x += 1 fig2.delaxes(axs2[plot_y,plot_x]) fig2.tight_layout() plt.savefig(filename + "{}_magnet_hists.png".format(i_cluster)) return
def plot_2d(popi,filename): magnet_dim = len(popi.get_x()[0]) hv = pg.hypervolume(popi) ref_point = hv.refpoint() best_point = (popi.get_f()[hv.greatest_contributor(ref_point)]) ndf, dl, dc, ndl = pg.fast_non_dominated_sorting(popi.get_f()) # print(pg.sort_population_mo(popi.get_f())) ndf_champ = [] # for j in range(2,200): # print(pg.select_best_N_mo(popi.get_f(),10)) best_10 = (pg.select_best_N_mo(popi.get_f(),10)) for i in best_10: print(i, np.power(np.zeros(magnet_dim)+2,popi.get_x()[i]), popi.get_f()[i]) x = np.linspace(pg.ideal(popi.get_f())[0],0) y = np.zeros(50)+(1) plot_x, plot_y = 0,0 objs = len(popi.get_f()[0]) fig, axs = plt.subplots(objs-1,sharex=True) fig.suptitle('ratios to Nom vs Resolution') log_res, log_x = [], [] for i in ndf[0]: log_res.append(np.log(popi.get_f()[i][0])/np.log(10)) log_x.append(np.log(popi.get_f()[i][1])/np.log(10)) if max(popi.get_f()[i]) < 1000000: print(i, np.power(np.zeros(magnet_dim)+2,popi.get_x()[i]), popi.get_f()[i]) if objs == 2: j = 1 axs.set_xlabel('resolution') axs.axvline(x=fNom[0],linestyle="dashed",color="red") axs.axvline(x=best_point[0],linestyle="dotted",color="blue") axs.axhline(y=1.0,linestyle="dashed",color="red") ndf_champ.append([popi.get_f()[i] for i in ndf[0]]) pg.plot_non_dominated_fronts(ndf_champ[0],comp=[0,j],axes=axs) # ax.plot df = (color="C{}".format(j)) # ax = pg.plot_non_dominated_fronts(popi.get_f()[0:j]) axs.set_ylabel(fNames[2]) # axs.set_ylim(0.9,1.1) axs.set_yscale('log') # axs.set_xlim(0.8,1.2) axs.set_xscale('log') else: axs[objs-2].set_xlabel('resolution') for j in range(1,2): # axs[plot_y].plot(x,y,linestyle="dashed",color="red") axs[plot_y].axvline(x=fNom[0],linestyle="dashed",color="red") axs[plot_y].axvline(x=best_point[0],linestyle="dotted",color="blue") axs[plot_y].axhline(y=1.0,linestyle="dashed",color="red") ndf_champ.append([popi.get_f()[i] for i in ndf[0]]) pg.plot_non_dominated_fronts(ndf_champ[0],comp=[0,j],axes=axs[plot_y]) # ax.plot(color="C{}".format(j)) # ax = pg.plot_non_dominated_fronts(popi.get_f()[0:j]) axs[plot_y].set_ylabel(fNames[2]) # axs[plot_y].set_ylim(1e-1,1e1) axs[plot_y].set_yscale('log') # axs[plot_y].set_xlim(0.1,10.0) # axs[plot_y].set_xscale('log') plot_y += 1 # print(ndf_champ, ndf[0]) # print(ndf) fig.tight_layout() fig.savefig(filename+"_ndf.png") plt.clf() # plt.plot(log_res, log_x,"o", linestyle="none", ) # fig.savefig(filename+"_logndf.png") return
def main(): generation = 0 if len(sys.argv)>2: if(sys.argv[2] == 'show'): show = True else: show=False else: show=False file_base_name = sys.argv[1] plotdata = plotDataOut() save = save_data() prob = problem(psm.problem_susmicro()) pop = population(prob, size = 60, seed = 3453412) specific_algo = nsga2(gen = 1, seed = 3453213) # pop = population(prob, size = 210, seed = 3453412) # algo = algorithm(moead(gen = 20)) # 250 algo = algorithm(specific_algo) initial_inputs = pop.get_x() initial_outputs = pop.get_f() ndf, dl, dc, ndl = fast_non_dominated_sorting(initial_outputs) save.initial_ndf = copy.deepcopy(ndf) save.initial_inputs = copy.deepcopy(initial_inputs) save.initial_outputs = copy.deepcopy(initial_outputs) start = timer() for generation in range(0, 50): save.pop = copy.deepcopy(pop) ################# initial pop ################## #get a list of the non-dominated front of the first set (random points) ndf, dl, dc, ndl = fast_non_dominated_sorting(pop.get_f()) ndf_x = [] for val in ndf[0]: ndf_x.append(pop.get_x()[val]) save.initial_surr_ndf_x = copy.deepcopy(ndf_x) print("evaluate the initial ndf in surrogate") inputs = pop.get_x() outputs = pop.get_f() save.inputs = copy.deepcopy(inputs) save.outputs = copy.deepcopy(outputs) data_file = "./pop_"+str(generation).zfill(4)+".pickle" save.pop = copy.deepcopy(pop) try: pickle.dump(save, open(data_file, "wb+" ) ) except: print("error opening '"+data_file+"' pickle file") exit() pop = algo.evolve(pop) end = timer() ndf, dl, dc, ndl = fast_non_dominated_sorting(pop.get_f()) ndf_x = [] for val in ndf[0]: ndf_x.append(pop.get_x()[val]) save.final_surr_ndf_x = copy.deepcopy(ndf_x) final_inputs = pop.get_x() final_outputs = pop.get_f() save.inputs = copy.deepcopy(final_inputs) save.outputs = copy.deepcopy(final_outputs) plotdata.final_inputs = copy.deepcopy(final_inputs) plotdata.final_outputs = copy.deepcopy(final_outputs) with open(file_base_name+"_plot_data.pickle","wb") as f: f.write(pickle.dumps(plotdata)) # Plot fig, ax = plt.subplots() # x_vals_f = [(row[0] + row[1]) / 2.0 for row in final_outputs] x_vals_f = [row[0] for row in final_outputs]#[dist(row[0], row[1]) for row in final_outputs] y_vals_f = [row[1] for row in final_outputs]#[row[2] * 2.0 for row in final_outputs] ax.scatter(x_vals_f, y_vals_f, c="purple", alpha=0.6, label='Final ndf surrogate model') # x_vals_i = [(row[0] + row[1])/2.0 for row in initial_outputs] x_vals_i = [row[0] for row in initial_outputs]#[dist(row[0], row[1]) for row in initial_outputs] y_vals_i = [row[1] for row in initial_outputs]#[row[2] * 2.0 for row in initial_outputs] ax.scatter(x_vals_i, y_vals_i, c="green", alpha=0.6, label='initial evaluation') ax.set_title('Initial to Surrogate population') ax.set_ylabel('ppf') ax.set_xlabel('1/radius') ax.legend(loc=1) #fig.savefig('surrogate-wims.png') #fig.show() # if you are debugging probably just show to screen if(show): print("\a") plt.show() fig.savefig(file_base_name+'-graph.svg') else: # if not debugging save the figure fig.savefig(file_base_name+'-graph.png') fig.savefig(file_base_name+'-graph.svg') # Plot only NDF #fig, ax = plt.subplots() initials = [[a,b] for a,b in zip(x_vals_i,y_vals_i)] finals = [[a,b] for a,b in zip(x_vals_f,y_vals_f)] plt.ylim([0,6]) plt.xlim([0,0.6]) ax = plot_non_dominated_fronts(initials, marker='o') plt.ylim([0,6]) plt.xlim([0,0.6]) ax = plot_non_dominated_fronts(finals, marker='x',) ax.set_title('Surrogate NDF to Serpent NDF') ax.set_ylabel('ppf') ax.set_xlabel('1/radius (relative)') # ax.legend(loc=1) if(show): print("\a") plt.show() fig.savefig(file_base_name+'-ndf_only.svg') else: # if not debugging save the figure fig.savefig(file_base_name+'-ndf_only.png') fig.savefig(file_base_name+'-ndf_only.svg') ndf_simplified = [] # copy.deepcopy(ndf[0]) for idx in range(len(pop.get_x())):#ndf[0]: x = pop.get_x()[idx] new_row = [aw_round(val) for val in x] ndf_simplified.append(new_row) #ndf_simplified = list(set(ndf_simplified)) print(str(len(ndf_simplified))) ndf_no_repeat = np.unique(ndf_simplified, axis=0) print("data from populations:"+str(len(pop))+" "+str(len(ndf_no_repeat))) print(str(ndf_no_repeat)) line = "input_test_list = [" # get whole final population and print it out... for vals in ndf_no_repeat: line +="[" for v in vals: line += str(v)+", " line += "],\n" line += "]\n" print(line) ndf, dl, dc, ndl = fast_non_dominated_sorting(pop.get_f()) for idx in ndf_simplified: f = ndf_simplified#pop.get_f()[idx] print("f: "+str(f)) print("NDF len:" + str(len(ndf_no_repeat))) print("Execution time for evolution: " + str(end-start))
def plot_non_dominated_fronts(self): return pg.plot_non_dominated_fronts(self.pop.get_f())
def plot_4d(popi, filename): magnet_dim = len(popi.get_x()[0]) hv = pg.hypervolume(popi) # ref_point = hv.refpoint() ref_point = (1e10, 1e10, 1e10, 1e10) best_point = (popi.get_f()[hv.greatest_contributor(ref_point)]) ndf, dl, dc, ndl = pg.fast_non_dominated_sorting(popi.get_f()) # print(pg.sort_population_mo(popi.get_f())) ndf_champ = [] # for j in range(2,200): # print(pg.select_best_N_mo(popi.get_f(),10)) best_10 = (pg.select_best_N_mo(popi.get_f(), 10)) # for i in best_10: # print(i, np.power(np.zeros(magnet_dim)+2,popi.get_x()[i]), popi.get_f()[i]) x = np.linspace(pg.ideal(popi.get_f())[0], 0) y = np.zeros(50) + (1) plot_x, plot_y = 0, 0 fig, axs = plt.subplots(3, sharex=True) fig.suptitle('Pareto Fronts of each parameter vs. BeamSpotSize at FP4') axs[optimized_params - 2].set_xlabel(fNames[3]) # for i in ndf[0]: # if max(popi.get_f()[i]) < 10: # print(i, np.power(np.zeros(magnet_dim)+2,popi.get_x()[i]), popi.get_f()[i]) reduced_ndf = [] first = True check_val = 1e9 for j in range(0, 3): # axs[plot_y].plot(x,y,linestyle="dashed",color="red") axs[plot_y].axvline(x=fNom[0], linestyle="dashed", color="red") # axs[plot_y].axvline(x=best_point[0],linestyle="dotted",color="blue") axs[plot_y].axhline(y=1.0, linestyle="dashed", color="red") for i in ndf[0]: if np.all(np.array(popi.get_f()[i]) < check_val) == True: # if np.all(np.array(popi.get_f()[i]) < 1) == True and first: ndf_champ.append(popi.get_f()[i]) reduced_ndf.append(i) first = False try: pg.plot_non_dominated_fronts(ndf_champ, comp=[3, j], axes=axs[plot_y]) if j == 1: print(filename[-6:-4], len(ndf_champ)) except: print(filename[-6:-4], "no better than nominal solutions") return # ax.plot(color="C{}".format(j)) # ax = pg.plot_non_dominated_fronts(popi.get_f()[0:j]) axs[plot_y].set_ylabel(fNames[j]) # axs[plot_y].set_ylim(1e-1,1e1) axs[plot_y].set_yscale('log') # axs[plot_y].set_xlim(0.1,10.0) axs[plot_y].set_xscale('log') plot_y += 1 # print(ndf_champ, ndf[0]) # print(ndf) fig.tight_layout() fig.savefig(filename + "_ndf.png") plt.cla() fig2, axs2 = plt.subplots(3, 4) plot_x, plot_y = 0, 0 reduced_qs = np.array(popi.get_x())[reduced_ndf] # print(reduced_qs) df = pd.DataFrame(reduced_qs, columns=[ 'y0', 'y1', 'y2', 'y3', 'y4', 'y5', 'y6', 'y7', 'y8', 'y9', 'y10' ]) qNom = np.zeros(magnet_dim) for i in range(magnet_dim): if plot_x > 3: plot_x, plot_y = 0, plot_y + 1 axs2[plot_y, plot_x] = df['y{0}'.format(i)].plot.hist(ax=axs2[plot_y, plot_x], bins=20, range=(-1, 1)) axs2[plot_y, plot_x].axvline(x=qNom[i], ymin=0, ymax=20, color='red', linestyle='dashed') # axs[plot_y,plot_x].axvline( x = max_y[i], ymin=0,ymax=20,color='green',linestyle='dashed') axs2[plot_y, plot_x].axes.yaxis.set_visible(False) axs2[plot_y, plot_x].axes.set_xlim(-1, 1) axs2[plot_y, plot_x].set_title("q{0}".format(i + 1)) plot_x += 1 fig2.delaxes(axs2[plot_y, plot_x]) fig2.tight_layout() plt.savefig(filename + ".png") return