def traj_optim_static(paths, tree): path, envs, modes, mnps = paths guard_index = [0] n = len(modes) v_init = np.zeros((n, 3)) for i in range(1, n): if not np.all(modes[i] == modes[i - 1]): guard_index.append(i) elif len(envs[i]) != 0: if not envs[i][0].is_same(envs[i - 1][0]): guard_index.append(i) elif not (mnps[i][0].is_same(mnps[i - 1][0]) and mnps[i][1].is_same(mnps[i - 1][1])): # manipulator change guard_index.append(i) g_v = np.identity(3) g_v[0:2, 0:2] = config2trans(path[i - 1])[0:2, 0:2] v_init[i - 1] = np.dot(g_v.T, np.array(path[i]) - np.array(path[i - 1])) #guard_index.append(len(modes)-1) guard_index = np.unique(guard_index) Gs = dict() hs = dict() As = dict() bs = dict() for i in range(len(path)): G, h, A, b = contact_mode_constraints(path[i], mnps[i], envs[i], modes[i], tree.world, tree.mnp_mu, tree.env_mu, tree.mnp_fn_max) gid = np.any(G[:, 0:3], axis=1) aid = np.any(A[:, 0:3], axis=1) Gs[i] = G[gid, 0:3] hs[i] = h[gid].flatten() As[i] = A[aid, 0:3] bs[i] = b[aid].flatten() modeconstraints = (Gs, hs, As, bs) q_goal = np.array(tree.x_goal) opt_prob = Optimization('Trajectory Optimization', obj_fun) x_init = np.hstack((np.array(path).flatten(), v_init.flatten())) cs = constraints(x_init, path, Gs, hs, As, bs, guard_index) opt_prob.addVarGroup('x', n * 6, 'c', value=x_init, lower=-10, upper=10) opt_prob.addObj('f') opt_prob.addConGroup('g', len(cs), 'i', lower=0.0, upper=10000.0) print(opt_prob) slsqp = SLSQP() #slsqp.setOption('IPRINT', -1) slsqp(opt_prob, sens_type='FD', goal=q_goal, path=path, modecons=modeconstraints, guard_index=guard_index) print(opt_prob.solution(0)) qs = [opt_prob.solution(0)._variables[i].value for i in range(n * 3)] return qs
def solveOpt(int_domain,J,x,model,u0): def objfun(u,**kwargs): # 1) extract paraeters int_domain = kwargs['int_domain'] J = kwargs['J'] x = kwargs['x'] model = kwargs['model'] # 2) define objective function f = np.trapz(int_domain,J * model.pf(int_domain,u,x)) g = [0]*2 # 3) budget constraint g[1] = u.sum() - 1 # 4) VaR constarint W = model.W sigmaMax = model.VaR / norm.ppf(1-model.alpha) g[0] = -sigmaMax + np.sqrt(W.dot(u).dot(u)) fail = 0 return f,g,fail opt_prob = Optimization('test problem',objfun) opt_prob.addObj('f') opt_prob.addCon('budget const','e') opt_prob.addCon('VaR const','i') opt_prob.addVarGroup('u',model.M,'c',lower=np.zeros(model.M), upper=np.ones(model.M),value=u0) print opt_prob slsqp = SLSQP() slsqp.setOption('IPRINT',-1) slsqp(opt_prob,sens_type='FD',int_domain=int_domain,J=J,x=x,model=model) print opt_prob.solution(0)
def optimize(k, w1, w2): # Physical problem rho = 0.2836 # lb/in^3 L = 5.0 # in P = 25000.0 # lb E = 30.0e6 # psi ys = 36260.0 # psi fs = 1.5 dtruss = TwoBarTruss(rho, L, P, E, ys, fs) struss = StochasticTwoBarTruss(dtruss) # Optimization Problem optproblem = TwoBarTrussOpt(MPI.COMM_WORLD, struss, k, w1, w2) opt_prob = Optimization(args.logfile, optproblem.evalObjCon) # Add functions opt_prob.addObj('weight') opt_prob.addCon('buckling-bar1', type='i') opt_prob.addCon('failure-bar1' , type='i') opt_prob.addCon('failure-bar2' , type='i') # Add variables opt_prob.addVar('area-1', type='c', value= 1.5, lower= 1.5, upper= 1.5) opt_prob.addVar('area-2', type='c', value= 1.5, lower= 1.5, upper= 1.5) opt_prob.addVar('height', type='c', value= 4.0, lower= 4.0, upper= 10.0) # Optimization algorithm if args.algorithm == 'ALGENCAN': opt = ALGENCAN() opt.setOption('iprint',2) opt.setOption('epsfeas',1e-6) opt.setOption('epsopt',1e-6) else: opt = SLSQP(pll_type='POA') opt.setOption('MAXIT',999) opt(opt_prob, sens_type=optproblem.evalObjConGradient, disp_opts=True, store_hst=True, hot_start=False) if optproblem.comm.Get_rank() ==0: print opt_prob.solution(0) opt_prob.write2file(disp_sols=True) x = optproblem.x_hist[-1] f = optproblem.fvals[0] print 'x', x print 'f', f return x, f
def runoptimizer(): opt_prob = Optimization('TP37 Constrained Problem',objfun) opt_prob.addObj('LL') opt_prob.addVar('x1','c',lower=0.01,upper=10.0,value=1.0) opt_prob.addVar('x2','c',lower=0.01,upper=10.0,value=1.0) opt_prob.addVar('x3','c',lower=0.01,upper=10.0,value=1.0) opt_prob.addVar('x4','c',lower=0.01,upper=10.0,value=1.0) opt_prob.addConGroup('g', 4, 'i') # sanity check print opt_prob print objfun([1.0,1.0,1.0,1.0]) # other optimization methods can be used here - we use sequential least squares programming slsqp = SLSQP() [fstr, xstr, inform] = slsqp(opt_prob) print opt_prob.solution(0) return [v.value for v in opt_prob.solution(0).getVarSet().values()]
def infill(self, points, method='error'): ## We'll be making non-permanent modifications to self.X and self.y here, so lets make a copy just in case initX = np.copy(self.X) inity = np.copy(self.y) ## This array will hold the new values we add returnValues = np.zeros([points, self.k], dtype=float) for i in range(points): opt_prob1 = Optimization('InFillPSO', self.errorObjective_normalized) for k in range(self.k): opt_prob1.addVar('{0}'.format(k), 'c', lower=0, upper=1, value=.5) pso1 = ALPSO() pso1.setOption('SwarmSize', 100) pso1.setOption('maxOuterIter', 100) pso1.setOption('stopCriteria', 1) pso1(opt_prob1) newpoint = np.zeros(self.k) for j in range(self.k): newpoint[j] = opt_prob1.solution(0)._variables[j].value returnValues[i][:] = self.inversenormX(newpoint) self.addPoint(returnValues[i], self.predict(returnValues[i]), norm=True) self.updateModel() del (opt_prob1) del (pso1) self.X = np.copy(initX) self.y = np.copy(inity) self.n = len(self.X) self.updateModel() return returnValues
upper=float(CONS_RHS_MAX_1_php[i - 1]), value=1) opt_prob.addObj('f') for i in range(1, len(NUTRIENTS_php) * 2 + 1): g_value = 'g' + str(i) opt_prob.addCon(g_value, 'i') # Instantiate Optimizer (SLSQP) slsqp = SLSQP() slsqp.setOption('IPRINT', 2) # Solve Problem (Without Parallel Gradient) [fstr, xstr, inform] = slsqp(opt_prob, sens_type='CS') if myrank == 0: sol = opt_prob.solution(0) #end xstr_array = [] for element in xstr: element = decimal.Decimal(element) xstr_array.append(round(element, 4)) results_vector = [] results_vector.append(xstr_array) fstr_array = [] for element in fstr: fstr_array.append(element)
class SLSQP_pyOpt(Algorithm): """ Utilization of the SLSQP algorithm of pyOpt package.""" def __init__(self): """Initialize the SLSQP algorithm for a specific building. """ print("Initializing the SLSQP Optimizer...") self.opt_prob = [] self.opt = [] self.building = Building() def configure(self, building): # Get building and optimization setup properties self.building = deepcopy(building) self.T, self.states, self.actions, self.disturbances, self.controlLim, self.actionLim, self.comfort, self.occ, self.nvars, self.ncons = self.building.getConfiguration( ) # Define Box Constraints (min/max values) for the control parameters boxConstraints = [] for ii in range(self.nvars): boxConstraints.append(self.controlLim) # Link to the python function calculating the cost and the constraints self.opt_prob = Optimization('SLSQP Constrained Problem', self.wrapSimulation) # Setupt Box Constrains in pyOpt for ii in range(self.nvars): self.opt_prob.addVar('x' + str(ii + 1), 'c', lower=boxConstraints[ii][0], upper=boxConstraints[ii][1], value=self.building.policy[0, ii]) # Setupt Cost Function in pyOpt self.opt_prob.addObj('f') # Setupt Inequality Constraints in pyOpt for ii in range(self.ncons): self.opt_prob.addCon('g' + str(ii + 1), 'i') # Print the Optimization setup print("----------------------------------------") print("----------------------------------------") print("SLSQP Optimization setup:") print(self.opt_prob) def optimize(self, options=[]): # Set SLSQP as the optimizer self.opt = SLSQP() # Set optimization options if (len(options) > 0): for ii in range(len(options)): self.opt.setOption(options.keys()[ii], options.values()[ii]) # Print the Optimizer Options print("----------------------------------------") print("----------------------------------------") print("SLSQP Optimizer options:") print(self.opt.options) # Get optimized controller self.opt(self.opt_prob, sens_step=1e-6) print(self.opt_prob.solution(0)) a = self.opt_prob.solution(0) for ii in range(self.building.policy.shape[1]): self.building.policy[0, ii] = a.getVar(ii).value return self.building.policy def wrapSimulation(self, policy): """A function that runs a building simulation and wraps the results in the format required by PyOpt library. Args: policy (numpy array): the controller to be used for the simulation Returns: f (float): the cost function value g (list): the vales of all constraints fail (0/1): indicates if the function finished successfully """ # Cost and Constraints f = 0 g = [] fail = 0 # Run building simulation x, cost, constraints = self.building.simulate(policy) f = np.sum(cost) g.append(np.sum(constraints)) # print(f) # print(g[0]) return f, g, fail
(x[1] - b[i])**2))) #end g = [0.0] * 1 g[0] = 20.04895 - (x[0] + 2.0)**2 - (x[1] + 1.0)**2 fail = 0 return f, g, fail # ============================================================================= # # ============================================================================= opt_prob = Optimization('Langermann Function 11', objfunc) opt_prob.addVar('x1', 'c', lower=-2.0, upper=10.0, value=8.0) opt_prob.addVar('x2', 'c', lower=-2.0, upper=10.0, value=8.0) opt_prob.addObj('f') opt_prob.addCon('g', 'i') print(opt_prob) # Global Optimization nsga2 = NSGA2() nsga2(opt_prob) print(opt_prob.solution(0)) # Local Optimization Refinement slsqp = SLSQP() slsqp(opt_prob.solution(0)) print(opt_prob.solution(0).solution(0))
time.sleep(0.5) fail = 0 return f, g, fail # ============================================================================= # # ============================================================================= # Instantiate Optimization Problem opt_prob = Optimization('TP37 Constrained Problem', objfunc) opt_prob.addVar('x1', 'c', lower=0.0, upper=42.0, value=10.0) opt_prob.addVar('x2', 'c', lower=0.0, upper=42.0, value=10.0) opt_prob.addVar('x3', 'c', lower=0.0, upper=42.0, value=10.0) opt_prob.addObj('f') opt_prob.addCon('g1', 'i') opt_prob.addCon('g2', 'i') # Instantiate Optimizer (SLSQP) slsqp = SLSQP() slsqp.setOption('IPRINT', -1) # Solve Problem (Without Parallel Gradient) slsqp(opt_prob, sens_type='CS') # end # Solve Problem (With Parallel Gradient) slsqp(opt_prob, sens_type='CS', sens_mode='pgc') print opt_prob.solution(1)
def main(): ########################################### # Define some values ########################################### n_blades = 2 n_elements = 10 radius = unit_conversion.in2m(9.6) / 2 root_cutout = 0.1 * radius dy = float(radius - root_cutout) / n_elements dr = float(1) / n_elements y = root_cutout + dy * np.arange(1, n_elements + 1) r = y / radius pitch = 0.0 airfoils = (('SDA1075_494p', 0.0, 1.0), ) allowable_Re = [ 1000000., 500000., 250000., 100000., 90000., 80000., 70000., 60000., 50000., 40000., 30000., 20000., 10000. ] vehicle_weight = 12.455 max_chord = 0.3 max_chord_tip = 5. alt = 0 tip_loss = True mach_corr = False # Forward flight parameters v_inf = 4. # m/s alpha0 = 0.0454 # Starting guess for trimmed alpha in radians n_azi_elements = 5 # Mission times time_in_hover = 300. # Time in seconds time_in_ff = 500. mission_time = [time_in_hover, time_in_ff] Cl_tables = {} Cd_tables = {} Clmax = {} # Get lookup tables if any(airfoil[0] != 'simple' for airfoil in airfoils): for airfoil in airfoils: Cl_table, Cd_table, Clmax = aero_coeffs.create_Cl_Cd_table( airfoil[0]) Cl_tables[airfoil[0]] = Cl_table Cd_tables[airfoil[0]] = Cd_table Clmax[airfoil[0]] = Clmax # Create list of Cl functions. One for each Reynolds number. Cl_tables (and Cd_tables) will be empty for the # 'simple' case, therefore this will be skipped for the simple case. For the full table lookup case this will be # skipped because allowable_Re will be empty. Cl_funs = {} Cd_funs = {} lift_curve_info_dict = {} if Cl_tables and allowable_Re: Cl_funs = dict( zip(allowable_Re, [ aero_coeffs.get_Cl_fun(Re, Cl_tables[airfoils[0][0]], Clmax[airfoils[0][0]][Re]) for Re in allowable_Re ])) Cd_funs = dict( zip(allowable_Re, [ aero_coeffs.get_Cd_fun(Re, Cd_tables[airfoils[0][0]]) for Re in allowable_Re ])) lift_curve_info_dict = aero_coeffs.create_liftCurveInfoDict( allowable_Re, Cl_tables[airfoils[0][0]]) ########################################### # Set design variable bounds ########################################### # Hover opt 500 gen, 1000 pop, 12.455 N weight, 9.6 in prop chord = np.array([ 0.11923604, 0.2168746, 0.31540216, 0.39822882, 0.42919, 0.35039799, 0.3457828, 0.28567224, 0.23418368, 0.13502483 ]) twist = np.array([ 0.45316866, 0.38457724, 0.38225075, 0.34671967, 0.33151445, 0.28719111, 0.25679667, 0.25099005, 0.19400679, 0.10926302 ]) omega = 3811.03596674 * 2 * np.pi / 60 original = (omega, chord, twist) dtwist = np.array( [twist[i + 1] - twist[i] for i in xrange(len(twist) - 1)]) dchord = np.array( [chord[i + 1] - chord[i] for i in xrange(len(chord) - 1)]) twist0 = twist[0] chord0 = chord[0] omega_start = omega dtwist_start = dtwist dchord_start = dchord twist0_start = twist0 chord0_start = chord0 omega_lower = 2000 * 2 * np.pi / 60 omega_upper = 8000.0 * 2 * np.pi / 60 twist0_lower = 0. * 2 * np.pi / 360 twist0_upper = 60. * 2 * np.pi / 360 chord0_upper = 0.1198 chord0_lower = 0.05 dtwist_lower = -10.0 * 2 * np.pi / 360 dtwist_upper = 10.0 * 2 * np.pi / 360 dchord_lower = -0.1 dchord_upper = 0.1 opt_prob = Optimization('Mission Simulator', objfun) opt_prob.addVar('omega_h', 'c', value=omega_start, lower=omega_lower, upper=omega_upper) opt_prob.addVar('twist0', 'c', value=twist0_start, lower=twist0_lower, upper=twist0_upper) opt_prob.addVar('chord0', 'c', value=chord0_start, lower=chord0_lower, upper=chord0_upper) opt_prob.addVarGroup('dtwist', n_elements - 1, 'c', value=dtwist_start, lower=dtwist_lower, upper=dtwist_upper) opt_prob.addVarGroup('dchord', n_elements - 1, 'c', value=dchord_start, lower=dchord_lower, upper=dchord_upper) opt_prob.addObj('f') opt_prob.addCon('thrust', 'i') opt_prob.addCon('c_tip', 'i') opt_prob.addConGroup('c_lower', n_elements, 'i') opt_prob.addConGroup('c_upper', n_elements, 'i') print opt_prob slsqp = SLSQP() slsqp.setOption('IPRINT', 1) slsqp.setOption('MAXIT', 1000) slsqp.setOption('ACC', 1e-8) fstr, xstr, inform = slsqp(opt_prob, sens_type='FD', n_blades=n_blades, radius=radius, dy=dy, dr=dr, y=y, r=r, pitch=pitch, airfoils=airfoils, vehicle_weight=vehicle_weight, max_chord=max_chord, tip_loss=tip_loss, mach_corr=mach_corr, Cl_funs=Cl_funs, Cd_funs=Cd_funs, Cl_tables=Cl_tables, Cd_tables=Cd_tables, allowable_Re=allowable_Re, alt=alt, v_inf=v_inf, alpha0=alpha0, mission_time=mission_time, n_azi_elements=n_azi_elements, lift_curve_info_dict=lift_curve_info_dict, max_chord_tip=max_chord_tip) print opt_prob.solution(0) # pop_size = 300 # max_gen = 500 # opt_method = 'nograd' # nsga2 = NSGA2() # nsga2.setOption('PrintOut', 2) # nsga2.setOption('PopSize', pop_size) # nsga2.setOption('maxGen', max_gen) # nsga2.setOption('pCross_real', 0.85) # nsga2.setOption('xinit', 1) # fstr, xstr, inform = nsga2(opt_prob, n_blades=n_blades, radius=radius, dy=dy, dr=dr, y=y, r=r, pitch=pitch, # airfoils=airfoils, vehicle_weight=vehicle_weight, max_chord=max_chord, tip_loss=tip_loss, # mach_corr=mach_corr, Cl_funs=Cl_funs, Cd_funs=Cd_funs, Cl_tables=Cl_tables, # Cd_tables=Cd_tables, allowable_Re=allowable_Re, opt_method=opt_method, alt=alt, # v_inf=v_inf, alpha0=alpha0, mission_time=mission_time, n_azi_elements=n_azi_elements, # pop_size=pop_size, max_gen=max_gen, lift_curve_info_dict=lift_curve_info_dict, # max_chord_tip=max_chord_tip) # print opt_prob.solution(0) # opt_method = 'nograd' # xstart_alpso = np.concatenate((np.array([omega_start, twist0_start, chord0_start]), dtwist_start, dchord_start)) # alpso = ALPSO() # alpso.setOption('xinit', 0) # alpso.setOption('SwarmSize', 200) # alpso.setOption('maxOuterIter', 100) # alpso.setOption('stopCriteria', 0) # fstr, xstr, inform = alpso(opt_prob, xstart=xstart_alpso, n_blades=n_blades, n_elements=n_elements, # root_cutout=root_cutout, radius=radius, dy=dy, dr=dr, y=y, r=r, pitch=pitch, # airfoils=airfoils, thrust=thrust, max_chord=max_chord, tip_loss=tip_loss, # mach_corr=mach_corr, Cl_funs=Cl_funs, Cd_funs=Cd_funs, Cl_tables=Cl_tables, # Cd_tables=Cd_tables, allowable_Re=allowable_Re, opt_method=opt_method) # print opt_prob.solution(0) def get_performance(o, c, t): chord_meters = c * radius prop = propeller.Propeller(t, chord_meters, radius, n_blades, r, y, dr, dy, airfoils=airfoils, Cl_tables=Cl_tables, Cd_tables=Cd_tables) quad = quadrotor.Quadrotor(prop, vehicle_weight) ff_kwargs = { 'propeller': prop, 'pitch': pitch, 'n_azi_elements': n_azi_elements, 'allowable_Re': allowable_Re, 'Cl_funs': Cl_funs, 'Cd_funs': Cd_funs, 'tip_loss': tip_loss, 'mach_corr': mach_corr, 'alt': alt, 'lift_curve_info_dict': lift_curve_info_dict } trim0 = np.array([alpha0, o]) alpha_trim, omega_trim, converged = trim.trim(quad, v_inf, trim0, ff_kwargs) T_ff, H_ff, P_ff = bemt.bemt_forward_flight( quad, pitch, omega_trim, alpha_trim, v_inf, n_azi_elements, alt=alt, tip_loss=tip_loss, mach_corr=mach_corr, allowable_Re=allowable_Re, Cl_funs=Cl_funs, Cd_funs=Cd_funs, lift_curve_info_dict=lift_curve_info_dict) dT_h, P_h = bemt.bemt_axial(prop, pitch, o, allowable_Re=allowable_Re, Cl_funs=Cl_funs, Cd_funs=Cd_funs, tip_loss=tip_loss, mach_corr=mach_corr, alt=alt) return sum(dT_h), P_h, T_ff, P_ff, alpha_trim, omega_trim omega = xstr[0] twist0 = xstr[1] chord0 = xstr[2] dtwist = xstr[3:3 + len(r) - 1] dchord = xstr[3 + len(r) - 1:] twist = calc_twist_dist(twist0, dtwist) chord = calc_chord_dist(chord0, dchord) print "chord = " + repr(chord) print "twist = " + repr(twist) # twist_base = calc_twist_dist(twist0_base, dtwist_base) # chord_base = calc_chord_dist(chord0_base, dchord_base) perf_opt = get_performance(omega, chord, twist) perf_orig = get_performance(original[0], original[1], original[2]) print "omega_orig = " + str(original[0]) print "Hover Thrust of original = " + str(perf_orig[0]) print "Hover Power of original = " + str(perf_orig[1]) print "FF Thrust of original = " + str(perf_orig[2]) print "FF Power of original = " + str(perf_orig[3]) print "Trim original (alpha, omega) = (%f, %f)" % (perf_orig[4], perf_orig[5]) print "omega = " + str(omega * 60 / 2 / np.pi) print "Hover Thrust of optimized = " + str(perf_opt[0]) print "Hover Power of optimized = " + str(perf_opt[1]) print "FF Thrust of optimized = " + str(perf_opt[2]) print "FF Power of optimized = " + str(perf_opt[3]) print "Trim optimized (alpha, omega) = (%f, %f)" % (perf_opt[4], perf_opt[5]) # print "Omega base = " + str(omega_start*60/2/np.pi) # print "Thrust of base = " + str(sum(perf_base[0])) # print "Power of base = " + str(sum(perf_base[1])) # plt.figure(1) plt.plot(r, original[1], '-b') plt.plot(r, chord, '-r') plt.xlabel('radial location') plt.ylabel('c/R') plt.legend(['start', 'opt']) plt.figure(2) plt.plot(r, original[2] * 180 / np.pi, '-b') plt.plot(r, twist * 180 / np.pi, '-r') plt.xlabel('radial location') plt.ylabel('twist') plt.legend(['start', 'opt']) plt.show()
#print out the problem print opt_prob #Run the GA # nsga = NSGA2(PopSize=300, maxGen=500, pMut_real=.1) # nsga(opt_prob) # pso = ALPSO() pso.setOption('SwarmSize', 30) pso.setOption('maxOuterIter', 100) pso.setOption('stopCriteria', 1) # pso.setOption('dt',1) pso(opt_prob) #print the best solution print opt_prob.solution(0) # Update the model variables to the best solution found by the optimizer a.update([ opt_prob.solution(0)._variables[0].value, opt_prob.solution(0)._variables[1].value, opt_prob.solution(0)._variables[2].value, opt_prob.solution(0)._variables[3].value, opt_prob.solution(0)._variables[4].value, opt_prob.solution(0)._variables[5].value ]) for enu, i in enumerate(x): print y[enu], a.predict(i)
def optimizeTrajectory(self, plot_func=None): # use non-linear optimization to find parameters for minimal # condition number trajectory self.plot_func = plot_func if self.config['showOptimizationGraph']: self.initGraph() ## describe optimization problem with pyOpt classes from pyOpt import Optimization from pyOpt import ALPSO, SLSQP # Instanciate Optimization Problem opt_prob = Optimization('Trajectory optimization', self.objective_func) opt_prob.addObj('f') # add variables, define bounds # w_f - pulsation opt_prob.addVar('wf', 'c', value=self.wf_init, lower=self.wf_min, upper=self.wf_max) # q - offsets for i in range(self.dofs): opt_prob.addVar('q_%d'%i,'c', value=self.qinit[i], lower=self.qmin[i], upper=self.qmax[i]) # a, b - sin/cos params for i in range(self.dofs): for j in range(self.nf[0]): opt_prob.addVar('a{}_{}'.format(i,j), 'c', value=self.ainit[i][j], lower=self.amin, upper=self.amax) for i in range(self.dofs): for j in range(self.nf[0]): opt_prob.addVar('b{}_{}'.format(i,j), 'c', value=self.binit[i][j], lower=self.bmin, upper=self.bmax) # add constraint vars (constraint functions are in obfunc) if self.config['minVelocityConstraint']: opt_prob.addConGroup('g', self.dofs*5, 'i') else: opt_prob.addConGroup('g', self.dofs*4, 'i') #print opt_prob initial = [v.value for v in list(opt_prob._variables.values())] if self.config['useGlobalOptimization']: ### optimize using pyOpt (global) opt = ALPSO() #augmented lagrange particle swarm optimization opt.setOption('stopCriteria', 0) opt.setOption('maxInnerIter', 3) opt.setOption('maxOuterIter', self.config['globalOptIterations']) opt.setOption('printInnerIters', 1) opt.setOption('printOuterIters', 1) opt.setOption('SwarmSize', 30) opt.setOption('xinit', 1) #TODO: how to properly limit max number of function calls? # no. func calls = (SwarmSize * inner) * outer + SwarmSize self.iter_max = opt.getOption('SwarmSize') * opt.getOption('maxInnerIter') * opt.getOption('maxOuterIter') + opt.getOption('SwarmSize') # run fist (global) optimization try: #reuse history opt(opt_prob, store_hst=False, hot_start=True, xstart=initial) except NameError: opt(opt_prob, store_hst=False, xstart=initial) print(opt_prob.solution(0)) ### pyOpt local # after using global optimization, get more exact solution with # gradient based method init optimizer (only local) opt2 = SLSQP() #sequential least squares opt2.setOption('MAXIT', self.config['localOptIterations']) if self.config['verbose']: opt2.setOption('IPRINT', 0) # TODO: amount of function calls depends on amount of variables and iterations to approximate gradient # iterations are probably steps along the gradient. How to get proper no. of func calls? self.iter_max = "(unknown)" if self.config['useGlobalOptimization']: if self.last_best_sol is not None: #use best constrained solution for i in range(len(opt_prob._variables)): opt_prob._variables[i].value = self.last_best_sol[i] else: #reuse previous solution for i in range(len(opt_prob._variables)): opt_prob._variables[i].value = opt_prob.solution(0).getVar(i).value opt2(opt_prob, store_hst=False, sens_step=0.1) else: try: #reuse history opt2(opt_prob, store_hst=True, hot_start=True, sens_step=0.1) except NameError: opt2(opt_prob, store_hst=True, sens_step=0.1) local_sol = opt_prob.solution(0) if not self.config['useGlobalOptimization']: print(local_sol) local_sol_vec = np.array([local_sol.getVar(x).value for x in range(0,len(local_sol._variables))]) if self.last_best_sol is not None: local_sol_vec = self.last_best_sol print("using last best constrained solution instead of given solver solution.") sol_wf, sol_q, sol_a, sol_b = self.vecToParams(local_sol_vec) print("testing final solution") self.iter_cnt = 0 self.objective_func(local_sol_vec) print("\n") self.trajectory.initWithParams(sol_a, sol_b, sol_q, self.nf, sol_wf) if self.config['showOptimizationGraph']: plt.ioff() return self.trajectory
def execute(self): """pyOpt execution. Note that pyOpt controls the execution, and the individual optimizers control the iteration.""" self.pyOpt_solution = None opt_prob = Optimization(self.title, self.objfunc, var_set={}, obj_set={}, con_set={}) # Add all parameters for name, param in self.get_parameters().iteritems(): val = param.evaluate() # We need to identify Enums, Lists, Dicts metadata = param.get_metadata()[0][1] # enumerated, discrete or continuous choices = [] if ('values' in metadata and \ isinstance(metadata['values'],(list, tuple, array, set))): vartype = 'd' choices = metadata['values'] elif isinstance(val, bool): vartype = 'd' choices = [True, False] elif isinstance(val, (int, int32, int64)): vartype = 'i' elif isinstance(val, (float, float32, float64)): vartype = 'c' else: msg = 'Only continuous, descrete, or enumerated variables ' + \ 'are supported. %s is %s.' % (name, type(val)) self.raise_exception(msg, ValueError) opt_prob.addVar(name, vartype, lower=param.low, upper=param.high, value=val, choices=choices) # Add all objectives for name in self.get_objectives().keys(): opt_prob.addObj(name) # Add all equality constraints for name in self.get_eq_constraints().keys(): opt_prob.addCon(name, type='e') # Add all inequality constraints for name in self.get_ineq_constraints().keys(): opt_prob.addCon(name, type='i') # Instantiate the requested optimizer optimizer = self.optimizer try: exec('from pyOpt import %s' % optimizer) except ImportError: msg = "Optimizer %s is not avialable in this installation." % \ optimizer self.raise_exception(msg, ImportError) optname = vars()[optimizer] opt = optname() # Set optimization options for option, value in self.options.iteritems(): opt.setOption(option, value) # Execute the optimization problem if self.differentiator: # Use OpenMDAO's differentiator for the gradient opt(opt_prob, sens_type=self.gradfunc) else: # Use pyOpt's internal finite difference opt(opt_prob, sens_type='FD') # Print results if self.print_results: print opt_prob.solution(0) # Pull optimal parameters back into framework and re-run, so that # framework is left in the right final state dvals = [] for i in range(0, len(opt_prob.solution(0)._variables)): dvals.append(opt_prob.solution(0)._variables[i].value) self.set_parameters(dvals) self.run_iteration() # Save the most recent solution. self.pyOpt_solution = opt_prob.solution(0)
def main(): ########################################### # Define some values ########################################### n_blades = 2 n_elements = 10 radius = unit_conversion.in2m(9.6) / 2 root_cutout = 0.1 * radius dy = float(radius - root_cutout) / n_elements dr = float(1) / n_elements y = root_cutout + dy * np.arange(1, n_elements + 1) r = y / radius pitch = 0.0 airfoils = (('SDA1075_494p', 0.0, 1.0), ) #allowable_Re = [] allowable_Re = [ 1000000., 500000., 250000., 100000., 90000., 80000., 70000., 60000., 50000., 40000., 30000., 20000., 10000. ] vehicle_weight = 12.455 max_chord = 0.6 max_chord_tip = 5. alt = 0 tip_loss = True mach_corr = False # Forward flight parameters v_inf = 4. # m/s alpha0 = 0.0454 # Starting guess for trimmed alpha in radians n_azi_elements = 5 # Mission times time_in_hover = 0. # Time in seconds time_in_ff = 500. mission_time = [time_in_hover, time_in_ff] Cl_tables = {} Cd_tables = {} Clmax = {} # Get lookup tables if any(airfoil[0] != 'simple' for airfoil in airfoils): for airfoil in airfoils: Cl_table, Cd_table, Clmax = aero_coeffs.create_Cl_Cd_table( airfoil[0]) Cl_tables[airfoil[0]] = Cl_table Cd_tables[airfoil[0]] = Cd_table Clmax[airfoil[0]] = Clmax # Create list of Cl functions. One for each Reynolds number. Cl_tables (and Cd_tables) will be empty for the # 'simple' case, therefore this will be skipped for the simple case. For the full table lookup case this will be # skipped because allowable_Re will be empty. Cl_funs = {} Cd_funs = {} lift_curve_info_dict = {} if Cl_tables and allowable_Re: Cl_funs = dict( zip(allowable_Re, [ aero_coeffs.get_Cl_fun(Re, Cl_tables[airfoils[0][0]], Clmax[airfoils[0][0]][Re]) for Re in allowable_Re ])) Cd_funs = dict( zip(allowable_Re, [ aero_coeffs.get_Cd_fun(Re, Cd_tables[airfoils[0][0]]) for Re in allowable_Re ])) lift_curve_info_dict = aero_coeffs.create_liftCurveInfoDict( allowable_Re, Cl_tables[airfoils[0][0]]) ########################################### # Set design variable bounds ########################################### omega_start = 4250. * 2 * np.pi / 60 # These are c/R values for the DA4002 propeller given at the UIUC propeller database chord_base = np.array([ 0.1198, 0.1128, 0.1436, 0.1689, 0.1775, 0.1782, 0.1773, 0.1782, 0.1790, 0.1787, 0.1787, 0.1786, 0.1785, 0.1790, 0.1792, 0.1792, 0.1692, 0.0154 ]) chord_base = np.array( [chord_base[i] for i in [0, 2, 4, 6, 8, 10, 12, 14, 15, 17]]) twist_base = np.array([ 42.481, 44.647, 41.154, 37.475, 34.027, 30.549, 27.875, 25.831, 23.996, 22.396, 21.009, 19.814, 18.786, 17.957, 17.245, 16.657, 13.973, 2.117 ]) * 2 * np.pi / 360 twist_base = np.array( [twist_base[i] for i in [0, 2, 4, 6, 8, 10, 12, 14, 15, 17]]) dtwist_base = np.array([ twist_base[i + 1] - twist_base[i] for i in xrange(len(twist_base) - 1) ]) dchord_base = np.array([ chord_base[i + 1] - chord_base[i] for i in xrange(len(chord_base) - 1) ]) twist0_base = twist_base[0] chord0_base = chord_base[0] chord_start = chord_base twist_start = twist_base dtwist_start = dtwist_base dchord_start = dchord_base twist0_start = twist0_base chord0_start = chord0_base print "chord0_start = " + str(chord0_start) omega_lower = 2000 * 2 * np.pi / 60 omega_upper = 8000.0 * 2 * np.pi / 60 twist0_lower = 0. * 2 * np.pi / 360 twist0_upper = 60. * 2 * np.pi / 360 chord0_upper = 0.1198 chord0_lower = 0.05 dtwist_lower = -10.0 * 2 * np.pi / 360 dtwist_upper = 10.0 * 2 * np.pi / 360 dchord_lower = -0.1 dchord_upper = 0.1 opt_prob = Optimization('Mission Simulator', objfun) opt_prob.addVar('omega_h', 'c', value=omega_start, lower=omega_lower, upper=omega_upper) opt_prob.addVar('twist0', 'c', value=twist0_start, lower=twist0_lower, upper=twist0_upper) opt_prob.addVar('chord0', 'c', value=chord0_start, lower=chord0_lower, upper=chord0_upper) opt_prob.addVarGroup('dtwist', n_elements - 1, 'c', value=dtwist_start, lower=dtwist_lower, upper=dtwist_upper) opt_prob.addVarGroup('dchord', n_elements - 1, 'c', value=dchord_start, lower=dchord_lower, upper=dchord_upper) opt_prob.addObj('f') opt_prob.addCon('thrust', 'i') opt_prob.addCon('c_tip', 'i') opt_prob.addConGroup('c_lower', n_elements, 'i') opt_prob.addConGroup('c_upper', n_elements, 'i') print opt_prob pop_size = 300 max_gen = 1100 opt_method = 'nograd' nsga2 = NSGA2() nsga2.setOption('PrintOut', 2) nsga2.setOption('PopSize', pop_size) nsga2.setOption('maxGen', max_gen) nsga2.setOption('pCross_real', 0.85) nsga2.setOption('pMut_real', 0.2) nsga2.setOption('xinit', 1) fstr, xstr, inform = nsga2(opt_prob, n_blades=n_blades, radius=radius, dy=dy, dr=dr, y=y, r=r, pitch=pitch, airfoils=airfoils, vehicle_weight=vehicle_weight, max_chord=max_chord, tip_loss=tip_loss, mach_corr=mach_corr, Cl_funs=Cl_funs, Cd_funs=Cd_funs, Cl_tables=Cl_tables, Cd_tables=Cd_tables, allowable_Re=allowable_Re, opt_method=opt_method, alt=alt, v_inf=v_inf, alpha0=alpha0, mission_time=mission_time, n_azi_elements=n_azi_elements, pop_size=pop_size, max_gen=max_gen, lift_curve_info_dict=lift_curve_info_dict, max_chord_tip=max_chord_tip) print opt_prob.solution(0) # opt_method = 'nograd' # xstart_alpso = np.concatenate((np.array([omega_start, twist0_start, chord0_start]), dtwist_start, dchord_start)) # alpso = ALPSO() # alpso.setOption('xinit', 0) # alpso.setOption('SwarmSize', 200) # alpso.setOption('maxOuterIter', 100) # alpso.setOption('stopCriteria', 0) # fstr, xstr, inform = alpso(opt_prob, xstart=xstart_alpso, n_blades=n_blades, n_elements=n_elements, # root_cutout=root_cutout, radius=radius, dy=dy, dr=dr, y=y, r=r, pitch=pitch, # airfoils=airfoils, thrust=thrust, max_chord=max_chord, tip_loss=tip_loss, # mach_corr=mach_corr, Cl_funs=Cl_funs, Cd_funs=Cd_funs, Cl_tables=Cl_tables, # Cd_tables=Cd_tables, allowable_Re=allowable_Re, opt_method=opt_method) # print opt_prob.solution(0) # opt_method = 'grad' # slsqp = SLSQP() # slsqp.setOption('IPRINT', 1) # slsqp.setOption('MAXIT', 1000) # slsqp.setOption('ACC', 1e-7) # fstr, xstr, inform = slsqp(opt_prob, sens_type='FD', n_blades=n_blades, n_elements=n_elements, # root_cutout=root_cutout, radius=radius, dy=dy, dr=dr, y=y, r=r, pitch=pitch, # airfoils=airfoils, thrust=thrust, max_chord=max_chord, # tip_loss=tip_loss, mach_corr=mach_corr, Cl_funs=Cl_funs, Cd_funs=Cd_funs, # Cl_tables=Cl_tables, Cd_tables=Cd_tables, allowable_Re=allowable_Re, # opt_method=opt_method, alt=alt) # print opt_prob.solution(0) def get_performance(o, c, t): chord_meters = c * radius prop = propeller.Propeller(t, chord_meters, radius, n_blades, r, y, dr, dy, airfoils=airfoils, Cl_tables=Cl_tables, Cd_tables=Cd_tables) quad = quadrotor.Quadrotor(prop, vehicle_weight) ff_kwargs = { 'propeller': prop, 'pitch': pitch, 'n_azi_elements': n_azi_elements, 'allowable_Re': allowable_Re, 'Cl_funs': Cl_funs, 'Cd_funs': Cd_funs, 'tip_loss': tip_loss, 'mach_corr': mach_corr, 'alt': alt, 'lift_curve_info_dict': lift_curve_info_dict } trim0 = np.array([alpha0, o]) alpha_trim, omega_trim, converged = trim.trim(quad, v_inf, trim0, ff_kwargs) T_ff, H_ff, P_ff = bemt.bemt_forward_flight( quad, pitch, omega_trim, alpha_trim, v_inf, n_azi_elements, alt=alt, tip_loss=tip_loss, mach_corr=mach_corr, allowable_Re=allowable_Re, Cl_funs=Cl_funs, Cd_funs=Cd_funs, lift_curve_info_dict=lift_curve_info_dict) dT_h, P_h = bemt.bemt_axial(prop, pitch, o, allowable_Re=allowable_Re, Cl_funs=Cl_funs, Cd_funs=Cd_funs, tip_loss=tip_loss, mach_corr=mach_corr, alt=alt) return sum(dT_h), P_h, T_ff, P_ff, alpha_trim, omega_trim omega = xstr[0] twist0 = xstr[1] chord0 = xstr[2] dtwist = xstr[3:3 + len(r) - 1] dchord = xstr[3 + len(r) - 1:] twist = calc_twist_dist(twist0, dtwist) chord = calc_chord_dist(chord0, dchord) print "chord = " + repr(chord) print "twist = " + repr(twist) # twist_base = calc_twist_dist(twist0_base, dtwist_base) # chord_base = calc_chord_dist(chord0_base, dchord_base) perf_opt = get_performance(omega, chord, twist) #perf_base = get_performance(omega_start, chord_base, twist_base) print "omega = " + str(omega * 60 / 2 / np.pi) print "Hover Thrust of optimized = " + str(perf_opt[0]) print "Hover Power of optimized = " + str(perf_opt[1]) print "FF Thrust of optimized = " + str(perf_opt[2]) print "FF Power of optimized = " + str(perf_opt[3]) print "Trim (alpha, omega) = (%f, %f)" % (perf_opt[4], perf_opt[5])
def main(): ########################################### # Define some values ########################################### n_blades = 2 n_elements = 10 radius = unit_conversion.in2m(9.6) / 2 #radius = 0.1397 root_cutout = 0.1 * radius dy = float(radius - root_cutout) / n_elements dr = float(1) / n_elements y = root_cutout + dy * np.arange(1, n_elements + 1) r = y / radius pitch = 0.0 airfoils = (('SDA1075_494p', 0.0, 1.0), ) #allowable_Re = [] allowable_Re = [ 1000000., 500000., 250000., 100000., 90000., 80000., 70000., 60000., 50000., 40000., 30000., 20000., 10000. ] vehicle_weight = 12.455 max_chord = 0.6 alt = 0 tip_loss = True mach_corr = False Cl_tables = {} Cd_tables = {} Clmax = {} # Get lookup tables if any(airfoil[0] != 'simple' for airfoil in airfoils): for airfoil in airfoils: Cl_table, Cd_table, Clmax = aero_coeffs.create_Cl_Cd_table( airfoil[0]) Cl_tables[airfoil[0]] = Cl_table Cd_tables[airfoil[0]] = Cd_table Clmax[airfoil[0]] = Clmax # Create list of Cl functions. One for each Reynolds number. Cl_tables (and Cd_tables) will be empty for the # 'simple' case, therefore this will be skipped for the simple case. For the full table lookup case this will be # skipped because allowable_Re will be empty. Cl_funs = {} Cd_funs = {} lift_curve_info_dict = {} if Cl_tables and allowable_Re: Cl_funs = dict( zip(allowable_Re, [ aero_coeffs.get_Cl_fun(Re, Cl_tables[airfoils[0][0]], Clmax[airfoils[0][0]][Re]) for Re in allowable_Re ])) Cd_funs = dict( zip(allowable_Re, [ aero_coeffs.get_Cd_fun(Re, Cd_tables[airfoils[0][0]]) for Re in allowable_Re ])) lift_curve_info_dict = aero_coeffs.create_liftCurveInfoDict( allowable_Re, Cl_tables[airfoils[0][0]]) ########################################### # Set design variable bounds ########################################### omega_start = 4250. * 2 * np.pi / 60 chord_base = np.array([ 0.1198, 0.1128, 0.1436, 0.1689, 0.1775, 0.1782, 0.1773, 0.1782, 0.1790, 0.1787, 0.1787, 0.1786, 0.1785, 0.1790, 0.1792, 0.1792, 0.1692, 0.0154 ]) chord_base = np.array( [chord_base[i] for i in [0, 2, 4, 6, 8, 10, 12, 14, 15, 17]]) twist_base = np.array([ 42.481, 44.647, 41.154, 37.475, 34.027, 30.549, 27.875, 25.831, 23.996, 22.396, 21.009, 19.814, 18.786, 17.957, 17.245, 16.657, 13.973, 2.117 ]) * 2 * np.pi / 360 twist_base = np.array( [twist_base[i] for i in [0, 2, 4, 6, 8, 10, 12, 14, 15, 17]]) dtwist_base = np.array([ twist_base[i + 1] - twist_base[i] for i in xrange(len(twist_base) - 1) ]) dchord_base = np.array([ chord_base[i + 1] - chord_base[i] for i in xrange(len(chord_base) - 1) ]) twist0_base = twist_base[0] chord0_base = chord_base[0] chord_start = chord_base twist_start = twist_base dtwist_start = dtwist_base dchord_start = dchord_base twist0_start = twist0_base chord0_start = chord0_base # chord = np.array([8.92386048e-02, 1.73000845e-01, 2.70523039e-01, 2.71542807e-01, 2.78749355e-01, 2.36866151e-01, # 2.04103526e-01, 1.37456074e-01, 8.68094589e-02, 1.05601135e-04]) # twist = np.array([0.00161645, 0.15105685, 0.28791442, 0.31577392, 0.28644651, 0.27418749, 0.24854514, 0.21812646, # 0.19802027, 0.14972058]) # omega_start = 3184.41320387 * 2*np.pi/60 # chord_start = chord # twist_start = twist # dchord_start = np.array([chord[i+1]-chord[i] for i in xrange(len(chord)-1)]) # dtwist_start = np.array([twist[i+1]-twist[i] for i in xrange(len(twist)-1)]) # twist0_start = twist[0] # chord0_start = chord[0] ## Initialize everything to zeros # dtwist_start = np.zeros(n_elements-1) # dchord_start = np.zeros(n_elements-1) # twist0_start = 0.0 # chord0_start = 0.0 omega_lower = 2000 * 2 * np.pi / 60 omega_upper = 8000.0 * 2 * np.pi / 60 twist0_lower = 0.0 * 2 * np.pi / 360 twist0_upper = 60. * 2 * np.pi / 360 chord0_upper = 0.1198 chord0_lower = 0.05 dtwist_lower = -10.0 * 2 * np.pi / 360 dtwist_upper = 10.0 * 2 * np.pi / 360 dchord_lower = -0.1 dchord_upper = 0.1 opt_prob = Optimization('Rotor in Hover', objfun) opt_prob.addVar('omega', 'c', value=omega_start, lower=omega_lower, upper=omega_upper) opt_prob.addVar('twist0', 'c', value=twist0_start, lower=twist0_lower, upper=twist0_upper) opt_prob.addVar('chord0', 'c', value=chord0_start, lower=chord0_lower, upper=chord0_upper) opt_prob.addVarGroup('dtwist', n_elements - 1, 'c', value=dtwist_start, lower=dtwist_lower, upper=dtwist_upper) opt_prob.addVarGroup('dchord', n_elements - 1, 'c', value=dchord_start, lower=dchord_lower, upper=dchord_upper) opt_prob.addObj('f') opt_prob.addCon('thrust', 'i') opt_prob.addConGroup('c_lower', n_elements, 'i') opt_prob.addConGroup('c_upper', n_elements, 'i') print opt_prob opt_method = 'nograd' nsga2 = NSGA2() nsga2.setOption('PrintOut', 2) nsga2.setOption('PopSize', 300) nsga2.setOption('maxGen', 1100) nsga2.setOption('pCross_real', 0.85) nsga2.setOption('xinit', 1) fstr, xstr, inform = nsga2(opt_prob, n_blades=n_blades, n_elements=n_elements, root_cutout=root_cutout, radius=radius, dy=dy, dr=dr, y=y, r=r, pitch=pitch, airfoils=airfoils, vehicle_weight=vehicle_weight, max_chord=max_chord, tip_loss=tip_loss, mach_corr=mach_corr, Cl_funs=Cl_funs, Cd_funs=Cd_funs, Cl_tables=Cl_tables, Cd_tables=Cd_tables, allowable_Re=allowable_Re, opt_method=opt_method, alt=alt, lift_curve_info_dict=lift_curve_info_dict) print opt_prob.solution(0) # opt_method = 'nograd' # xstart_alpso = np.concatenate((np.array([omega_start, twist0_start, chord0_start]), dtwist_start, dchord_start)) # alpso = ALPSO() # alpso.setOption('xinit', 0) # alpso.setOption('SwarmSize', 200) # alpso.setOption('maxOuterIter', 100) # alpso.setOption('stopCriteria', 0) # fstr, xstr, inform = alpso(opt_prob, xstart=xstart_alpso, n_blades=n_blades, n_elements=n_elements, # root_cutout=root_cutout, radius=radius, dy=dy, dr=dr, y=y, r=r, pitch=pitch, # airfoils=airfoils, thrust=thrust, max_chord=max_chord, tip_loss=tip_loss, # mach_corr=mach_corr, Cl_funs=Cl_funs, Cd_funs=Cd_funs, Cl_tables=Cl_tables, # Cd_tables=Cd_tables, allowable_Re=allowable_Re, opt_method=opt_method) # print opt_prob.solution(0) # opt_method = 'grad' # slsqp = SLSQP() # slsqp.setOption('IPRINT', 1) # slsqp.setOption('MAXIT', 1000) # slsqp.setOption('ACC', 1e-7) # fstr, xstr, inform = slsqp(opt_prob, sens_type='FD', n_blades=n_blades, n_elements=n_elements, # root_cutout=root_cutout, radius=radius, dy=dy, dr=dr, y=y, r=r, pitch=pitch, # airfoils=airfoils, thrust=thrust, max_chord=max_chord, # tip_loss=tip_loss, mach_corr=mach_corr, Cl_funs=Cl_funs, Cd_funs=Cd_funs, # Cl_tables=Cl_tables, Cd_tables=Cd_tables, allowable_Re=allowable_Re, # opt_method=opt_method, alt=alt) # print opt_prob.solution(0) def get_performance(o, c, t): chord_meters = c * radius prop = propeller.Propeller(t, chord_meters, radius, n_blades, r, y, dr, dy, airfoils=airfoils, Cl_tables=Cl_tables, Cd_tables=Cd_tables) return bemt.bemt_axial(prop, pitch, o, allowable_Re=allowable_Re, Cl_funs=Cl_funs, Cd_funs=Cd_funs, tip_loss=tip_loss, mach_corr=mach_corr, output='long', alt=alt) omega = xstr[0] twist0 = xstr[1] chord0 = xstr[2] dtwist = xstr[3:3 + len(r) - 1] dchord = xstr[3 + len(r) - 1:] twist = calc_twist_dist(twist0, dtwist) chord = calc_chord_dist(chord0, dchord) print "chord = " + repr(chord) print "twist = " + repr(twist) # twist_base = calc_twist_dist(twist0_base, dtwist_base) # chord_base = calc_chord_dist(chord0_base, dchord_base) perf_opt = get_performance(omega, chord, twist) #perf_base = get_performance(omega_start, chord_base, twist_base) print "omega = " + str(omega * 60 / 2 / np.pi) print "Thrust of optimized = " + str(sum(perf_opt[0])) print "Power of optimized = " + str(perf_opt[1]) # print "Omega base = " + str(omega_start*60/2/np.pi) # print "Thrust of base = " + str(sum(perf_base[0])) # print "Power of base = " + str(sum(perf_base[1])) plt.figure(1) plt.plot(r, chord_start, '-b') plt.plot(r, chord, '-r') plt.xlabel('radial location') plt.ylabel('c/R') plt.legend(['start', 'opt']) plt.figure(2) plt.plot(r, twist_start * 180 / np.pi, '-b') plt.plot(r, twist * 180 / np.pi, '-r') plt.xlabel('radial location') plt.ylabel('twist') plt.legend(['start', 'opt']) plt.show()
f += -(c[i]*exp(-(1/pi)*((x[0]-a[i])**2 + (x[1]-b[i])**2))*cos(pi*((x[0]-a[i])**2 + (x[1]-b[i])**2))) #end g = [0.0]*1 g[0] = 20.04895 - (x[0]+2.0)**2 - (x[1]+1.0)**2 fail = 0 return f,g,fail # ============================================================================= # # ============================================================================= opt_prob = Optimization('Langermann Function 11',objfunc) opt_prob.addVar('x1','c',lower=-2.0,upper=10.0,value=8.0) opt_prob.addVar('x2','c',lower=-2.0,upper=10.0,value=8.0) opt_prob.addObj('f') opt_prob.addCon('g','i') print opt_prob # Global Optimization nsga2 = NSGA2() nsga2(opt_prob) print opt_prob.solution(0) # Local Optimization Refinement slsqp = SLSQP() slsqp(opt_prob.solution(0)) print opt_prob.solution(0).solution(0)
# ============================================================================= # # ============================================================================= opt_prob = Optimization('Rosenbrock Unconstraint Problem', objfunc) opt_prob.addVar('x1', 'c', lower=-10.0, upper=10.0, value=-3.0) opt_prob.addVar('x2', 'c', lower=-10.0, upper=10.0, value=-4.0) opt_prob.addObj('f') print(opt_prob) # Instantiate Optimizer (PSQP) & Solve Problem psqp = PSQP() psqp.setOption('IPRINT', 0) psqp(opt_prob, sens_type='FD') print(opt_prob.solution(0)) # Instantiate Optimizer (SLSQP) & Solve Problem slsqp = SLSQP() slsqp.setOption('IPRINT', -1) slsqp(opt_prob, sens_type='FD') print(opt_prob.solution(1)) # Instantiate Optimizer (CONMIN) & Solve Problem conmin = CONMIN() conmin.setOption('IPRINT', 0) conmin(opt_prob, sens_type='CS') print(opt_prob.solution(2)) # Instantiate Optimizer (COBYLA) & Solve Problem cobyla = COBYLA()
def variogram_fit(SVExp, Sb=(0.01,400), Rb=(2,20), Nb=(0,400), ab=(0,2), vb=(0,1000)): # Array with functions to be called from the Variograms library VarFunArr = [VariogramFit.SVExponential, VariogramFit.SVGaussian, VariogramFit.SVSpherical, VariogramFit.SVCubic, VariogramFit.SVPentaspherical, VariogramFit.SVSinehole, VariogramFit.SVPower, VariogramFit.SVMatern] # Names of functions for display only optFunNam = ['Exponential','Gaussian','Spherical','Cubic', 'Pentaspherical','Sinehole','Power','Matern'] # Boundaries semivariogram parameters #Sb = (0.01,400) # Limit for the sill #Rb = (2,20) # Limit for the range #Nb = (0,400) # Limit for the Nugget effect #ab = (0,2) # Limit for a in power variogram #vb = (0,1000) # Limit for Matern v parameters # Initial seed for variogram fit sr = random.uniform(Sb[0],Sb[1]) rr = random.uniform(Rb[0],Rb[1]) nr = random.uniform(Nb[0],Nb[1]) ar = random.uniform(ab[0],ab[1]) vr = random.uniform(vb[0],vb[1]) return sr, rr, nr, ar, vr Var = [] Res = [] Mdl = [] # Wrapper of minimisation function (RMSE) for semivariogram fitting def OptFun(x,*args): F, g, fail = VariogramFit.optFunMaster(x,SVExp,j,VarFunArr) if F == 9999: fail = 1 else: Var.append(x) Res.append(F) Mdl.append(j) return F, g, fail print 'Initialising Variogram fit' print '' # Optimisation starts to minimise differences between experimental and # theoretical semivariograms for j in xrange(0,len(VarFunArr)): print 'Variogram Fitting ' + optFunNam[j] print '' VarProb = Optimization('Variogram Fitting: ' + optFunNam[j], OptFun) VarProb.addObj('RMSE') VarProb.addVar('Sill','c',lower=Sb[0],upper=Sb[1],value=sr) VarProb.addVar('Range','c',lower=Rb[0],upper=Rb[1],value=rr) VarProb.addVar('Nugget','c',lower=Nb[0],upper=Nb[1],value=nr) VarProb.addVar('Exponent (a)','c',lower=ab[0],upper=ab[1],value=ar) VarProb.addVar('Rank (v)','c',lower=vb[0],upper=vb[1],value=vr) args = (SVExp, j, VarFunArr, Var, Res, Mdl) optmz = ALHSO() optmz(VarProb) print VarProb.solution(0) print '' # Get position of best semivariogram k = numpy.argmin(Res) xopt = Var[k] ModOpt = Mdl[k] del Var del Res del Mdl print 'Theoretical variogram fit - Done!' print '' return xopt, ModOpt, VarFunArr
def execute(self): """pyOpt execution. Note that pyOpt controls the execution, and the individual optimizers control the iteration.""" self.pyOpt_solution = None self.run_iteration() opt_prob = Optimization(self.title, self.objfunc, var_set={}, obj_set={}, con_set={}) # Add all parameters self.param_type = {} self.nparam = self.total_parameters() for name, param in self.get_parameters().iteritems(): # We need to identify Enums, Lists, Dicts metadata = param.get_metadata()[1] values = param.evaluate() # Assuming uniform enumerated, discrete, or continuous for now. val = values[0] choices = [] if 'values' in metadata and \ isinstance(metadata['values'], (list, tuple, array, set)): vartype = 'd' choices = metadata['values'] elif isinstance(val, bool): vartype = 'd' choices = [True, False] elif isinstance(val, (int, int32, int64)): vartype = 'i' elif isinstance(val, (float, float32, float64)): vartype = 'c' else: msg = 'Only continuous, discrete, or enumerated variables' \ ' are supported. %s is %s.' % (name, type(val)) self.raise_exception(msg, ValueError) self.param_type[name] = vartype names = param.names lower_bounds = param.get_low() upper_bounds = param.get_high() for i in range(param.size): opt_prob.addVar(names[i], vartype, lower=lower_bounds[i], upper=upper_bounds[i], value=values[i], choices=choices) # Add all objectives for name in self.get_objectives(): opt_prob.addObj(name) # Add all equality constraints for name, con in self.get_eq_constraints().items(): if con.size > 1: for i in range(con.size): opt_prob.addCon('%s [%s]' % (name, i), type='e') else: opt_prob.addCon(name, type='e') # Add all inequality constraints for name, con in self.get_ineq_constraints().items(): if con.size > 1: for i in range(con.size): opt_prob.addCon('%s [%s]' % (name, i), type='i') else: opt_prob.addCon(name, type='i') self.inputs = self.list_param_group_targets() self.objs = self.list_objective_targets() self.cons = self.list_constraint_targets() # Instantiate the requested optimizer optimizer = self.optimizer try: exec('from pyOpt import %s' % optimizer) except ImportError: msg = "Optimizer %s is not available in this installation." % \ optimizer self.raise_exception(msg, ImportError) optname = vars()[optimizer] opt = optname() # Set optimization options for option, value in self.options.iteritems(): opt.setOption(option, value) # Execute the optimization problem if self.pyopt_diff: # Use pyOpt's internal finite difference opt(opt_prob, sens_type='FD', sens_step=self.gradient_options.fd_step, store_hst=self.store_hst, hot_start=self.hot_start) else: # Use OpenMDAO's differentiator for the gradient opt(opt_prob, sens_type=self.gradfunc, store_hst=self.store_hst, hot_start=self.hot_start) # Print results if self.print_results: print opt_prob.solution(0) # Pull optimal parameters back into framework and re-run, so that # framework is left in the right final state dvals = [] for i in range(0, len(opt_prob.solution(0)._variables)): dvals.append(opt_prob.solution(0)._variables[i].value) # Integer parameters come back as floats, so we need to round them # and turn them into python integers before setting. if 'i' in self.param_type.values(): for j, param in enumerate(self.get_parameters().keys()): if self.param_type[param] == 'i': dvals[j] = int(round(dvals[j])) self.set_parameters(dvals) self.run_iteration() # Save the most recent solution. self.pyOpt_solution = opt_prob.solution(0)
def execute(self): """pyOpt execution. Note that pyOpt controls the execution, and the individual optimizers control the iteration.""" self.pyOpt_solution = None opt_prob = Optimization(self.title, self.objfunc, var_set={}, obj_set={}, con_set={}) # Add all parameters self.param_type = {} for name, param in self.get_parameters().iteritems(): # We need to identify Enums, Lists, Dicts metadata = param.get_metadata()[0][1] values = param.evaluate() # Assuming uniform enumerated, discrete, or continuous for now. val = values[0] choices = [] if "values" in metadata and isinstance(metadata["values"], (list, tuple, array, set)): vartype = "d" choices = metadata["values"] elif isinstance(val, bool): vartype = "d" choices = [True, False] elif isinstance(val, (int, int32, int64)): vartype = "i" elif isinstance(val, (float, float32, float64)): vartype = "c" else: msg = "Only continuous, discrete, or enumerated variables" " are supported. %s is %s." % ( name, type(val), ) self.raise_exception(msg, ValueError) self.param_type[name] = vartype names = param.names lower_bounds = param.get_low() upper_bounds = param.get_high() for i in range(param.size): opt_prob.addVar( names[i], vartype, lower=lower_bounds[i], upper=upper_bounds[i], value=values[i], choices=choices ) # Add all objectives for name in self.get_objectives(): opt_prob.addObj(name) # Add all equality constraints for name in self.get_eq_constraints(): opt_prob.addCon(name, type="e") # Add all inequality constraints for name in self.get_ineq_constraints(): opt_prob.addCon(name, type="i") # Instantiate the requested optimizer optimizer = self.optimizer try: exec ("from pyOpt import %s" % optimizer) except ImportError: msg = "Optimizer %s is not available in this installation." % optimizer self.raise_exception(msg, ImportError) optname = vars()[optimizer] opt = optname() # Set optimization options for option, value in self.options.iteritems(): opt.setOption(option, value) # Execute the optimization problem if self.pyopt_diff: # Use pyOpt's internal finite difference opt(opt_prob, sens_type="FD") else: # Use OpenMDAO's differentiator for the gradient opt(opt_prob, sens_type=self.gradfunc) # Print results if self.print_results: print opt_prob.solution(0) # Pull optimal parameters back into framework and re-run, so that # framework is left in the right final state dvals = [] for i in range(0, len(opt_prob.solution(0)._variables)): dvals.append(opt_prob.solution(0)._variables[i].value) # Integer parameters come back as floats, so we need to round them # and turn them into python integers before setting. if "i" in self.param_type.values(): for j, param in enumerate(self.get_parameters().keys()): if self.param_type[param] == "i": dvals[j] = int(round(dvals[j])) self.set_parameters(dvals) self.run_iteration() self.record_case() # Save the most recent solution. self.pyOpt_solution = opt_prob.solution(0)
# Instantiate Optimization Problem opt_prob = Optimization('TP37 Constrained Problem',objfunc) opt_prob.addVar('x1','c',lower=0.0,upper=42.0,value=10.0) opt_prob.addVar('x2','c',lower=0.0,upper=42.0,value=10.0) opt_prob.addVar('x3','c',lower=0.0,upper=42.0,value=10.0) opt_prob.addObj('f') opt_prob.addCon('g1','i') opt_prob.addCon('g2','i') print(opt_prob) # Instantiate Optimizer (PSQP) & Solve Problem psqp = PSQP() psqp.setOption('IPRINT',0) psqp(opt_prob,sens_type='FD') print(opt_prob.solution(0)) # Instantiate Optimizer (SLSQP) & Solve Problem slsqp = SLSQP() slsqp.setOption('IPRINT',-1) slsqp(opt_prob,sens_type='FD') print(opt_prob.solution(1)) # Instantiate Optimizer (CONMIN) & Solve Problem conmin = CONMIN() conmin.setOption('IPRINT',0) conmin(opt_prob,sens_type='CS') print(opt_prob.solution(2)) # Instantiate Optimizer (COBYLA) & Solve Problem cobyla = COBYLA()
fail = 0 return f,g,fail # ============================================================================= # # ============================================================================= # Instantiate Optimization Problem opt_prob = Optimization('TOY Constrained Problem',objfunc,use_groups=True) opt_prob.addVarGroup('a',2,'c',value=1.0, lower=0.0, upper=10) opt_prob.delVarGroup('a') opt_prob.addVar('x','c',value=1.0, lower=0.0, upper=10) opt_prob.addVarGroup('y',2,'c',value=1.0, lower=0.0, upper=10) opt_prob.delVarGroup('y') opt_prob.addVarGroup('z',1,'c',value=1.0, lower=0.0, upper=10) opt_prob.addVarGroup('b',5,'c',value=3.0, lower=0.0, upper=10) opt_prob.delVarGroup('b') opt_prob.addObj('f') opt_prob.addCon('g1','i') opt_prob.addCon('g2','i') print(opt_prob) # Instantiate Optimizer (SLSQP) & Solve Problem slsqp = SLSQP() slsqp(opt_prob) print(opt_prob.solution(0))
# ============================================================================= # # ============================================================================= # Instantiate Optimization Problem opt_prob = Optimization('Constrained Rosen-Suzuki',objfunc) opt_prob.addVar('x1','c',value=1.5) opt_prob.addVar('x2','c',value=1.5) opt_prob.addVar('x3','c',value=1.5) opt_prob.addVar('x4','c',value=1.5) opt_prob.addObj('f') opt_prob.addCon('g1','i') opt_prob.addCon('g2','i') opt_prob.addCon('g3','i') print(opt_prob) # Instantiate Optimizer (CONMIN) conmin = CONMIN() # Solve Problem with Optimizer Using Finite Differences conmin(opt_prob,sens_type='FD') print(opt_prob.solution(0)) # Solve Problem with Optimizer Using Complex Step conmin(opt_prob,sens_type='CS') print(opt_prob.solution(1)) # Solve Problem with Optimizer Using User-Provided Sensitivities conmin(opt_prob,sens_type=gradfunc) print(opt_prob.solution(2))
from pyOpt import Optimization, NSGA2 def objfunc(x): f = -x[0] * x[1] * x[2] h = -x[0] * x[2] g = [0.0] * 2 g[0] = x[0] + 2. * x[1] + 2. * x[2] - 72.0 g[1] = -x[0] - 2. * x[1] - 2. * x[2] fail = 0 return f, h, g, fail # Instantiate Optimization Problem opt_prob = Optimization('TP37 Constrained Problem', objfunc) opt_prob.addVar('x1', 'c', lower=0.0, upper=42.0, value=10.0) opt_prob.addVar('x2', 'c', lower=0.0, upper=42.0, value=10.0) opt_prob.addVar('x3', 'c', lower=0.0, upper=42.0, value=10.0) opt_prob.addObj('f') opt_prob.addObj('h') opt_prob.addCon('g1', 'i') opt_prob.addCon('g2', 'i') print(opt_prob) nsga2 = NSGA2() nsga2.setOption('PrintOut', 0) nsga2(opt_prob) print(opt_prob.solution(0))
def variogram_fit(SVExp, Sb=(0.01, 400), Rb=(2, 20), Nb=(0, 400), ab=(0, 2), vb=(0, 1000)): # Array with functions to be called from the Variograms library VarFunArr = [ VariogramFit.SVExponential, VariogramFit.SVGaussian, VariogramFit.SVSpherical, VariogramFit.SVCubic, VariogramFit.SVPentaspherical, VariogramFit.SVSinehole, VariogramFit.SVPower, VariogramFit.SVMatern ] # Names of functions for display only optFunNam = [ 'Exponential', 'Gaussian', 'Spherical', 'Cubic', 'Pentaspherical', 'Sinehole', 'Power', 'Matern' ] # Boundaries semivariogram parameters #Sb = (0.01,400) # Limit for the sill #Rb = (2,20) # Limit for the range #Nb = (0,400) # Limit for the Nugget effect #ab = (0,2) # Limit for a in power variogram #vb = (0,1000) # Limit for Matern v parameters # Initial seed for variogram fit sr = random.uniform(Sb[0], Sb[1]) rr = random.uniform(Rb[0], Rb[1]) nr = random.uniform(Nb[0], Nb[1]) ar = random.uniform(ab[0], ab[1]) vr = random.uniform(vb[0], vb[1]) return sr, rr, nr, ar, vr Var = [] Res = [] Mdl = [] # Wrapper of minimisation function (RMSE) for semivariogram fitting def OptFun(x, *args): F, g, fail = VariogramFit.optFunMaster(x, SVExp, j, VarFunArr) if F == 9999: fail = 1 else: Var.append(x) Res.append(F) Mdl.append(j) return F, g, fail print 'Initialising Variogram fit' print '' # Optimisation starts to minimise differences between experimental and # theoretical semivariograms for j in xrange(0, len(VarFunArr)): print 'Variogram Fitting ' + optFunNam[j] print '' VarProb = Optimization('Variogram Fitting: ' + optFunNam[j], OptFun) VarProb.addObj('RMSE') VarProb.addVar('Sill', 'c', lower=Sb[0], upper=Sb[1], value=sr) VarProb.addVar('Range', 'c', lower=Rb[0], upper=Rb[1], value=rr) VarProb.addVar('Nugget', 'c', lower=Nb[0], upper=Nb[1], value=nr) VarProb.addVar('Exponent (a)', 'c', lower=ab[0], upper=ab[1], value=ar) VarProb.addVar('Rank (v)', 'c', lower=vb[0], upper=vb[1], value=vr) args = (SVExp, j, VarFunArr, Var, Res, Mdl) optmz = ALHSO() optmz(VarProb) print VarProb.solution(0) print '' # Get position of best semivariogram k = numpy.argmin(Res) xopt = Var[k] ModOpt = Mdl[k] del Var del Res del Mdl print 'Theoretical variogram fit - Done!' print '' return xopt, ModOpt, VarFunArr
g[1] = 2 - x[1] fail = 0 return f,g,fail # ============================================================================= # # ============================================================================= # Instanciate Optimization Problem opt_prob = Optimization('TOY Constraint Problem',objfunc) opt_prob.addVar('x1','c',value=1.0,lower=0.0,upper=10.0) opt_prob.addVar('x2','c',value=1.0,lower=0.0,upper=10.0) opt_prob.addObj('f') opt_prob.addCon('g1','i') opt_prob.addCon('g2','i') print opt_prob # Instanciate Optimizer (ALPSO) & Solve Problem Storing History slsqp = SLSQP() slsqp.setOption('IFILE','slsqp1.out') slsqp(opt_prob,store_hst=True) print opt_prob.solution(0) # Solve Problem Using Stored History (Warm Start) slsqp.setOption('IFILE','slsqp2.out') slsqp(opt_prob, store_hst=True, hot_start='slsqp1') print opt_prob.solution(1)
# ============================================================================= # # ============================================================================= opt_prob = Optimization('Rosenbrock Unconstraint Problem',objfunc) opt_prob.addVar('x1','c',lower=-10.0,upper=10.0,value=-3.0) opt_prob.addVar('x2','c',lower=-10.0,upper=10.0,value=-4.0) opt_prob.addObj('f') print opt_prob # Instantiate Optimizer (PSQP) & Solve Problem psqp = PSQP() psqp.setOption('IPRINT',0) psqp(opt_prob,sens_type='FD') print opt_prob.solution(0) # Instantiate Optimizer (SLSQP) & Solve Problem slsqp = SLSQP() slsqp.setOption('IPRINT',-1) slsqp(opt_prob,sens_type='FD') print opt_prob.solution(1) # Instantiate Optimizer (CONMIN) & Solve Problem conmin = CONMIN() conmin.setOption('IPRINT',0) conmin(opt_prob,sens_type='CS') print opt_prob.solution(2) # Instantiate Optimizer (COBYLA) & Solve Problem cobyla = COBYLA()
# Instantiate Optimization Problem opt_prob = Optimization('TP37 Constrained Problem',objfunc) opt_prob.addVar('x1','c',lower=0.0,upper=42.0,value=10.0) opt_prob.addVar('x2','c',lower=0.0,upper=42.0,value=10.0) opt_prob.addVar('x3','c',lower=0.0,upper=42.0,value=10.0) opt_prob.addObj('f') opt_prob.addCon('g1','i') opt_prob.addCon('g2','i') # Solve Problem (No-Parallelization) nlpqlp_none = NLPQLP() nlpqlp_none.setOption('IPRINT',0) nlpqlp_none(opt_prob) if myrank == 0: print(opt_prob.solution(0)) #end # Solve Problem (Parallel Gradient) nlpqlp_pgc = NLPQLP() nlpqlp_pgc.setOption('IPRINT',0) nlpqlp_pgc(opt_prob,sens_mode='pgc') if myrank == 0: print(opt_prob.solution(1)) #end # Solve Problem (Parallel Line Search) nlpqlp_spm = NLPQLP(pll_type='SPM') nlpqlp_spm.setOption('IPRINT',0) nlpqlp_spm(opt_prob) print(opt_prob.solution(2))
fail = 0 return f, g, fail opt_prob = Optimization('Rosenbrock Unconstrained Problem', objfun) opt_prob.addVar('x1', 'c', lower=-10.0, upper=10.0, value=0.0) opt_prob.addVar('x2', 'c', lower=-10.0, upper=10.0, value=0.0) opt_prob.addObj('f') print opt_prob # Instantiate optimizer (PSQP) and solve problem psqp = PSQP() psqp.setOption('IPRINT', 0) psqp(opt_prob, sens_type='FD') print opt_prob.solution(0) # Instantiate optimizer (SLSQP) and solve problem slsqp = SLSQP() slsqp.setOption('IPRINT', -1) slsqp(opt_prob, sens_type='FD') print opt_prob.solution(1) # Instantiate optimizer (CONMIN) and solve problem conmin = CONMIN() conmin.setOption('IPRINT', 0) conmin(opt_prob, sens_type='CS') print opt_prob.solution(2) # Instantiate optimizer (COBYLA) and solve problem cobyla = COBYLA()
# Add functions opt_prob.addObj('weight') opt_prob.addCon('buckling-bar1', type='i') opt_prob.addCon('failure-bar1', type='i') opt_prob.addCon('failure-bar2', type='i') # Add variables opt_prob.addVar('area-1', type='c', value=1.0, lower=1.0e-3, upper=2.0) opt_prob.addVar('area-2', type='c', value=1.0, lower=1.0e-3, upper=2.0) opt_prob.addVar('height', type='c', value=4.0, lower=4.0, upper=10.0) # Optimization algorithm if args.algorithm == 'ALGENCAN': opt = ALGENCAN() opt.setOption('iprint', 2) opt.setOption('epsfeas', 1e-6) opt.setOption('epsopt', 1e-6) else: opt = SLSQP(pll_type='POA') opt.setOption('MAXIT', 999) opt(opt_prob, sens_type=optproblem.evalObjConGradient, disp_opts=True, store_hst=True, hot_start=False) if optproblem.comm.Get_rank() == 0: print opt_prob.solution(0) opt_prob.write2file(disp_sols=True)
class GP_SS(Algorithm): """ Implementation of Building Identification and Control using Gaussian Process State-Space models. A GP regression model per state is created and then the constrained optimization problem is solved using PyOpt's SLSQP solver.""" def __init__(self): """Initialize the GP_SS algorithm for a specific building. """ print("Initializing the GP_SS...") self.building = Building() self.X = [] self.Y = [] self.dynModels = [] # Number of Initial Exploration Simulation self.initExploration = 36 # Number of Samples for witching to Sparse Gaussian Processes self.num_inducing = 2000 # Safety constraint for exploration self.explorationConstraint = 0.03 # Needed to determine the best controller out of all iterations self.costs = [] self.constraints = [] self.policies = [] self.baseline = [] def configure(self, building): # Get building and optimization setup properties self.building = deepcopy(building) self.T, self.states, self.actions, self.disturbances, self.controlLim, self.actionLim, self.comfort, self.occ, self.nvars, self.ncons = self.building.getConfiguration( ) # Run initial random simulations and contstruct initial dataset for ii in range(0, self.initExploration): self.building.rand = 1 xa, cf, cc = self.building.simulate(self.building.policy) xx = xa[0:-1, ] yy = xa[1:, self.states] if (ii == 0): self.X = xx self.Y = yy else: self.X = np.concatenate((self.X, xx), axis=0) self.Y = np.concatenate((self.Y, yy), axis=0) # Last simulation is the baseline controller self.building.rand = 0 xa, cf, cc = self.building.simulate(self.building.policy) self.baseline.append(self.building.policy) self.baseline.append(np.sum(cf)) self.baseline.append(np.sum(cc)) xx = xa[0:-1, ] yy = xa[1:, self.states] self.X = np.concatenate((self.X, xx), axis=0) self.Y = np.concatenate((self.Y, yy), axis=0) def optimize(self, options): # Set max number of optimization iterations maxIter = 1 if (len(options) > 0): maxIter = options["MAXIT"] # Log costs and constraints for all internal iterations self.costs = np.zeros((maxIter + 1, 1)) self.constraints = np.zeros((maxIter + 1, self.ncons)) self.policies = np.zeros((maxIter + 1, self.nvars)) # GP_SS process initPolicy = self.building.policy.copy() for ii in range(maxIter): # Train GP state-space models kernel = GPy.kern.Matern52(self.X.shape[1], ARD=False) for jj in range(0, len(self.states)): if (self.X.shape[0] > self.num_inducing): print("Using Sparse GP Model...") dynModel = GPy.models.SparseGPRegression( self.X, self.Y[:, jj].reshape(self.Y.shape[0], 1), kernel, num_inducing=self.num_inducing) self.dynModels.append(dynModel.copy()) else: print("Using Full GP Model...") dynModel = GPy.models.GPRegression( self.X, self.Y[:, jj].reshape(self.Y.shape[0], 1), kernel) dynModel.optimize_restarts(num_restarts=2) dynModel.optimize('bfgs', messages=True, max_iters=5000) self.dynModels.append(dynModel.copy()) print(self.dynModels[jj]) self.checkModelAccuracy(dynModel, self.X, self.Y[:, jj]) # Define Box Constraints (min/max values) for the control parameters boxConstraints = [] for jj in range(self.nvars): boxConstraints.append(self.controlLim) # Link to the python function calculating the cost and the constraints. Note that # this is not the actual simulation, but the propagate function self.opt_prob = Optimization('GPSS_SLSQP Constrained Problem', self.propagate) # Setupt Box Constrains in pyOpt for jj in range(self.nvars): self.opt_prob.addVar('x' + str(jj + 1), 'c', lower=boxConstraints[jj][0], upper=boxConstraints[jj][1], value=self.building.policy[0, jj]) # Setupt Cost Function in pyOpt self.opt_prob.addObj('f') # Setupt Inequality Constraints in pyOpt for jj in range(self.ncons + 1): self.opt_prob.addCon('g' + str(jj + 1), 'i') # Print the Optimization setup print("----------------------------------------") print("----------------------------------------") print("GPSS_SLSQP Optimization setup:") print(self.opt_prob) optionsSLSQP = {'ACC': 1.0e-20, 'MAXIT': 10000, 'IPRINT': 1} # Set SLSQP as the optimizer self.opt = SLSQP() # Set optimization options for jj in range(len(optionsSLSQP)): self.opt.setOption(optionsSLSQP.keys()[jj], optionsSLSQP.values()[jj]) # Print the Optimizer Options print("----------------------------------------") print("----------------------------------------") print("SLSQP Optimizer options:") print(self.opt.options) # Get optimized controller self.opt(self.opt_prob, sens_step=1e-6) print(self.opt_prob.solution(0)) a = self.opt_prob.solution(0) for jj in range(self.building.policy.shape[1]): self.building.policy[0, jj] = a.getVar(jj).value # Evaluate the optimized controller in the simulation model xa, cf, cc = self.building.simulate(self.building.policy) print("COST: = =========== " + str(np.sum(cf))) print("CONSTRAINT: = =========== " + str(np.sum(cc))) xx = xa[0:-1, ] yy = xa[1:, self.states] if (ii == 0): self.X = xx self.Y = yy else: self.X = np.concatenate((self.X, xx), axis=0) self.Y = np.concatenate((self.Y, yy), axis=0) self.costs[ii, 0] = np.sum(cf) for jj in range(self.ncons): self.constraints[ii, jj] = np.sum(cc[:, jj]) self.policies[ii, :] = self.building.policy.copy() self.building.policy = initPolicy.copy() self.policies[ii + 1, :] = self.baseline[0].copy() self.costs[ii + 1, 0] = self.baseline[1] self.constraints[ii + 1, 0] = self.baseline[2] policyIndex = self.selectBestController(self.costs, self.constraints) self.building.policy = self.policies[policyIndex, :].copy() return self.building.policy def selectBestController(self, costs, constraints): """A function that selects the best controller out of a set of controllers, based on their performance on the cost function and the constraints. Args: costs (numpy array): The resulting cost of each controller, as evaluated on the simulation model constraints (numpy array): The resulting constraints of each controller, as evaluated on the simulation model Returns: policyIndex (float): the index of the best controller """ wCost = 1 wConstraints = 10000000 p = np.zeros((costs.shape[0], 1)) for ii in range(costs.shape[0]): p[ii, 0] = p[ii, 0] + wCost * costs[ii, 0] for jj in range(constraints.shape[1]): p[ii, 0] = p[ii, 0] + wConstraints * constraints[ii, jj] policyIndex = np.argmin(p) return policyIndex def propagate(self, policy): """A function that uses the GP state-space models identified from the data to perform rollouts based on a given controller. Args: policy (numpy array): the controller to be used for the rollout Returns: f (float): the cost function value g (list): the vales of all constraints fail (0/1): indicates if the function finished successfully """ # Initial state xx = np.zeros((self.building.T + 1, len(self.building.states) + self.building.w.shape[1])) uu = np.zeros((self.building.T + 1, len(self.building.actions))) cc = np.zeros((self.building.T + 1, 1)) cf = np.zeros((self.building.T + 1, 1)) var = np.zeros((self.building.T, len(self.building.states))) xx[0, ] = self.X[0, 0:2] # [17, w[0,]] uu[0, ] = self.building.controller(policy, xx[0, ], 0) cc[0, ] = self.building.comfortConstraints(xx[0, self.building.states], 0) cf[0, ] = self.building.costFunction(uu[0, ], 0) # state propagation using the provided controller for ii in range(1, self.building.T + 1): newX = np.hstack([xx[ii - 1, ], uu[ii - 1]]).reshape(1, xx.shape[1] + uu.shape[1]) for jj in range(0, len(self.building.states)): results = self.dynModels[jj].predict(newX) xx[ii, jj] = results[0] var[ii - 1, jj] = results[1] xx[ii, 1] = self.building.w[ii, ] uu[ii, ] = self.building.controller(policy, xx[ii, ], ii) cc[ii, ] = self.building.comfortConstraints( xx[ii, self.building.states], ii) cf[ii, ] = self.building.costFunction(uu[ii, ], ii) f = np.sum(cf) g = [] g.append(np.mean(var) - self.explorationConstraint) # Exploration constraint g.append(np.sum(cc)) fail = 0 return f, g, fail def checkModelAccuracy(self, dynModel, xtest, ytest): """A function that evaluates the accuracy of the GP state-space model. Args: dynModel (GPy object): The GP model xtest (numpy array): The features of the regression ytest (numpy array): The targets of the regression """ results = dynModel.predict(xtest) ypred = results[0] # sGP = results[1] rsqTrain, maeTrain, rsqAdjTrain = self.evaluateGoodnessOfFit( xtest, ytest, ypred) print("Rsq train Gaussian Processes Regression = " + str(rsqTrain)) print("Rsq Adjusted train Gaussian Processes Regression = " + str(rsqAdjTrain)) print("MAE train Gaussian Processes Regression = " + str(maeTrain)) def evaluateGoodnessOfFit(self, x, y, ypred): """A function that evaluates the goodness of fit, under different measures. Args: x (numpy array): The features of the regression y (numpy array): The targets of the regression ypred (numpy array): The predictions of the regression model Returns: Rsquared (float): R-squared mae (float): Mean Absolute Error rsqAdj (float): The Adjusted R-square """ print(y.shape[0]) print(x.shape[1]) y_hat = np.mean(y) SStot = np.sum(np.power(y - y_hat, 2)) SSres = np.sum(np.power(y - ypred.flatten(), 2)) if (SStot == 0): rsq = 1 else: rsq = 1 - SSres / SStot mae = np.sum(np.abs(y - ypred.flatten())) / ypred.shape[0] rsqAdj = 1 - (1 - rsq) * (y.shape[0] - 1) / (y.shape[0] - x.shape[1] - 1) return rsq, mae, rsqAdj def wrapSimulation(self, policy): """A function that runs a building simulation and wraps the results in the format required by PyOpt library. Args: policy (numpy array): the controller to be used for the simulation Returns: f (float): the cost function value g (list): the vales of all constraints fail (0/1): indicates if the function finished successfully """ # Cost and Constraints f = 0 g = [] fail = 0 # Run building simulation x, cost, constraints = self.building.simulate(policy) f = np.sum(cost) g.append(np.sum(constraints)) # print(f) # print(g[0]) return f, g, fail