Пример #1
0
    def _reinitialize(self, solver=None, optOptions=None):
        try:
            import pyoptsparse
        except ImportError:
            err_msg = (
                "It appears you do not have pyOptSparse installed. " +
                "Please refer to https://pyoptsparse.readthedocs.io/ for " +
                "guidance on how to properly install the module.")
            self.logger.error(err_msg, stack_info=True)
            raise ImportError(err_msg)

        self.optProb = pyoptsparse.Optimization(self.model,
                                                self.objective_func)

        self.optProb = self.model.add_var_group(self.optProb)
        self.optProb = self.model.add_con_group(self.optProb)
        self.optProb.addObj("obj")

        if solver is not None:
            self.solver = solver
            print("Setting up optimization with user's choice of solver: ",
                  self.solver)
        else:
            self.solver = "SLSQP"
            print("Setting up optimization with default solver: SLSQP.")
        if optOptions is not None:
            self.optOptions = optOptions
        else:
            self.optOptions = {"Major feasibility tolerance": 1e-1}

        exec("self.opt = pyoptsparse." + self.solver +
             "(optOptions=self.optOptions)")
    def init_problem(self, n):
        print(f"Solving Brachistochrone problem with n = {n}...")

        self.n = n
        self.x_arr = np.linspace(0, 1, n)  # fixed
        y_inner = np.linspace(1 - 1 / n, 1 / n,
                              n - 2)  # initial guess of (inner) values

        # Optimal/final y points
        self.y_arr = np.zeros(n)
        self.y_arr[0] = 1.0

        # Optimization problem
        opt_prob: pyop.Optimization = pyop.Optimization(
            'brachistochrone', self.objfunc)

        # Design variables
        opt_prob.addVarGroup('y', nVars=n-2, type='c', value=y_inner, \
                                  lower=None, upper=None)

        # Assign the key value for the objective function
        opt_prob.addObj('obj')

        # Optimizer
        optimizer = pyop.SNOPT()
        # optimizer.setOption('iPrint',0)
        path = '/home/seth/school/optimization/output/'
        # optimizer.setOption('Print file', path+f'SNOPT_print-{n}.out')
        # optimizer.setOption('Summary file', path+f'SNOPT_summary-{n}.out')

        return opt_prob, optimizer
    def init_problem(self):
        # Optimization problem
        self.opt_prob: pyop.Optimization = pyop.Optimization(
            'trusty', self.objfunc)
        # Design variables
        self.opt_prob.addVarGroup('areas', nVars=10, type='c', value=self.areas, \
                                  lower=0.1, upper=None)

        # Constraints
        # yield_compression, yield_tension, area_min
        stress_yield = np.array([25e3] * 10)
        stress_yield[8] = 75e3
        self.opt_prob.addConGroup('stress_arr',
                                  nCon=10,
                                  lower=-stress_yield,
                                  upper=stress_yield)

        # Assign the key value for the objective function
        self.opt_prob.addObj('mass')

        self.optimizer = pyop.SNOPT()
        self.optimizer.setOption('iPrint', 0)
        path = '/home/seth/school/optimization/output/'
        self.optimizer.setOption('Print file', path + f'SNOPT_print.out')
        self.optimizer.setOption('Summary file', path + f'SNOPT_summary.out')
def optimize_farmcost(*args):
    y0 = np.array([9, 10])

    funcs, _ = obj_farmcost({"y": y0})
    print(f'initial COE: {funcs["coe"]}')
    # starting point and bounds

    # objective
    opt_prob: pyop.Optimization = pyop.Optimization('coe', obj_farmcost)

    # linear constraint
    # the constraint y3 > y2 can be formulated as a linear constraint.
    opt_prob.addVarGroup('y', nVars=2, value=y0, lower=0, upper=10)
    opt_prob.addConGroup('y3y2', nCon=1, lower=1e-5)

    opt_prob.addObj('coe')

    optimizer = pyop.SNOPT()

    # deterministic optimization
    sol: pyop.pyOpt_solution.Solution = optimizer(opt_prob, sens='FD')

    print(f'{sol.fStar.item() = }')
    print(f'{sol.xStar["y"] = }')

    obj_farmcost(sol.xStar, plotit=False)
