def _metric(self, data): ret = super()._metric(data) if not self.sliding_window: data = self.data[-self.metric_window_size:] # get necessary data from the current population current = data[-1] c_F, c_ideal, c_nadir = current["F"], current["ideal"], current[ "nadir"] # normalize all previous generations with respect to current ideal and nadir N = [normalize(e["F"], c_ideal, c_nadir) for e in data] # check if the movement of all points is significant if self.all_to_current: c_N = normalize(c_F, c_ideal, c_nadir) if self.perf_indicator == "igd": delta_f = [IGD(c_N).calc(N[k]) for k in range(len(N))] elif self.perf_indicator == "hv": # delta_f = [IGDPlus(c_N).calc(N[k]) for k in range(len(N))] hv = Hypervolume(ref_point=np.ones(c_F.shape[1])) delta_f = [hv.calc(N[k]) for k in range(len(N))] else: delta_f = [IGD(N[k + 1]).calc(N[k]) for k in range(len(N) - 1)] ret["delta_f"] = delta_f return ret
def run(countryname, capacity): problem = ScheduleProblem(country_name=countryname, critical_capacity=capacity, record_all=True) algorithm = NSGA2( pop_size=100, n_offsprings=100, sampling=get_sampling("int_random"), crossover=get_crossover("int_sbx", prob=0.9, eta=15), mutation=get_mutation("int_pm", eta=20), eliminate_duplicates=True ) termination = get_termination("n_gen", 100) res = minimize(problem, algorithm, termination, seed=1, pf=problem.pareto_front(use_cache=False), save_history=True, verbose=True) # create the performance indicator object with reference point (4,4) metric = Hypervolume(ref_point=np.array([1.0, 1.0])) # collect the population in each generation pop_each_gen = [a.pop for a in res.history] with open("./experiments/ga_{}_lastpop.json".format(countryname), 'w') as f: json.dump( {"df":[e.to_dict() for e in problem.last[0]],"x":problem.last[1].tolist()}, f) with open("./experiments/ga_{}_lastobj.json".format(countryname), 'w') as f: json.dump( {"deaths": problem.last_objectives[0].tolist(), "activity":problem.last_objectives[1].tolist()} , f) # Objective Space fig = plt.figure() plot = Scatter(title = "Objective Space") plot.add(res.F) plt.savefig("./experiments/ga_{}_objective.png".format(countryname)) # receive the population in each generation obj_and_feasible_each_gen = [pop[pop.get("feasible")[:,0]].get("F") for pop in pop_each_gen] # calculate for each generation the HV metric hv = [metric.calc(f) for f in obj_and_feasible_each_gen] # function evaluations at each snapshot n_evals = np.array([a.evaluator.n_eval for a in res.history]) # visualize the convergence curve fig = plt.figure() plt.plot(n_evals, hv, '-o') plt.title("Convergence") plt.xlabel("Function Evaluations") plt.ylabel("Hypervolume") plt.savefig("./experiments/ga_{}_hypervolume.png".format(countryname)) plt.show()
reynolds = dspace[:,0] pitch= dspace[:,1] depth = dspace[:,2] #print(dspace) metric = Hypervolume(ref_point=np.array([1.0, 1.0])) # collect the population in each generation pop_each_gen = [a.pop for a in res.history] # receive the population in each generation obj_and_feasible_each_gen = [pop[pop.get("feasible")[:,0]].get("F") for pop in pop_each_gen] # calculate for each generation the HV metric hv = [metric.calc(f) for f in obj_and_feasible_each_gen] # visualze the convergence curve plt.plot(np.arange(len(hv)), hv, '-o') plt.title("Convergence") plt.xlabel("Generation") plt.ylabel("Hypervolume") plt.show() ps = problem.pareto_set(use_cache=False, flatten=False) pf = problem.pareto_front(use_cache=False, flatten=False) # Design Space #plot = Scatter(title = "Design Space", axis_labels="x") #plot.add(res.X, s=30, facecolors='none', edgecolors='r') #res.X design space values
# data of variant variantHV = np.array([]) for i in range(GEN): genHV = 0.0 for file in execFiles: # A = np.reshape(file["A"], (NP,GEN)) A = file["A"] B = file["B"] #C = file["C"] genData = [] for j in range(NP*i, NP*(i+1)): genData.append(np.array([ A[j], B[j], # C[j] ])) genHV = genHV + metric.calc(np.array(genData)) genHV = genHV / float(len(execFiles)) variantHV = np.append(variantHV, genHV) HVData[variant] = variantHV # write HVData in a separate file df = pd.DataFrame(HVData, columns=variants) dir_path = os.path.dirname(os.path.realpath(__file__)) df.to_csv(dir_path + "/files/" + problem + ".csv")
# data of variant variantHV = np.array([]) for gen in range(0, GEN): # sum of the avarage HV of each element genHV = 0.0 for file in variantFiles: populationArray = [] for i in range(NP): elementArray = [] for objIndex in range(NUM_OBJS): elementArray.append(file.iloc[(gen * NUM_OBJS) + objIndex][i]) populationArray.append(np.array(elementArray)) variantArray = np.array(populationArray) # genHV = genHV / float(NP) genHV = genHV + (metric.calc(variantArray) / float(NP)) genHV = genHV / float(len(variantFiles)) variantHV = np.append(variantHV, genHV) HVData[variant] = variantHV # write HVData in a separate file df = pd.DataFrame(HVData, columns=variants) dir_path = os.path.dirname(os.path.realpath(__file__)) df.to_csv(dir_path + "/files/" + problem + ".csv")
feas = np.where(opt.get("feasible"))[0] _F = opt.get("F")[feas] F.append(_F) ''' === Hypvervolume (HV) === ''' import matplotlib.pyplot as plt from pymoo.performance_indicator.hv import Hypervolume # MODIFY - this is problem dependend ref_point = np.array([1.0, 1.0]) # create the performance indicator object with reference point metric = Hypervolume(ref_point=ref_point, normalize=False) # calculate for each generation the HV metric hv = [metric.calc(f) for f in F] fig = plt.figure() # visualze the convergence curve plt.plot(n_evals, hv, '-o', markersize=4, linewidth=2) plt.title("Convergence") plt.xlabel("Function Evaluations") plt.ylabel("Hypervolume") # fig.savefig(LATEX_DIR + 'convergence.eps', format='eps') plt.show() from pymoo.factory import get_visualization, get_decomposition F = res.F weights = np.array([0.01, 0.99]) decomp = get_decomposition("asf")
# sum of the avarage HV of each element genHV = 0.0 for file in variantFiles: populationArray = [] for i in range(NP): populationArray.append( np.array([ file.iloc[(gen * 3)][i], file.iloc[(gen * 3) + 1][i], file.iloc[(gen * 3) + 2][i], ])) variantArray = np.array(populationArray) genHV = genHV + metric.calc(variantArray) genHV = genHV / float(len(variantFiles)) variantHV = np.append(variantHV, genHV) HVData.append(variantHV) x = np.linspace(0, int(len(variantFiles[0]) / 3), int(len(variantFiles[0]) / 3)) for i in range(len(HVData)): if len(x) != len(HVData[i]): print("variant -> " + str(i)) print(len(HVData[i])) plt.scatter(x, HVData[i], s=2, alpha=0.6, label=variants[i]) plt.title(problem)
# i - 1, because generation 1 has index 0 for i in generations2plot: plt.scatter(-history[i-1][:,0],-history[i-1][:,1]) ax4.set_xlabel('Total profit [US$]') ax4.set_ylabel('Natural Vegetation [hectar]') plt.plot(revenue[0],area[0], "sr") plt.legend(["initial", 500, 1000, 1500, 2000, 2500, 3000]) #plt.savefig(default_directory+"/figures/pareto_front_over_generations.png") plt.show() # Hypervolume from pymoo.performance_indicator.hv import Hypervolume # make an array of the generation numbers n_gen = np.array(range(1,len(history)+1)) # set reference point ref_point = np.array([0.0, 0.0]) # create the performance indicator object with reference point metric = Hypervolume(ref_point=ref_point, normalize=False) # calculate for each generation the HV metric hv = [metric.calc(i) for i in history] # visualze the convergence curve fig5, ax5 = plt.subplots(1) ax5.plot(n_gen, hv, '-o', markersize=4, linewidth=2) ax5.set_xlabel("Generation") ax5.set_ylabel("Hypervolume") #plt.savefig(default_directory+"/figures/hypervolume.png") plt.show()