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
def optimization_platypus_vpp(offspringsplatypus, gamethod, windspeedrange, windanglerange): # Clean the folder with previous results folder = "assets/data/vpp_results/*" files = glob.glob(folder) for f in files: os.remove(f) # Adjust input data minimum_tw_knots = np.float(windspeedrange[0]) maximum_tw_knots = np.float(windspeedrange[1]) + 1 minimum_tw_angle = np.float(windanglerange[0]) * 10 maximum_tw_angle = np.float(windanglerange[1]) * 10 + 1 # Import dimensions dim_obj = codecs.open('assets/data/dimensions_hull_limits.json', 'r', encoding='utf-8').read() dim = json.loads(dim_obj) lwlmin = np.float(dim["lwlmin"]) lwlmax = np.float(dim["lwlmax"]) bwlmin = np.float(dim["bwlmin"]) bwlmax = np.float(dim["bwlmax"]) tcmin = np.float(dim["tcmin"]) tcmax = np.float(dim["tcmax"]) lwl_avg = (lwlmax + lwlmin) / 2 lcbmin = np.float(dim["lcbmin"]) - lwl_avg / 2 lcbmax = np.float(dim["lcbmax"]) - lwl_avg / 2 lcfmin = np.float(dim["lcfmin"]) - lwl_avg / 2 lcfmax = np.float(dim["lcfmax"]) - lwl_avg / 2 cbmin = np.float(dim["cbmin"]) cbmax = np.float(dim["cbmax"]) cmmin = np.float(dim["cmmin"]) cmmax = np.float(dim["cmmax"]) cpmin = np.float(dim["cpmin"]) cpmax = np.float(dim["cpmax"]) cwpmin = np.float(dim["cwpmin"]) cwpmax = np.float(dim["cwpmax"]) dim_obj = codecs.open('assets/data/dimensions-appendages-limits.json', 'r', encoding='utf-8').read() dim = json.loads(dim_obj) fbmin = np.float(dim["fbmin"]) fbmax = np.float(dim["fbmax"]) boamin = np.float(dim["boamin"]) boamax = np.float(dim["boamax"]) mass_crew = 280 pmin = np.float(dim["pmin"]) pmax = np.float(dim["pmax"]) emin = np.float(dim["emin"]) emax = np.float(dim["emax"]) imin = np.float(dim["imin"]) imax = np.float(dim["imax"]) jmin = np.float(dim["jmin"]) jmax = np.float(dim["jmax"]) spanRmin = np.float(dim["spanRmin"]) spanRmax = np.float(dim["spanRmax"]) tipcRmin = np.float(dim["tipcRmin"]) tipcRmax = np.float(dim["tipcRmax"]) rootcRmin = np.float(dim["rootcRmin"]) rootcRmax = np.float(dim["rootcRmax"]) tiptcksRmin = np.float(dim["tiptcksRmin"]) tiptcksRmax = np.float(dim["tiptcksRmax"]) roottcksRmin = np.float(dim["roottcksRmin"]) roottcksRmax = np.float(dim["roottcksRmax"]) sweepRdegmin = np.float(dim["sweepRdegmin"]) sweepRdegmax = np.float(dim["sweepRdegmax"]) spanKmin = np.float(dim["spanKmin"]) spanKmax = np.float(dim["spanKmax"]) tipcKmin = np.float(dim["tipcKmin"]) tipcKmax = np.float(dim["tipcKmax"]) rootcKmin = np.float(dim["rootcKmin"]) rootcKmax = np.float(dim["rootcKmax"]) tiptcksKmin = np.float(dim["tiptcksKmin"]) tiptcksKmax = np.float(dim["tiptcksKmax"]) roottcksKmin = np.float(dim["roottcksKmin"]) roottcksKmax = np.float(dim["roottcksKmax"]) sweepKdegmin = np.float(dim["sweepKdegmin"]) sweepKdegmax = np.float(dim["sweepKdegmax"]) badmin = np.float(dim["badmin"]) badmax = np.float(dim["badmax"]) splmin = np.float(dim["splmin"]) splmax = np.float(dim["splmax"]) lpgmin = np.float(dim["lpgmin"]) lpgmax = np.float(dim["lpgmax"]) ehmmin = np.float(dim["ehmmin"]) ehmmax = np.float(dim["ehmmax"]) emdcmin = np.float(dim["emdcmin"]) emdcmax = np.float(dim["emdcmax"]) hsrmin = np.float(dim["hsrmin"]) hsrmax = np.float(dim["hsrmax"]) pmzmin = np.float(dim["pmzmin"]) pmzmax = np.float(dim["pmzmax"]) emzmin = np.float(dim["emzmin"]) emzmax = np.float(dim["emzmax"]) badmzmin = np.float(dim["badmzmin"]) badmzmax = np.float(dim["badmzmax"]) xceamin = np.float(dim["xceamin"]) xceamax = np.float(dim["xceamax"]) def function_platypus_vpp(vars): # each vars[i] give one random number between the minimum and maximum limit for each parameter loa, lwl, boa, bwl, tc, lcb, lcf = vars[0], vars[1], vars[2], vars[ 3], vars[4], vars[5], vars[6] cb, cm, cp, cwp, free_board = vars[7], vars[8], vars[9], vars[ 10], vars[11] height_mainsail, base_mainsail, height_foretriangle, base_foretriangle = vars[ 12], vars[13], vars[14], vars[15] span_rudder, tip_chord_rudder, root_chord_rudder, tip_thickness_rudder, root_thickness_rudder, sweep_rudder_deg = vars[ 16], vars[17], vars[18], vars[19], vars[20], vars[21] span_keel, tip_chord_keel, root_chord_keel, tip_thickness_keel, root_thickness_keel, sweep_keel_deg = vars[ 22], vars[23], vars[24], vars[25], vars[26], vars[27] boom_heigth_deck, length_spinnaker, perpendicular_jib = vars[28], vars[ 29], vars[30] height_mast, diameter_mast, height_surface_rudder, height_mizzen, base_mizzen, boom_height_mizzen = vars[ 31], vars[32], vars[33], vars[34], vars[35], vars[36] lead_sail = vars[37] resultados = vpp_solve('main+genoa', loa, lwl, boa, bwl, tc, lcb, lcf, cb, cm, cp, cwp, 4.5, 0.8, free_board, 5.674, lead_sail, \ mass_crew, height_mainsail, base_mainsail, height_foretriangle, base_foretriangle, boom_heigth_deck, length_spinnaker, \ perpendicular_jib, span_rudder, tip_chord_rudder, root_chord_rudder, tip_thickness_rudder, root_thickness_rudder, \ sweep_rudder_deg, span_keel, tip_chord_keel, root_chord_keel, tip_thickness_keel, root_thickness_keel, sweep_keel_deg, \ '6digit', '6digit', height_mast, diameter_mast, height_surface_rudder, height_mizzen, base_mizzen, boom_height_mizzen, 0, 0, 0, \ minimum_tw_knots, maximum_tw_knots, minimum_tw_angle, maximum_tw_angle) #lat_surface_cb, KG,lead_rudder #naca_keel, naca_rudder, chord_bulb_keel, diameter_bulb, surface_area_bulb # Count the number of lines to set the index number index = sum( [len(files) for r, d, files in os.walk("assets/data/vpp_results")]) if index > 1: index = index - 1 # Export data to csv exportdata = [ index, format(resultados[0], '.4f'), format(resultados[1], '.4f'), format(resultados[2], '.4f'), 'true' ] with open("assets/data/optimizationvpp.csv", "a") as file: writer = csv.writer(file, delimiter=',') writer.writerow(exportdata) #print(index) return resultados[0], resultados[2] # Optimize for 9 parameters, 2 objectives and 2 restrictions problem = Problem(38, 2) problem.types[:] = [Real(lwlmin, lwlmax), Real(lwlmin, lwlmax), Real(boamin, boamax), Real(bwlmin, bwlmax), \ Real(tcmin, tcmax), Real(lcbmin, lcbmax), Real(lcfmin, lcfmax), Real(cbmin, cbmax), Real(cmmin, cmmax), \ Real(cpmin, cpmax), Real(cwpmin, cwpmax), Real(fbmin, fbmax), Real(pmin, pmax), Real(emin, emax), \ Real(imin, imax), Real(jmin, jmax), Real(spanRmin, spanRmax), Real(tipcRmin, tipcRmax), Real(rootcRmin, rootcRmax), \ Real(tiptcksRmin, tiptcksRmax), Real(roottcksRmin, roottcksRmax), Real(sweepRdegmin, sweepRdegmax), \ Real(spanKmin, spanKmax), Real(tipcKmin, tipcKmax), Real(rootcKmin, rootcKmax), Real(tiptcksKmin, tiptcksKmax), \ Real(roottcksKmin, roottcksKmax), Real(sweepKdegmin, sweepKdegmax), \ Real(badmin, badmax), Real(splmin, splmax), Real(lpgmin, lpgmax), \ Real(ehmmin, ehmmax), Real(emdcmin, emdcmax), Real(hsrmin, hsrmax), Real(pmzmin, pmzmax), Real(emzmin, emzmax), \ Real(badmzmin, badmzmax), Real(xceamin, xceamax)] problem.directions[:] = [Problem.MAXIMIZE, Problem.MAXIMIZE] problem.function = function_platypus_vpp # Six methods applied (there is four more still not applied) if gamethod == 'NSGAII': algorithm = NSGAII(problem) elif gamethod == 'GDE3': algorithm = GDE3(problem) elif gamethod == 'OMOPSO': algorithm = OMOPSO(problem, epsilons=0.05) elif gamethod == 'SMPSO': algorithm = SMPSO(problem) elif gamethod == 'SPEA2': algorithm = SPEA2(problem) elif gamethod == 'EpsMOEA': algorithm = EpsMOEA(problem, epsilons=0.05) algorithm.run(np.int(offspringsplatypus)) return "ok"
# 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[:]) costs.append(s.objectives[:]) points = np.array(points)
#CTP1 0.0163707270088 hyp = [] for i in range(5): 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 = SPEA2(problem) algorithm.run(200) nondominated_solutions = nondominated(algorithm.result) ref = np.array([5000, 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)) print('SRD', np.mean(hyp)) print('SRD', np.max(hyp)) print('SRD', np.std(hyp)) hyp = [] for i in range(100):
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
def optimization_platypus_resistance(lwlmin, lwlmax, bwlmin, bwlmax, tcmin, tcmax, lcfmin, lcfmax, lcbmin, lcbmax, displac, cwpmin, cwpmax, cpmin, cpmax, cmmin, cmmax, gamethod, offspringsplatypus, gyration, wave_angle, wl_sl, wave_height): def function_platypus(vars): # each vars[i] give one random number between the minimum and maximum limit for each parameter lwl, bwl, tc, lcf, lcb, cwp, cp, cm = vars[0], vars[1], vars[2], vars[ 3], vars[4], vars[5], vars[6], vars[7] # import extra parameters dimensions = codecs.open('assets/data/dimensions.json', 'r', encoding='utf-8').read() dim = json.loads(dimensions) gaconfig_obj = codecs.open('assets/data/parametersga.json', 'r', encoding='utf-8').read() gaconfig = json.loads(gaconfig_obj) velocityrange = np.array(gaconfig["velocityrange"]) heelrange = np.array(gaconfig["heelrange"]) # calculate remaining parameters disp = np.float(displac) awp = bwl * lwl * cwp boa = bwl * 1.1 dispmass = disp * 1025 cs = boa * 3.28084 / (dispmass * 2.20462 / 64)**(1 / 3) cb = disp / (lwl * bwl * tc) # calculate the resistance for a combinantion of velocities and heel angle Rt, CR, Rv, Ri, Rr, Rincli, count, Radd = 0, 0, 0, 0, 0, 0, 0, 0 for velocity in range(velocityrange[0], velocityrange[1], 1): for heel in range(heelrange[0], heelrange[1], 5): froude_number = velocity / (9.81 * lwl)**0.5 result = resistance(lwl, bwl, tc, cp, cm, cwp, disp, lcb, lcf, velocity, heel) froude_number = 0.3 result2 = calc_added_resistance(disp, lwl, bwl, tc, cp, wave_angle, froude_number, gyration, wl_sl, wave_height) Rt, Rv, Ri, Rr, Rincli, CR, count, = Rt + result[ 0], Rv + result[1], Ri + result[2], Rr + result[ 3], Rincli + result[4], CR + result[5], count + 1 Radd = Radd + abs(result2) Rt, CR, Rv, Ri, Rr, Rincli, Radd = Rt / count, CR / count, Rv / count, Ri / count, Rr / count, Rincli / count, Radd / count # count the number of lines to set the index number rows = [] with open("assets/data/optimizationresistance.csv", "r") as csvfile: csvreader = csv.reader(csvfile) for row in csvreader: rows.append(row) index = csvreader.line_num # calculate constraints of delft series, capsize screening factor, and displacement constraint1, constraint2, constraint3, constraint4, constraint5, constraint6, valid = False, False, False, False, False, False, False if (lwl / bwl) > 5 or (lwl / bwl) < 2.73: constraint1 = True if (bwl / tc) > 6.5 or ( bwl / tc ) < 3.8: #(bwl/tcan) > 19.39 or (bwl/tcan) < 2.46 delft series seems to have unrealistic limits constraint2 = True if (lwl / disp**(1 / 3)) > 8.5 or (lwl / disp**(1 / 3)) < 4.34: constraint3 = True if (awp / disp**(2 / 3)) > 12.67 or (awp / disp**(2 / 3)) < 3.78: constraint4 = True if cs > 2: constraint5 = True if cb < 0.35: constraint6 = True if constraint1 == False and constraint2 == False and constraint3 == False and constraint4 == False and constraint5 == False and constraint6 == False: valid = True # export data to csv exportdata = [ index, format(Rt, '.4f'), format(Rv, '.4f'), format(Ri, '.4f'), format(Rr, '.4f'), format(Rincli, '.4f'), format(CR, '.4f'), format(cs, '.4f'), format(lwl, '.4f'), format(bwl, '.4f'), format(tc, '.4f'), format(disp, '.4f'), format(cwp, '.4f'), format(lcb, '.4f'), format(lcf, '.4f'), constraint1, constraint2, constraint3, constraint4, constraint5, valid ] with open("assets/data/optimizationresistance.csv", "a", newline='') as file: writer = csv.writer(file, delimiter=',') writer.writerow(exportdata) # return 2 objectives and 5 restrictions return [Rt, CR], [ cs - 2, lwl / bwl - 5, 2.73 - lwl / bwl, bwl / tc - 6.5, 3.8 - bwl / tc ] # optimize for 9 parameters, 2 objectives and 5 restrictions problem = Problem(8, 2, 5) problem.types[:] = [ Real(lwlmin, lwlmax), Real(bwlmin, bwlmax), Real(tcmin, tcmax), Real(lcfmin, lcfmax), Real(lcbmin, lcbmax), Real(cwpmin, cwpmax), Real(cpmin, cpmax), Real(cmmin, cmmax) ] problem.directions[:] = [Problem.MINIMIZE, Problem.MAXIMIZE] problem.constraints[:] = "<0" problem.function = function_platypus # six methods applied (there is four more still not applied) if gamethod == 'NSGAII': algorithm = NSGAII(problem) elif gamethod == 'GDE3': algorithm = GDE3(problem) elif gamethod == 'OMOPSO': algorithm = OMOPSO(problem, epsilons=0.05) elif gamethod == 'SMPSO': algorithm = SMPSO(problem) elif gamethod == 'SPEA2': algorithm = SPEA2(problem) elif gamethod == 'EpsMOEA': algorithm = EpsMOEA(problem, epsilons=0.05) algorithm.run(np.int(offspringsplatypus)) return offspringsplatypus