def moea(name, solsize, popsize, wscalar_, moea_type, max_gen=float('inf'), timeLimit=float('inf')): from platypus import HUX, BitFlip, TournamentSelector from platypus import Problem, Binary from platypus import NSGAII, NSGAIII, SPEA2 from platyplus.operators import varOr from platyplus.algorithms import SMSEMOA time_start = time.perf_counter() logger.info('Running '+moea_type+' in '+name) prMutation = 0.1 prVariation = 1-prMutation vartor = varOr(HUX(), BitFlip(1), prVariation, prMutation) def evalKnapsack(x): return wscalar_.fobj([xi[0] for xi in x]) problem = Problem(wscalar_.N, wscalar_.M) problem.types[:] = [Binary(1) for i in range(wscalar_.N)] problem.function = evalKnapsack if moea_type in ['NSGAII', 'NSGAII-2', 'NSGAII-4']: alg = NSGAII(problem, population_size=popsize, selector=TournamentSelector(1), variator=vartor) elif moea_type in ['NSGAIII', 'NSGAIII-2', 'NSGAIII-4']: alg = NSGAIII(problem, divisions_outer=3, population_size=popsize, selector=TournamentSelector(1), variator=vartor) elif moea_type in ['SPEA2', 'SPEA2-2', 'SPEA2-4']: alg = SPEA2(problem, population_size=popsize, selector=TournamentSelector(1), variator=vartor) elif moea_type in ['SMSdom']: alg = SMSEMOA(problem, population_size=popsize, selector=TournamentSelector(1), variator=vartor, selection_method = 'nbr_dom') elif moea_type in ['SMShv']: alg = SMSEMOA(problem, population_size=popsize, selector=TournamentSelector(1), variator=vartor, selection_method = 'hv_contr') gen = 1 while gen<max_gen and time.perf_counter()-time_start<timeLimit: alg.step() gen+=1 alg.population_size = solsize alg.step() moeaSols = [evalKnapsack(s.variables) for s in alg.result] moea_time = time.perf_counter() - time_start logger.info(moea_type+' in '+name+' finnished.') return moeaSols, moea_time
from platypus import nondominated from hypervolume import hypervolume import ast import random random.seed(0) for d in range(1, 10): for g in range(1, 10): hyp = [] nfes = [] for i in range(10): problem = Problem(2, 2, 2) problem.types[:] = [Real(0, 5), Real(0, 3)] problem.constraints[:] = "<=0" problem.function = BNH algorithm = NSGAIII(problem, d * problem.nvars) algorithm.run(d * g * problem.nvars) funcname = 'BNH' # if not os.path.exists(funcname): # os.makedirs(funcname) nondominated_solutions = nondominated(algorithm.result) ref = np.array([140, 50]) obj = [] for s in nondominated_solutions: lijst = str(s.objectives) obj.append(ast.literal_eval(lijst)) obj = np.array(obj) # np.savetxt(str(funcname)+'/'+str(funcname)+'_pf_run_'+str(i)+'.csv', obj, delimiter=',') hyp.append(hypervolume(obj, ref))
from platypus import NSGAIII, DTLZ2 # define the problem definition problem = DTLZ2(3) # instantiate the optimization algorithm algorithm = NSGAIII(problem, divisions_outer=12) # optimize the problem using 10,000 function evaluations algorithm.run(1000) # plot the results using matplotlib import matplotlib.pyplot as plt from mpl_toolkits.mplot3d import Axes3D fig = plt.figure() ax = fig.add_subplot(111, projection='3d') ax.scatter([s.objectives[0] for s in algorithm.result], [s.objectives[1] for s in algorithm.result], [s.objectives[2] for s in algorithm.result]) plt.show()
from platypus import NSGAIII, DTLZ2, Recorder from platypus import MainWindow from PyQt5.QtGui import QApplication # define the problem definition problem = DTLZ2(3) # instantiate the optimization algorithm algorithm = NSGAIII(problem, divisions_outer=12) # optimize the problem using 10,000 function evaluations recorder = Recorder(save_result=True, save_all=False) # GUI version app = QApplication([]) window = MainWindow(nobjs=problem.nobjs, algorithm=algorithm, nfe=10000, recorder=recorder) app.exec_() # # non-GUI version # algorithm.run(10000, recorder=recorder) # plot the results using matplotlib import matplotlib.pyplot as plt from mpl_toolkits.mplot3d import Axes3D fig = plt.figure() ax = fig.add_subplot(111, projection='3d') ax.scatter([s.objectives[0] for s in algorithm.result], [s.objectives[1] for s in algorithm.result], [s.objectives[2] for s in algorithm.result]) plt.show()
hyp = [] for i in range(5): ref = np.array([5000, 2]) problem = Problem(6, 2, 16) problem.types[:] = [ Real(5.0, 9.0), Real(16.0, 22.0), Real(5.0, 9.0), Real(12.0, 16.0), Real(-2.8, 9.8), Real(-1.6, 3.4) ] problem.constraints[:] = "<=0" problem.function = problemCall algorithm = NSGAIII(problem, len(ref)) algorithm.run(200) nondominated_solutions = nondominated(algorithm.result) obj = [] for s in nondominated_solutions: lijst = str(s.objectives) obj.append(ast.literal_eval(lijst)) obj = np.array(obj) hyp.append(hypervolume(obj, ref)) print('ship', np.mean(hyp)) print('ship', np.max(hyp)) print('ship', np.std(hyp)) hyp = [] for i in range(100): ref = np.array([7000, 1700])
fs = np.array(fs) feasible = np.sum(cs <= 0, axis=1) == 3 for i in range(1, len(fs)): fi = fs[:i][feasible[:i]] nsgaiihv.append(hypervolume(fi, ref)) nsgaiihv = nsgaiihv[:30] print(nsgaiihv[-1]) fs = [] cs = [] random.seed(0) problem = Problem(2, 3, 3) problem.types[:] = [Real(-4, 4), Real(-4, 4)] problem.constraints[:] = "<=0" problem.function = TRICOP algorithm = NSGAIII(problem, 1) algorithm.run(30) nsgaiiihv = [] cs = np.array(cs) fs = np.array(fs) feasible = np.sum(cs <= 0, axis=1) == 3 for i in range(1, len(fs)): fi = fs[:i][feasible[:i]] nsgaiiihv.append(hypervolume(fi, ref)) nsgaiiihv = nsgaiiihv[:30] print(nsgaiiihv[-1]) class TRICOP_c(Problem): def __init__(self): super().__init__(n_var=2, n_obj=3, n_constr=3)
def _pick_algorithm(myproblem, algorithm, population, mutation_probability, current_solution, evaluator=None): """ Return a serial or parallel platypus.Algorithm object based on input string :param myproblem: EZFF Problem to be optimized :type myproblem: Problem :param algorithm: EZFF Algorithm to use for optimization. Allowed options are ``NSGAII``, ``NSGAIII`` and ``IBEA`` :type algorithm: str :param population: Population size for genetic algorithms :type population: int :param evaluator: Platypus.Evaluator in case of parallel execution :type evaluator: Platypus.Evaluator """ if mutation_probability is None: variator = GAOperator(SBX(), PM()) else: variator = GAOperator(SBX(), PM(probability=mutation_probability)) print('Using provided mutation probability') if algorithm.lower().upper() == 'NSGAII': if evaluator is None: if current_solution is None: return NSGAII(myproblem, population_size=population, variator=variator) else: return NSGAII(myproblem, population_size=population, variator=variator, generator=InjectedPopulation( current_solution[0:population])) else: if current_solution is None: return NSGAII(myproblem, population_size=population, variator=variator, evaluator=evaluator) else: return NSGAII(myproblem, population_size=population, variator=variator, generator=InjectedPopulation( current_solution[0:population]), evaluator=evaluator) elif algorithm.lower().upper() == 'NSGAIII': num_errors = len(myproblem.directions) divisions = int( np.power(population * np.math.factorial(num_errors - 1), 1.0 / (num_errors - 1))) + 2 - num_errors divisions = np.maximum(1, divisions) if evaluator is None: if current_solution is None: return NSGAIII(myproblem, divisions_outer=divisions, variator=variator) else: return NSGAIII(myproblem, divisions_outer=divisions, variator=variator, generator=InjectedPopulation( current_solution[0:population])) else: if current_solution is None: return NSGAIII(myproblem, divisions_outer=divisions, variator=variator, evaluator=evaluator) else: return NSGAIII(myproblem, divisions_outer=divisions, variator=variator, generator=InjectedPopulation( current_solution[0:population]), evaluator=evaluator) elif algorithm.lower().upper() == 'IBEA': if evaluator is None: if current_solution is None: return IBEA(myproblem, population_size=population, variator=variator) else: return IBEA(myproblem, population_size=population, variator=variator, generator=InjectedPopulation( current_solution[0:population])) else: if current_solution is None: return IBEA(myproblem, population_size=population, variator=variator, evaluator=evaluator) else: return IBEA(myproblem, population_size=population, variator=variator, generator=InjectedPopulation( current_solution[0:population]), evaluator=evaluator) else: raise Exception( 'Please enter an algorithm for optimization. NSGAII , NSGAIII , IBEA are supported' )
problem.function = uswitch_objective # Run optimization in parallel n_proc = 4 n_evals = 100000 alg_name = 'NSGAII' #alg_name = 'NSGAIII' #alg_name = 'SPEA2' start_time = time.time() with ProcessPoolEvaluator(n_proc) as evaluator: if alg_name=='NSGAII': algorithm = NSGAII(problem,evaluator=evaluator) elif alg_name=='NSGAIII': divs = 20 alg_name=alg_name+str(divs) algorithm = NSGAIII(problem,divisions_outer=div,evaluator=evaluator) elif alg_name=='SPEA2': algorithm = SPEA2(problem,evaluator=evaluator) else: print("Using NSGAII algorithm by default") algorithm = NSGAII(problem,evaluator=evaluator) algorithm.run(n_evals) print("Total run time = {:.2f} hours".format((time.time()-start_time)/3600.)) # Save Results save_dir = "./Data/U_switch/plat/" pareto_file_name = save_dir + "pareto_front_{0}_{1}_{2}_".format(d,tau_p,n_evals) + alg_name + "_dtmax{0}.npy".format(dtmax) points = [] costs = [] for s in algorithm.result: points.append(s.variables[:])
# print(solution.objectives[:]) def random(self): solution = ps.Solution(self) solution.variables[:] = [ random.uniform(0, 5) for _ in range(self.types) ] solution.evaluate() return solution # define the problem definition problem = MyProblem() # instantiate the optimization algorithm algorithm = NSGAIII(problem, 20) # optimize the problem using 10,000 function evaluations algorithm.run(10000) # plot the results using matplotlib import matplotlib.pyplot as plt plt.scatter([s.objectives[0] for s in algorithm.result], [s.objectives[1] for s in algorithm.result]) plt.xlim([-5.1, 5.1]) plt.ylim([-5.1, 5.1]) plt.xlabel("$f_1(x)$") plt.ylabel("$f_2(x)$") plt.show()
def my_graph(points, edges): global n_dim global fig number = 0 d1 = pd.read_csv(points) d2 = pd.read_csv(edges) n_dim = len(d1.columns) m1 = 'MDS' m2 = 'MOPSO-NSGAII' m3 = 'MOPSO-NSGAIII' # ## MDS mds = MDS(n_components=2) dat = pd.DataFrame(mds.fit(d1).embedding_, columns=["x1", "x2"]) dij = manhattan_distances(d1.values, d1.values) dis2 = manhattan_distances(dat.values, dat.values) mds_stress = (np.sum((dij - dis2)**2))**0.5 mds_inter = number_of_intersection(dat["x1"], dat["x2"], d2) graph(dat, d2, m1, number, 1, mds_stress, mds_inter) print "MDS Stress : ", mds_stress print "Total Intersection MDS = ", mds_inter # ## Multi Objective Particle Swarm Optimization (MOPSO) def objective_mopso(x): twoD = np.reshape(x, (-1, 2)) dis = manhattan_distances(twoD, twoD) stress = (np.sum((dij - dis)**2))**0.5 mopso_inter = number_of_intersection(x[0:][::2], x[1:][::2], d2) return [stress, mopso_inter] problem = Problem(len(d1) * 2, 2) problem.types[:] = Real(-50, 50) problem.function = objective_mopso ngsaii = NSGAII(problem, population_size=100) ngsaii.run(10000) result = ngsaii.result ngsaiii = NSGAIII(problem, population_size=100, divisions_outer=100) ngsaiii.run(10000) result2 = ngsaiii.result ax = fig.add_subplot(1, 4, 4) lngsaii = plt.scatter([s.objectives[0] for s in ngsaii.result], [s.objectives[1] for s in ngsaii.result], color='b') lngsaiii = plt.scatter([s.objectives[0] for s in ngsaiii.result], [s.objectives[1] for s in ngsaiii.result], color='g') lmds, = plt.plot(mds_stress, mds_inter, 'ro', markersize=8) y_min, y_max = ax.get_ylim() x_min, x_max = ax.get_xlim() plt.xticks( np.arange(math.floor(x_min), math.ceil(x_max), math.ceil((math.ceil(x_max) - math.ceil(x_min)) / 5))) if math.ceil(y_min) == math.floor(y_max): plt.yticks(np.arange(math.ceil(y_min - 1.1), math.ceil(y_max + 1.1), 1)) else: plt.yticks( np.arange( math.floor(y_min - .1), math.ceil(y_max + .1), math.ceil( (math.ceil(y_max + .1) - math.ceil(y_min - .1)) / 5))) plt.savefig('./output/graph' + str(number) + '.png', bbox_inches='tight') count = 0 out = {} ngsaii_inter = result[0].objectives[1] ngsaii_stress = result[0].objectives[0] val = 0 for solution in ngsaii.result: out[solution.objectives] = solution.variables if solution.objectives[1] < ngsaii_inter: ngsaii_inter = solution.objectives[1] ngsaii_stress = solution.objectives[0] val = count count += 1 sample = out[result[val].objectives] x = sample[0:][::2] y = sample[1:][::2] newD = pd.DataFrame({"x1": x, "x2": y}) print "Stress for NGSAII = ", ngsaii_stress print "Total Intersection NGSAII = ", ngsaii_inter graph(newD, d2, m2, number, 2, ngsaii_stress, ngsaii_inter) count = 0 out = {} ngsaiii_inter = result2[0].objectives[1] ngsaiii_stress = result2[0].objectives[0] val = 0 for solution in ngsaiii.result: out[solution.objectives] = solution.variables if solution.objectives[1] < ngsaiii_inter: ngsaiii_inter = solution.objectives[1] ngsaiii_stress = solution.objectives[0] val = count count += 1 sample = out[result2[val].objectives] x = sample[0:][::2] y = sample[1:][::2] newD = pd.DataFrame({"x1": x, "x2": y}) print "Stress for NGSAIII = ", ngsaiii_stress print "Total Intersection NGSAIII = ", ngsaiii_inter graph(newD, d2, m3, number, 3, ngsaiii_stress, ngsaiii_inter)
def NSGAIII_Experiment(): NSGAIII_results = {} hypNS3 = [0] random.seed(0) for d in range(1, 10): hyp = [] nfes = [] for i in range(100): problem = Problem(7, 2, 11) problem.types[:] = [ Real(2.6, 3.6), Real(0.7, 0.8), Real(17, 28), Real(7.3, 8.3), Real(7.3, 8.3), Real(2.9, 3.9), Real(5, 5.5) ] problem.constraints[:] = "<=0" problem.function = SRD algorithm = NSGAIII(problem, d) algorithm.run(40 * problem.nvars) funcname = 'SRD' nondominated_solutions = nondominated(algorithm.result) ref = np.array([7000, 1700]) obj = [] for s in nondominated_solutions: lijst = str(s.objectives) obj.append(ast.literal_eval(lijst)) obj = np.array(obj) hyp.append(hypervolume(obj, ref)) nfes.append(algorithm.nfe) if np.mean(nfes) < (40 * problem.nvars * 1.1): if np.mean(hypNS3) < np.mean(hyp): hypNS3 = hyp print(funcname, np.mean(hypNS3), '(', np.std(hypNS3), ')') NSGAIII_results[funcname] = hypNS3 hypNS3 = [0] random.seed(0) for d in range(1, 20): hyp = [] nfes = [] for i in range(100): problem = Problem(3, 2, 3) problem.types[:] = [ Real(1, 3), Real(0.0005, 0.05), Real(0.0005, 0.05) ] problem.constraints[:] = "<=0" problem.function = TBTD algorithm = NSGAIII(problem, d) algorithm.run(40 * problem.nvars) funcname = 'TBTD' nondominated_solutions = nondominated(algorithm.result) ref = np.array([0.1, 50000]) obj = [] for s in nondominated_solutions: lijst = str(s.objectives) obj.append(ast.literal_eval(lijst)) obj = np.array(obj) hyp.append(hypervolume(obj, ref)) nfes.append(algorithm.nfe) if np.mean(nfes) < (40 * problem.nvars * 1.1): if np.mean(hypNS3) < np.mean(hyp): hypNS3 = hyp print(funcname, np.mean(hypNS3), '(', np.std(hypNS3), ')') NSGAIII_results[funcname] = hypNS3 hypNS3 = [0] random.seed(0) for d in range(1, 30): hyp = [] nfes = [] for i in range(100): problem = Problem(4, 2, 5) problem.types[:] = [ Real(0.125, 5), Real(0.1, 10), Real(0.1, 10), Real(0.125, 5) ] problem.constraints[:] = "<=0" problem.function = WB algorithm = NSGAIII(problem, d) algorithm.run(40 * problem.nvars) funcname = 'WB' nondominated_solutions = nondominated(algorithm.result) ref = np.array([350, 0.1]) obj = [] for s in nondominated_solutions: lijst = str(s.objectives) obj.append(ast.literal_eval(lijst)) obj = np.array(obj) hyp.append(hypervolume(obj, ref)) nfes.append(algorithm.nfe) if np.mean(nfes) < (40 * problem.nvars * 1.1): if np.mean(hypNS3) < np.mean(hyp): hypNS3 = hyp print(funcname, np.mean(hypNS3), '(', np.std(hypNS3), ')') NSGAIII_results[funcname] = hypNS3 hypNS3 = [0] random.seed(0) for d in range(1, 30): hyp = [] nfes = [] for i in range(100): problem = Problem(4, 2, 5) problem.types[:] = [ Real(55, 80), Real(75, 110), Real(1000, 3000), Real(2, 20) ] problem.constraints[:] = "<=0" problem.function = DBD algorithm = NSGAIII(problem, d) algorithm.run(40 * problem.nvars) funcname = 'DBD' nondominated_solutions = nondominated(algorithm.result) ref = np.array([5, 50]) obj = [] for s in nondominated_solutions: lijst = str(s.objectives) obj.append(ast.literal_eval(lijst)) obj = np.array(obj) hyp.append(hypervolume(obj, ref)) nfes.append(algorithm.nfe) if np.mean(nfes) < (40 * problem.nvars * 1.1): if np.mean(hypNS3) < np.mean(hyp): hypNS3 = hyp print(funcname, np.mean(hypNS3), '(', np.std(hypNS3), ')') NSGAIII_results[funcname] = hypNS3 hypNS3 = [0] random.seed(0) for d in range(1, 20): hyp = [] nfes = [] for i in range(100): problem = Problem(2, 2, 5) problem.types[:] = [Real(20, 250), Real(10, 50)] problem.constraints[:] = "<=0" problem.function = NBP algorithm = NSGAIII(problem, d) algorithm.run(40 * problem.nvars) funcname = 'NBP' nondominated_solutions = nondominated(algorithm.result) ref = np.array([11150, 12500]) obj = [] for s in nondominated_solutions: lijst = str(s.objectives) obj.append(ast.literal_eval(lijst)) obj = np.array(obj) hyp.append(hypervolume(obj, ref)) nfes.append(algorithm.nfe) if np.mean(nfes) < (40 * problem.nvars * 1.1): if np.mean(hypNS3) < np.mean(hyp): hypNS3 = hyp print(funcname, np.mean(hypNS3), '(', np.std(hypNS3), ')') NSGAIII_results[funcname] = hypNS3 hypNS3 = [0] random.seed(0) for d in range(1, 10): hyp = [] nfes = [] for i in range(100): problem = Problem(6, 3, 9) problem.types[:] = [ Real(150, 274.32), Real(25, 32.31), Real(12, 22), Real(8, 11.71), Real(14, 18), Real(0.63, 0.75) ] problem.constraints[:] = "<=0" problem.function = SPD algorithm = NSGAIII(problem, d) algorithm.run(40 * problem.nvars) funcname = 'SPD' nondominated_solutions = nondominated(algorithm.result) ref = np.array([16, 19000, -260000]) obj = [] for s in nondominated_solutions: lijst = str(s.objectives) obj.append(ast.literal_eval(lijst)) obj = np.array(obj) hyp.append(hypervolume(obj, ref)) nfes.append(algorithm.nfe) if np.mean(nfes) < (40 * problem.nvars * 1.1): if np.mean(hypNS3) < np.mean(hyp): hypNS3 = hyp print(funcname, np.mean(hypNS3), '(', np.std(hypNS3), ')') NSGAIII_results[funcname] = hypNS3 hypNS3 = [0] random.seed(0) for d in range(1, 20): hyp = [] nfes = [] for i in range(100): problem = Problem(7, 3, 10) problem.types[:] = [ Real(0.5, 1.5), Real(0.45, 1.35), Real(0.5, 1.5), Real(0.5, 1.5), Real(0.875, 2.625), Real(0.4, 1.2), Real(0.4, 1.2) ] problem.constraints[:] = "<=0" problem.function = CSI algorithm = NSGAIII(problem, d) algorithm.run(40 * problem.nvars) funcname = 'CSI' nondominated_solutions = nondominated(algorithm.result) ref = np.array([42, 4.5, 13]) obj = [] for s in nondominated_solutions: lijst = str(s.objectives) obj.append(ast.literal_eval(lijst)) obj = np.array(obj) hyp.append(hypervolume(obj, ref)) nfes.append(algorithm.nfe) if np.mean(nfes) < (40 * problem.nvars * 1.1): if np.mean(hypNS3) < np.mean(hyp): hypNS3 = hyp print(funcname, np.mean(hypNS3), '(', np.std(hypNS3), ')') NSGAIII_results[funcname] = hypNS3 hypNS3 = [0] random.seed(0) for d in range(1, 10): hyp = [] nfes = [] for i in range(100): problem = Problem(3, 5, 7) problem.types[:] = [ Real(0.01, 0.45), Real(0.01, 0.1), Real(0.01, 0.1) ] problem.constraints[:] = "<=0" problem.function = WP algorithm = NSGAIII(problem, d) algorithm.run(40 * problem.nvars) funcname = 'WP' nondominated_solutions = nondominated(algorithm.result) ref = np.array([83000, 1350, 2.85, 15989825, 25000]) obj = [] for s in nondominated_solutions: lijst = str(s.objectives) obj.append(ast.literal_eval(lijst)) obj = np.array(obj) hyp.append(hypervolume(obj, ref)) nfes.append(algorithm.nfe) if np.mean(nfes) < (40 * problem.nvars * 1.1): if np.mean(hypNS3) < np.mean(hyp): hypNS3 = hyp print(funcname, np.mean(hypNS3), '(', np.std(hypNS3), ')') NSGAIII_results[funcname] = hypNS3 hypNS3 = [0] random.seed(0) for d in range(1, 20): hyp = [] nfes = [] for i in range(1): problem = Problem(2, 2, 2) problem.types[:] = [Real(0, 5), Real(0, 3)] problem.constraints[:] = "<=0" problem.function = BNH algorithm = NSGAIII(problem, d) algorithm.run(40 * problem.nvars) funcname = 'BNH' nondominated_solutions = nondominated(algorithm.result) ref = np.array([140, 50]) obj = [] for s in nondominated_solutions: lijst = str(s.objectives) obj.append(ast.literal_eval(lijst)) obj = np.array(obj) hyp.append(hypervolume(obj, ref)) nfes.append(algorithm.nfe) if np.mean(nfes) < (40 * problem.nvars * 1.1): if np.mean(hypNS3) < np.mean(hyp): hypNS3 = hyp print(d) print(funcname, np.mean(hypNS3), '(', np.std(hypNS3), ')') NSGAIII_results[funcname] = hypNS3 hypNS3 = [0] random.seed(0) for d in range(1, 20): hyp = [] nfes = [] for i in range(100): problem = Problem(2, 2, 2) problem.types[:] = [Real(0.1, 1), Real(0, 5)] problem.constraints[:] = "<=0" problem.function = CEXP algorithm = NSGAIII(problem, d) algorithm.run(40 * problem.nvars) funcname = 'CEXP' nondominated_solutions = nondominated(algorithm.result) ref = np.array([1, 9]) obj = [] for s in nondominated_solutions: lijst = str(s.objectives) obj.append(ast.literal_eval(lijst)) obj = np.array(obj) hyp.append(hypervolume(obj, ref)) nfes.append(algorithm.nfe) if np.mean(nfes) < (40 * problem.nvars * 1.1): if np.mean(hypNS3) < np.mean(hyp): hypNS3 = hyp print(funcname, np.mean(hypNS3), '(', np.std(hypNS3), ')') NSGAIII_results[funcname] = hypNS3 hypNS3 = [0] random.seed(0) for d in range(1, 100): hyp = [] nfes = [] for i in range(100): problem = Problem(6, 2, 2) problem.types[:] = [ Real(0, 1), Real(0, 1), Real(0, 1), Real(0, 1), Real(0, 1), Real(0, 1) ] problem.constraints[:] = "<=0" problem.function = C3DTLZ4 algorithm = NSGAIII(problem, d) algorithm.run(40 * problem.nvars) funcname = 'C3DTLZ4' nondominated_solutions = nondominated(algorithm.result) ref = np.array([3, 3]) obj = [] for s in nondominated_solutions: lijst = str(s.objectives) obj.append(ast.literal_eval(lijst)) obj = np.array(obj) hyp.append(hypervolume(obj, ref)) nfes.append(algorithm.nfe) if np.mean(nfes) < (40 * problem.nvars * 1.1): if np.mean(hypNS3) < np.mean(hyp): hypNS3 = hyp print(funcname, np.mean(hypNS3), '(', np.std(hypNS3), ')') NSGAIII_results[funcname] = hypNS3 hypNS3 = [0] random.seed(0) for d in range(1, 40): hyp = [] nfes = [] for i in range(100): problem = Problem(2, 2, 2) problem.types[:] = [Real(-20, 20), Real(-20, 20)] problem.constraints[:] = "<=0" problem.function = SRN algorithm = NSGAIII(problem, d) algorithm.run(40 * problem.nvars) funcname = 'SRN' nondominated_solutions = nondominated(algorithm.result) ref = np.array([301, 72]) obj = [] for s in nondominated_solutions: lijst = str(s.objectives) obj.append(ast.literal_eval(lijst)) obj = np.array(obj) hyp.append(hypervolume(obj, ref)) nfes.append(algorithm.nfe) if np.mean(nfes) < (40 * problem.nvars * 1.1): if np.mean(hypNS3) < np.mean(hyp): hypNS3 = hyp print(funcname, np.mean(hypNS3), '(', np.std(hypNS3), ')') NSGAIII_results[funcname] = hypNS3 hypNS3 = [0] random.seed(0) for d in range(1, 40): hyp = [] nfes = [] for i in range(100): problem = Problem(2, 2, 2) problem.types[:] = [Real(1e-5, np.pi), Real(1e-5, np.pi)] problem.constraints[:] = "<=0" problem.function = TNK algorithm = NSGAIII(problem, d) algorithm.run(40 * problem.nvars) funcname = 'TNK' nondominated_solutions = nondominated(algorithm.result) ref = np.array([3, 3]) obj = [] for s in nondominated_solutions: lijst = str(s.objectives) obj.append(ast.literal_eval(lijst)) obj = np.array(obj) hyp.append(hypervolume(obj, ref)) nfes.append(algorithm.nfe) if np.mean(nfes) < (40 * problem.nvars * 1.1): if np.mean(hypNS3) < np.mean(hyp): hypNS3 = hyp print(funcname, np.mean(hypNS3), '(', np.std(hypNS3), ')') NSGAIII_results[funcname] = hypNS3 hypNS3 = [0] random.seed(0) for d in range(1, 10): hyp = [] nfes = [] for i in range(100): problem = Problem(6, 2, 6) problem.types[:] = [ Real(0, 10), Real(0, 10), Real(1, 5), Real(0, 6), Real(1, 5), Real(0, 10) ] problem.constraints[:] = "<=0" problem.function = OSY algorithm = NSGAIII(problem, d) algorithm.run(40 * problem.nvars) funcname = 'OSY' nondominated_solutions = nondominated(algorithm.result) ref = np.array([0, 386]) obj = [] for s in nondominated_solutions: lijst = str(s.objectives) obj.append(ast.literal_eval(lijst)) obj = np.array(obj) hyp.append(hypervolume(obj, ref)) nfes.append(algorithm.nfe) if np.mean(nfes) < (40 * problem.nvars * 1.1): if np.mean(hypNS3) < np.mean(hyp): hypNS3 = hyp print(funcname, np.mean(hypNS3), '(', np.std(hypNS3), ')') NSGAIII_results[funcname] = hypNS3 hypNS3 = [0] random.seed(0) for d in range(1, 40): hyp = [] nfes = [] for i in range(100): problem = Problem(2, 2, 2) problem.types[:] = [Real(0, 1), Real(0, 1)] problem.constraints[:] = "<=0" problem.function = CTP1 algorithm = NSGAIII(problem, d) algorithm.run(40 * problem.nvars) funcname = 'CTP1' nondominated_solutions = nondominated(algorithm.result) ref = np.array([1, 2]) obj = [] for s in nondominated_solutions: lijst = str(s.objectives) obj.append(ast.literal_eval(lijst)) obj = np.array(obj) hyp.append(hypervolume(obj, ref)) nfes.append(algorithm.nfe) if np.mean(nfes) < (40 * problem.nvars * 1.1): if np.mean(hypNS3) < np.mean(hyp): hypNS3 = hyp print(funcname, np.mean(hypNS3), '(', np.std(hypNS3), ')') NSGAIII_results[funcname] = hypNS3 hypNS3 = [0] random.seed(0) for d in range(1, 20): hyp = [] nfes = [] for i in range(100): problem = Problem(10, 2, 1) problem.types[:] = [ Real(0, 1), Real(0, 1), Real(0, 1), Real(0, 1), Real(0, 1), Real(0, 1), Real(0, 1), Real(0, 1), Real(0, 1), Real(0, 1) ] problem.constraints[:] = "<=0" problem.function = BICOP1 algorithm = NSGAIII(problem, d) algorithm.run(40 * problem.nvars) funcname = 'BICOP1' nondominated_solutions = nondominated(algorithm.result) ref = np.array([9, 9]) obj = [] for s in nondominated_solutions: lijst = str(s.objectives) obj.append(ast.literal_eval(lijst)) obj = np.array(obj) hyp.append(hypervolume(obj, ref)) nfes.append(algorithm.nfe) if np.mean(nfes) < (40 * problem.nvars * 1.1): if np.mean(hypNS3) < np.mean(hyp): hypNS3 = hyp print(funcname, np.mean(hypNS3), '(', np.std(hypNS3), ')') NSGAIII_results[funcname] = hypNS3 hypNS3 = [0] random.seed(0) for d in range(1, 100): hyp = [] nfes = [] for i in range(100): problem = Problem(10, 2, 2) problem.types[:] = [ Real(0, 1), Real(0, 1), Real(0, 1), Real(0, 1), Real(0, 1), Real(0, 1), Real(0, 1), Real(0, 1), Real(0, 1), Real(0, 1) ] problem.constraints[:] = "<=0" problem.function = BICOP2 algorithm = NSGAIII(problem, d) algorithm.run(40 * problem.nvars) funcname = 'BICOP2' nondominated_solutions = nondominated(algorithm.result) ref = np.array([70, 70]) obj = [] for s in nondominated_solutions: lijst = str(s.objectives) obj.append(ast.literal_eval(lijst)) obj = np.array(obj) hyp.append(hypervolume(obj, ref)) nfes.append(algorithm.nfe) if np.mean(nfes) < (40 * problem.nvars * 1.1): if np.mean(hypNS3) < np.mean(hyp): hypNS3 = hyp print(funcname, np.mean(hypNS3), '(', np.std(hypNS3), ')') NSGAIII_results[funcname] = hypNS3 hypNS3 = [0] random.seed(0) for d in range(1, 10): hyp = [] nfes = [] for i in range(100): problem = Problem(2, 3, 3) problem.types[:] = [Real(-4, 4), Real(-4, 4)] problem.constraints[:] = "<=0" problem.function = TRICOP algorithm = NSGAIII(problem, d) algorithm.run(40 * problem.nvars) funcname = 'TRICOP' nondominated_solutions = nondominated(algorithm.result) ref = np.array([34, -4, 90]) obj = [] for s in nondominated_solutions: lijst = str(s.objectives) obj.append(ast.literal_eval(lijst)) obj = np.array(obj) hyp.append(hypervolume(obj, ref)) nfes.append(algorithm.nfe) if np.mean(nfes) < (40 * problem.nvars * 1.1): if np.mean(hypNS3) < np.mean(hyp): hypNS3 = hyp print(funcname, np.mean(hypNS3), '(', np.std(hypNS3), ')') NSGAIII_results[funcname] = hypNS3 return NSGAIII_results
from platypus import NSGAIII, DTLZ2 # define the problem definition problem = DTLZ2(3) # instantiate the optimization algorithm algorithm = NSGAIII(problem, divisions_outer=12) # optimize the problem using 10,000 function evaluations algorithm.run(10000) # plot the results using matplotlib import matplotlib.pyplot as plt from mpl_toolkits.mplot3d import Axes3D fig = plt.figure() ax = fig.add_subplot(111, projection='3d') ax.scatter([s.objectives[0] for s in algorithm.result], [s.objectives[1] for s in algorithm.result], [s.objectives[2] for s in algorithm.result]) plt.show()
def moea(name, solsize, popsize, wscalar_, moea_type, max_gen=float('inf'), timeLimit=float('inf')): from platypus import Problem, TournamentSelector from platypus import NSGAII, NSGAIII, SPEA2 from platyplus.operators import varOr, mutGauss, cxUniform from platyplus.types import RealGauss from platyplus.algorithms import SMSEMOA N = wscalar_.xdim M = wscalar_.M time_start = time.perf_counter() logger.info('Running ' + moea_type + ' in ' + name) prMutation = 0.1 prVariation = 1 - prMutation vartor = varOr(cxUniform(), mutGauss(), prVariation, prMutation) def eval_(theta): return wscalar_.f(np.array(theta)) problem = Problem(N, M) problem.types[:] = [RealGauss() for i in range(N)] problem.function = eval_ if moea_type == 'NSGAII': alg = NSGAII(problem, population_size=popsize, selector=TournamentSelector(1), variator=vartor) elif moea_type == 'NSGAIII': alg = NSGAIII(problem, divisions_outer=3, population_size=popsize, selector=TournamentSelector(1), variator=vartor) elif moea_type == 'SPEA2': alg = SPEA2(problem, population_size=popsize, selector=TournamentSelector(1), variator=vartor) elif moea_type == 'SMSdom': alg = SMSEMOA(problem, population_size=popsize, selector=TournamentSelector(1), variator=vartor, selection_method='nbr_dom') elif moea_type == 'SMShv': alg = SMSEMOA(problem, population_size=popsize, selector=TournamentSelector(1), variator=vartor, selection_method='hv_contr') gen = 1 while gen < max_gen and time.perf_counter() - time_start < timeLimit: alg.step() gen += 1 alg.population_size = solsize alg.step() moeaSols = [eval_(s.variables) for s in alg.result] moea_time = time.perf_counter() - time_start logger.info(moea_type + ' in ' + name + ' finnished.') return moeaSols, moea_time