Пример #5
0
    #Equality Constraints
    funcs['eq_con'] = equalityConstraints(t0, tf, p)

    #Inequality Constraints
    funcs['ineq_con'] = inequalityConstraints(t_span, p)

    return funcs, False


if __name__ == "__main__":
    '''----------- Setting up the problem -----------'''

    p = np.ones(12) * 1e-4

    optProb = pyoptsparse.Optimization('Differential_Flatness', objective)
    optProb.addVarGroup('xvars', 12, 'c', lower=None, upper=None, value=p)
    eq_bnd = [0.0, 0.0, 0.0, 2.0, 10.0, 0.0, 0.0, 1.0]
    optProb.addConGroup('eq_con', 8, lower=eq_bnd, upper=eq_bnd)
    if use_gamma:
        optProb.addConGroup(
            'ineq_con', 400, lower=0.0, upper=None
        )  # I can get an answer but the constraints are violated and it runs into numerical difficulties
    else:
        optProb.addConGroup('ineq_con', 200, lower=0.0, upper=None)
    optProb.addObj('obj')

    opt = pyoptsparse.SNOPT()
    sol = opt(optProb, sens='CS', storeHistory='constrained.txt')

    data = {
Пример #6
0
import pyoptsparse


def objfunc(xdict):
    x = xdict['xvars']
    funcs = {}
    funcs['obj'] = -x[0] * x[1] * x[2]
    conval = [0] * 2
    conval[0] = x[0] + 2. * x[1] + 2. * x[2] - 72.0
    conval[1] = -x[0] - 2. * x[1] - 2. * x[2]
    funcs['con'] = conval
    fail = False

    return funcs, fail


optProb = pyoptsparse.Optimization('TP037', objfunc)
optProb.addVarGroup('xvars',
                    3,
                    'c',
                    lower=[0, 0, 0],
                    upper=[42, 42, 42],
                    value=10)
optProb.addConGroup('con', 2, lower=None, upper=0.0)
optProb.addObj('obj')
print(optProb)
opt = pyoptsparse.SNOPT()
sol = opt(optProb, sens='FD')
print(sol)
Пример #7
0
    def optimize_pyoptsparse(self, solver, sens, options, callback=None):
        """Solve the problem with pyoptsparse."""
        def objfunc_builder():
            """Builds an objective function with a name chosen at run-time."""
            def objfunc(xdictInside):
                """Give the objective and constraints in pyoptsparse format."""
                funcs = dict()
                x = xdictInside['vars']  # extract the variables as a 1D array
                funcs[self.objective_name] = self.objective(x)

                # add the constraints to the funcs dictionary, one key per group
                n_nonlin_constr_per_group = self.n_nonlin_constr_per_group[1:]
                for ind, numConstr in enumerate(n_nonlin_constr_per_group):
                    if ind in self.nonlin_constraint_names:
                        key = self.nonlin_constraint_names[ind]
                    else:
                        key = 'constraint_group{0:d}'.format(ind)
                    funcs[key] = np.array(self.nonlin_constr[ind](x), ndmin=1)
                obj_fail = self.obj_failure(x)
                constr_fail_list = [f(x) for f in self.nonlin_constr_fail]
                fail = any([constr_fail_list, obj_fail])
                return funcs, fail

            objfunc.__name__ = self.objective_name
            return objfunc

        if sens in (None, 'provided'):

            def sens(xdict, funcs):
                """Specify objective/constraint gradients in pyoptparse format."""
                func_sens = dict()
                x = xdict['vars']  # extract the design variables as a 1D array
                func_sens[self.objective_name,
                          'vars'] = np.array(self.gradient(x), ndmin=1)

                # add the constraints to the funcs dictionary, one key per group
                n_nonlin_constr_per_group = self.n_nonlin_constr_per_group[1:]
                for ind, numConstr in enumerate(n_nonlin_constr_per_group):
                    if ind in self.nonlin_constraint_names:
                        key = self.nonlin_constraint_names[ind]
                    else:
                        key = 'constraint_group{0:d}'.format(ind)
                    func_sens[key, 'vars'] = np.array(self.nonlin_jac[ind](x),
                                                      ndmin=2)
                obj_grad_fail = self.grad_failure(x)
                constr_jac_fail_list = [f(x) for f in self.nonlin_jac_fail]
                fail = any([constr_jac_fail_list, obj_grad_fail])
                return func_sens, fail

        # Warn the user if they tried to use a callback function
        if callback is not None:
            raise ValueError('pyoptsparse does not support callbacks.')

        # Create an Optimization instance and add the objective function
        objfunc = objfunc_builder()
        opt_prob = pyoptsparse.Optimization(self.name, objfunc)
        opt_prob.addObj(self.objective_name)

        # Add the design variables
        opt_prob.addVarGroup('vars',
                             self.nvar,
                             lower=self.var_bounds[:, 0],
                             upper=self.var_bounds[:, 1],
                             value=self.var_init)

        ## Add the constraints
        # Add the nonlinear constraints
        n_nonlin_constr_per_group = self.n_nonlin_constr_per_group[1:]
        for ind, numConstr in enumerate(n_nonlin_constr_per_group):
            if ind in self.nonlin_constraint_names:
                constraint_name = self.nonlin_constraint_names[ind]
            else:
                constraint_name = 'constraint_group{0:d}'.format(ind)
            opt_prob.addConGroup(constraint_name,
                                 numConstr,
                                 lower=self.nonlin_bounds_per_group[ind][:, 0],
                                 upper=self.nonlin_bounds_per_group[ind][:, 1])

        # Add the linear constraints
        opt_prob.addConGroup('Linear Constraints',
                             self.n_lin_constr,
                             lower=self.lin_bounds[:, 0],
                             upper=self.lin_bounds[:, 1],
                             linear=True,
                             wrt='vars',
                             jac={'vars': self.lin_mat})

        # Solve the optimization problem
        print(opt_prob)
        opt = eval('pyoptsparse.' + solver.lstrip('pyoptsparse:') + '()')
        sol = opt(opt_prob, sens=sens)
        print(sol)

        # Extract the optimized parameter vector and objective value
        xStar = [None] * self.nvar
        for i in range(self.nvar):
            xStar[i] = sol.variables['vars'][i].value
        fStar = sol.objectives[self.objective_name].value

        return (xStar, fStar)
Пример #8
0

def objfunc(xdict):
    x = xdict['xvars']
    funcs = {}
    funcs['obj'] = -x[0] * x[1] * x[2]
    conval = [0] * 2
    conval[0] = x[0] + 2. * x[1] + 2. * x[2] - 72.0
    conval[1] = -x[0] - 2. * x[1] - 2. * x[2]
    funcs['con'] = conval
    fail = False

    return funcs, fail


optProb: pyop.Optimization = pyop.Optimization('TP037', objfunc)

# Design variables - can be created individually or as a group
optProb.addVarGroup('xvars',
                    nVars=3,
                    type='c',
                    lower=[0, 0, 0],
                    upper=[42, 42, 42],
                    value=10)

# Constraints - also individually or group
optProb.addConGroup('con', nCon=2, lower=None, upper=0.0)

optProb.addObj('obj')
print(optProb)
Пример #9
0
            min      mu_CD(twist_cp, rv) + 2 * sigma_CD(twist_cp, rv)
         twist_cp

        subject to   mu_CL = 0.5
    """

    uq_systemsize = 2
    ndv = 5
    UQObj = UQOASExample1Opt(uq_systemsize)
    collocation_obj = StochasticCollocation(5, "Normal")
    collocation_con = collocation_obj
    collocation_grad_obj = StochasticCollocation(5,
                                                 "Normal",
                                                 QoI_dimensions=ndv)
    collocation_grad_con = collocation_grad_obj
    optProb = pyoptsparse.Optimization('UQ_OASExample1', objfunc)
    optProb.addVarGroup('xvars', ndv, 'c', lower=-10., upper=15.)
    optProb.addConGroup('con', 1, lower=0.5, upper=0.5)
    optProb.addObj('obj')
    opt = pyoptsparse.SNOPT(optOptions={'Major feasibility tolerance': 1e-10})
    sol = opt(optProb, sens=sens)
    # sol = opt(optProb, sens='FD')

    # Error Calculation
    full_integration_val = 0.03428059998452251
    reduced_fval = sol.fStar
    err = abs(full_integration_val - reduced_fval)
    rel_err = abs((full_integration_val - reduced_fval) / full_integration_val)
    print sol
    print "integration val = ", sol.fStar
    print "error val = ", err
Пример #10
0
        start_solar = 1.0
        start_battery_mwh = 100.0
        start_battery_mw = 100.0

        x = {}
        x["electrolyzer_size_mw"] = start_electrolyzer
        x["wind_capacity_mw"] = start_wind
        x["solar_capacity_mw"] = start_solar
        x["battery_storage_mwh"] = start_battery_mwh
        x["battery_storage_mw"] = start_battery_mw

        funcs, _ = objective_function(x)
        start_lcoh = funcs["h_lcoe"] * obj_scale
        print("start_lcoh: ", start_lcoh)

        optProb = pyoptsparse.Optimization("optimize_sizing",
                                           objective_function)
        optProb.addVar("electrolyzer_size_mw",
                       type="c",
                       lower=1,
                       upper=250,
                       value=start_electrolyzer)
        optProb.addVar("wind_capacity_mw",
                       type="c",
                       lower=1,
                       upper=1000,
                       value=start_wind)
        optProb.addVar("solar_capacity_mw",
                       type="c",
                       lower=1,
                       upper=500,
                       value=start_solar)
Пример #11
0
    def init_problem(self):
        px = np.zeros(6) + 1e-4
        py = np.zeros(6) + 1e-4

        self.n = 100
        self.t = np.linspace(0, 15, self.n)
        self.tpos_exp = self.t**np.arange(6).reshape(
            6, 1)  # exponents for trajectory equation
        self.tvel_exp = self.t**np.array([0, 0, 1, 2, 3, 4]).reshape(
            6, 1)  # exponents for veloc terms
        self.tacc_exp = self.t**np.array([0, 0, 0, 1, 2, 3]).reshape(
            6, 1)  # exponents for accel terms
        self.tjerk_exp = self.t**np.array([0, 0, 0, 0, 1, 2]).reshape(
            6, 1)  # exponents for each jerk term

        self.cvel = np.arange(
            6, dtype=np.float64)  # Constant mulipliers for each velocity term
        self.cacc = np.array(
            [0, 0, 2, 6, 12, 20],
            dtype=np.float64)  # Constant mulipliers for each acceleration term
        self.cjerk = np.array(
            [0, 0, 0, 6, 24, 60],
            dtype=np.float64)  # Constant multipliers for each jerk term

        # Optimization problem
        opt_prob: pyop.Optimization = pyop.Optimization(
            'differential_flat', self.objfunc)

        # Design variables
        opt_prob.addVarGroup('px',
                             nVars=6,
                             type='c',
                             value=px,
                             lower=None,
                             upper=None)
        opt_prob.addVarGroup('py',
                             nVars=6,
                             type='c',
                             value=py,
                             lower=None,
                             upper=None)

        x0, y0, xf, yf = [0., 0., 10., 0.]
        vx0, vy0, vxf, vyf = [0., 2., 0., 1.]

        self.L = 1.5  # length of car
        gam_max = np.pi / 4
        self.vmax_square = 10**2  # vmax = 10 m/s
        self.amax_square = 2**2  # amax = 2 m/s**2

        #### CONSTRAINTS ####
        # start and finish constraints
        opt_prob.addConGroup('initial pos',
                             nCon=2,
                             lower=[x0, y0],
                             upper=[x0, y0])
        opt_prob.addConGroup('initial vel',
                             nCon=2,
                             lower=[vx0, vy0],
                             upper=[vx0, vy0])
        opt_prob.addConGroup('final pos',
                             nCon=2,
                             lower=[xf, yf],
                             upper=[xf, yf])
        opt_prob.addConGroup('final vel',
                             nCon=2,
                             lower=[vxf, vyf],
                             upper=[vxf, vyf])

        # constraints over entire trajectory
        opt_prob.addConGroup('v', nCon=self.n, lower=0, upper=self.vmax_square)
        opt_prob.addConGroup('a', nCon=self.n, lower=0, upper=self.amax_square)
        # opt_prob.addConGroup('gam_max', nCon=self.n, lower=-gam_max, upper=gam_max)
        opt_prob.addConGroup('gam_plus', nCon=self.n, lower=0, upper=None)
        opt_prob.addConGroup('gam_minus', nCon=self.n, lower=0, upper=None)

        # Assign the key value for the objective function
        opt_prob.addObj('obj-min-jerk')

        # Optimizer
        optimizer = pyop.SNOPT()
        # optimizer.setOption('iPrint',0)
        # optimizer.setOption('iSumm', 0)
        # path = '/home/seth/school/optimization/output/'
        # optimizer.setOption('Print file', path+f'SNOPT_print-{n}.out')
        # optimizer.setOption('Summary file', path+f'SNOPT_summary-{n}.out')

        return opt_prob, optimizer
Пример #12
0
        # Get some information on the total number of constraints
        n_thickness_intersects = UQObj.QoI.p[
            'oas_scaneagle.AS_point_0.wing_perf.thickness_intersects'].size
        n_CM = 3
        n_constraints = 1 + n_thickness_intersects + 1 + n_CM + 3

        # Create the Monte Carlo object based on the dominant directions
        nsample = 1000
        mc_obj = MonteCarlo(nsample,
                            UQObj.jdist,
                            UQObj.QoI_dict,
                            include_derivs=True)
        mc_obj.getSamples(UQObj.jdist, include_derivs=True)

        optProb = pyoptsparse.Optimization('UQ_OASScanEagle', objfunc_uq)
        n_twist_cp = UQObj.QoI.input_dict['n_twist_cp']
        n_thickness_cp = UQObj.QoI.input_dict['n_thickness_cp']
        optProb.addVarGroup('twist_cp',
                            n_twist_cp,
                            'c',
                            lower=-5.,
                            upper=10,
                            value=init_twist_cp)
        optProb.addVarGroup('thickness_cp',
                            n_thickness_cp,
                            'c',
                            lower=0.001,
                            upper=0.01,
                            scale=1.e3,
                            value=init_thickness_cp)
Пример #13
0
    def __init__(self):
        # Plotting histories
        p0 = np.zeros(6) + 1e-4

        self.n = 100
        self.t = np.linspace(0, 15, self.n)
        self.tpos_exp = self.t**np.arange(6).reshape(
            6, 1)  # exponents for trajectory equation
        self.tvel_exp = self.t**np.array([0, 0, 1, 2, 3, 4]).reshape(
            6, 1)  # exponents for veloc terms
        self.tacc_exp = self.t**np.array([0, 0, 0, 1, 2, 3]).reshape(
            6, 1)  # exponents for accel terms
        self.tjerk_exp = self.t**np.array([0, 0, 0, 0, 1, 2]).reshape(
            6, 1)  # exponents for each jerk term

        self.cvel = np.arange(
            6, dtype=np.float64)  # Constant mulipliers for each velocity term
        self.cacc = np.array(
            [0, 0, 2, 6, 12, 20],
            dtype=np.float64)  # Constant mulipliers for each acceleration term
        self.cjerk = np.array(
            [0, 0, 0, 6, 24, 60],
            dtype=np.float64)  # Constant multipliers for each jerk term

        # Optimization problem
        opt_prob: pyop.Optimization = pyop.Optimization(
            'differential_flat_quad', self.objfunc)

        # Design variables
        opt_prob.addVarGroup('px',
                             nVars=6,
                             type='c',
                             value=p0,
                             lower=None,
                             upper=None)
        opt_prob.addVarGroup('py',
                             nVars=6,
                             type='c',
                             value=p0,
                             lower=None,
                             upper=None)
        opt_prob.addVarGroup('pz',
                             nVars=6,
                             type='c',
                             value=p0,
                             lower=None,
                             upper=None)
        opt_prob.addVarGroup('ps',
                             nVars=6,
                             type='c',
                             value=p0,
                             lower=None,
                             upper=None)

        # ENU
        #      [ x,   y,   z, psi ]
        pos0 = np.array([0., 0., 0., 0.])
        posf = np.array([0., 10., 10., 0.])
        vel0 = np.array([0., 2., 2., 0.])
        velf = np.array([0., 2., 0., 0.])
        # x0, y0, z0, psi0 = [0.,  0.,  0., 0.]
        # xf, yf, zf, psif = [0., 10., 10., 0.]
        # vx0, vy0, vz0, w0 = [0., 2., 2., 0.]
        # vxf, vyf, vzf, wf = [0., 2., 0., 0.]

        self.L = 1.5  # length of car
        gam_max = np.pi / 4
        self.vmax_square = 10**2  # vmax = 10 m/s
        self.amax_square = 2**2  # amax = 2 m/s**2

        #### CONSTRAINTS ####
        # start and finish constraints
        opt_prob.addConGroup('initial pos', nCon=4, lower=pos0, upper=pos0)
        opt_prob.addConGroup('initial vel', nCon=4, lower=vel0, upper=vel0)
        opt_prob.addConGroup('final pos', nCon=4, lower=posf, upper=posf)
        opt_prob.addConGroup('final vel', nCon=4, lower=velf, upper=velf)

        # constraints over entire trajectory
        # opt_prob.addConGroup('v', nCon=self.n, lower=0, upper=self.vmax_square)
        # opt_prob.addConGroup('a', nCon=self.n, lower=0, upper=self.amax_square)
        # opt_prob.addConGroup('gam_max', nCon=self.n, lower=-gam_max, upper=gam_max)
        # opt_prob.addConGroup('gam_plus', nCon=self.n, lower=0, upper=None)
        # opt_prob.addConGroup('gam_minus', nCon=self.n, lower=0, upper=None)

        # Assign the key value for the objective function
        opt_prob.addObj('obj-min-jerk')

        # Optimizer
        optimizer = pyop.SNOPT()
        # optimizer.setOption('iPrint',0)
        # optimizer.setOption('iSumm', 0)
        path = '/home/seth/school/optimization/output/'
        optimizer.setOption('Print file', path + f'SNOPT-hw5.out')
        optimizer.setOption('Summary file', path + f'SNOPT-hw5-summary.out')

        self.opt_prob: pyop.Optimization = opt_prob
        self.optimizer: pyop.SNOPT = optimizer
    funcs = {}
    funcs["obj"] = AEP_sum / 1e9

    fail = False
    return funcs, fail


solutions = []

for i in range(len(wd)):
    wd_itr = wd[i]
    ws_itr = ws[i]
    freq_itr = freq[i]

    # Setup the optimization problem
    optProb = pyoptsparse.Optimization("yaw_opt_wd_" + str(wd_itr),
                                       objective_function)

    # Add the design variables to the optimization problem
    optProb.addVarGroup("yaw", nturbs, "c", lower=0.0, upper=20.0, value=2.0)

    # Add the objective to the optimization problem
    optProb.addObj("obj")

    # Setup the optimization solver
    # Note: pyOptSparse has other solvers available; some may require additional
    #   licenses/installation. See https://github.com/mdolab/pyoptsparse for
    #   more information. When ready, they can be invoked by changing 'SLSQP'
    #   to the solver name, for example: 'opt = pyoptsparse.SNOPT(fi=fi)'.
    opt = pyoptsparse.SLSQP()

    # Run the optimization with finite-differencing
Пример #15
0

#### Callback function
def callbackF2(Xi):
    temp = 1
    global Nfeval, all_functions, max_const_vio
    print(solve(Xi))
    all_functions.append(solve(Xi))
    max = np.max(np.abs(constraintAll(Xi)))

    max_const_vio.append(max)


#### Solve
# Optimization Object
optProb = pyopt.Optimization('Truss Problem', objfunc)

# Design Variables
optProb.addVarGroup('xvars',
                    10,
                    'c',
                    lower=[0.1] * 10,
                    upper=None,
                    value=[0.1] * 10)

lower = [-25e3] * 10
lower[8] = -75e3
upper = [25e3] * 10
upper[8] = 75e3

# set_trace()
Пример #16
0

def objective_function(varDict, **kwargs):
    # Parse the variable dictionary
    yaw = varDict["yaw"]

    # Compute the objective function
    funcs = {}
    funcs["obj"] = -1 * fi.get_farm_power_for_yaw_angle(yaw) / 1e5

    fail = False
    return funcs, fail


# Setup the optimization problem
optProb = pyoptsparse.Optimization("yaw_opt", objective_function)

# Add the design variables to the optimization problem
optProb.addVarGroup("yaw", 4, "c", lower=0, upper=20, value=2.0)

# Add the objective to the optimization problem
optProb.addObj("obj")

# Setup the optimization solver
# Note: pyOptSparse has other solvers available; some may require additional
#   licenses/installation. See https://github.com/mdolab/pyoptsparse for more
#   information. When ready, they can be invoked by changing 'SLSQP' to the
#   solver name, for example: 'opt = pyoptsparse.SNOPT(fi=fi)'.
opt = pyoptsparse.SLSQP(fi=fi)

# Run the optimization with finite-differencing
Пример #17
0
def Pyoptsparse_Solve(problem,
                      solver='SNOPT',
                      FD='single',
                      sense_step=1.0E-6,
                      nonderivative_line_search=False):
    """ This converts your SUAVE Nexus problem into a PyOptsparse optimization problem and solves it.
        Pyoptsparse has many algorithms, they can be switched out by using the solver input. 

        Assumptions:
        None

        Source:
        N/A

        Inputs:
        problem                   [nexus()]
        solver                    [str]
        FD (parallel or single)   [str]
        sense_step                [float]
        nonderivative_line_search [bool]

        Outputs:
        outputs                   [list]

        Properties Used:
        None
    """

    # Have the optimizer call the wrapper
    mywrap = lambda x: PyOpt_Problem(problem, x)

    inp = problem.optimization_problem.inputs
    obj = problem.optimization_problem.objective
    con = problem.optimization_problem.constraints

    if FD == 'parallel':
        from mpi4py import MPI
        comm = MPI.COMM_WORLD
        myrank = comm.Get_rank()

    # Instantiate the problem and set objective

    try:
        import pyoptsparse as pyOpt
    except:
        raise ImportError('No version of pyOptsparse found')

    opt_prob = pyOpt.Optimization('SUAVE', mywrap)
    for ii in range(len(obj)):
        opt_prob.addObj(obj[ii, 0])

    # Set inputs
    nam = inp[:, 0]  # Names
    ini = inp[:, 1]  # Initials
    bnd = inp[:, 2]  # Bounds
    scl = inp[:, 3]  # Scale
    typ = inp[:, 4]  # Type

    # Pull out the constraints and scale them
    bnd_constraints = help_fun.scale_const_bnds(con)
    scaled_constraints = help_fun.scale_const_values(con, bnd_constraints)
    x = ini / scl

    for ii in range(0, len(inp)):
        lbd = (bnd[ii][0] / scl[ii])
        ubd = (bnd[ii][1] / scl[ii])
        #if typ[ii] == 'continuous':
        vartype = 'c'
        #if typ[ii] == 'integer':
        #vartype = 'i'
        opt_prob.addVar(nam[ii], vartype, lower=lbd, upper=ubd, value=x[ii])

    # Setup constraints
    for ii in range(0, len(con)):
        name = con[ii][0]
        edge = scaled_constraints[ii]

        if con[ii][1] == '<':
            opt_prob.addCon(name, upper=edge)
        elif con[ii][1] == '>':
            opt_prob.addCon(name, lower=edge)
        elif con[ii][1] == '=':
            opt_prob.addCon(name, lower=edge, upper=edge)

    # Finalize problem statement and run
    print(opt_prob)

    if solver == 'SNOPT':
        opt = pyOpt.SNOPT()
        CD_step = (sense_step**2.)**(1. / 3.
                                     )  #based on SNOPT Manual Recommendations
        opt.setOption('Function precision', sense_step**2.)
        opt.setOption('Difference interval', sense_step)
        opt.setOption('Central difference interval', CD_step)

    elif solver == 'SLSQP':
        opt = pyOpt.SLSQP()

    elif solver == 'FSQP':
        opt = pyOpt.FSQP()

    elif solver == 'PSQP':
        opt = pyOpt.PSQP()

    elif solver == 'NSGA2':
        opt = pyOpt.NSGA2(pll_type='POA')

    elif solver == 'ALPSO':
        #opt = pyOpt.pyALPSO.ALPSO(pll_type='DPM') #this requires DPM, which is a parallel implementation
        opt = pyOpt.ALPSO()

    elif solver == 'CONMIN':
        opt = pyOpt.CONMIN()

    elif solver == 'IPOPT':
        opt = pyOpt.IPOPT()

    elif solver == 'NLPQLP':
        opt = pyOpt.NLQPQLP()

    elif solver == 'NLPY_AUGLAG':
        opt = pyOpt.NLPY_AUGLAG()

    if nonderivative_line_search == True:
        opt.setOption('Nonderivative linesearch')
    if FD == 'parallel':
        outputs = opt(opt_prob, sens='FD', sensMode='pgc')

    elif solver == 'SNOPT' or solver == 'SLSQP':
        outputs = opt(opt_prob, sens='FD', sensStep=sense_step)

    else:
        outputs = opt(opt_prob)

    return outputs