当前位置: 首页>>代码示例>>Python>>正文


Python opt.SolverFactory类代码示例

本文整理汇总了Python中pyomo.opt.SolverFactory的典型用法代码示例。如果您正苦于以下问题:Python SolverFactory类的具体用法?Python SolverFactory怎么用?Python SolverFactory使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。


在下文中一共展示了SolverFactory类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: solve_instance

def solve_instance(instance):
    solver = SolverFactory('couenne')

    results = solver.solve(instance, tee=True)
    instance.solutions.load_from(results)

    return instance
开发者ID:davidlandry93,项目名称:ift7020-projet,代码行数:7,代码来源:optimize_pose_main.py

示例2: solve

 def solve(self):
     opt = SolverFactory("cplex")
     model = self._model
     model.dual.clearValue()
     model.load(opt.solve(model))#,keepfiles=True,symbolic_solver_labels=True,tee=True))
     self._solved = True
     self._update_tree_node_xbars()
开发者ID:Pyomo,项目名称:pyomo,代码行数:7,代码来源:dualphmodel.py

示例3: solve_optimization_period

 def solve_optimization_period(self, period, return_model_instance=False):
     model = dispatch_formulation.create_dispatch_model(self, period)
     instance = model.create_instance(report_timing=False) # report_timing=True used to try to make this step faster
     solver = SolverFactory(cfg.solver_name)
     solution = solver.solve(instance)
     instance.solutions.load_from(solution)
     return instance if return_model_instance else all_results_to_list(instance)
开发者ID:anamileva,项目名称:energyPATHWAYS,代码行数:7,代码来源:dispatch_classes.py

示例4: initialize

def initialize(**kwds):
    obj = Options(**kwds)
    #
    # Set obj.available
    #
    opt = None
    try:
        opt = SolverFactory(obj.name, solver_io=obj.io)
    except:
        pass
    if opt is None or isinstance(opt, UnknownSolver):
        obj.available = False
    elif (obj.name == "gurobi") and (not GUROBISHELL.license_is_valid()):
        obj.available = False
    elif (obj.name == "baron") and (not BARONSHELL.license_is_valid()):
        obj.available = False
    else:
        obj.available = (opt.available(exception_flag=False)) and (
            (not hasattr(opt, "executable")) or (opt.executable() is not None)
        )
    #
    # Check capabilities
    #
    if obj.available:
        for _c in obj.capabilities:
            if not _c in opt._capabilities:
                raise ValueError("Solver %s does not support capability %s!" % (obj.name, _c))
        #
        # Get version
        #
        obj.version = opt.version()
    return obj
开发者ID:qtothec,项目名称:pyomo,代码行数:32,代码来源:solvers.py

示例5: solveModel

    def solveModel(self, x, y, z):
        model = self.model
        opt = SolverFactory(self.config.solver)
        opt.options.update(self.config.solver_options)

        results = opt.solve(
            model, keepfiles=self.keepfiles, tee=self.stream_solver)

        if ((results.solver.status == SolverStatus.ok)
                and (results.solver.termination_condition == TerminationCondition.optimal)):
            model.solutions.load_from(results)
            for i in range(0, self.lx):
                x[i] = value(self.TRF.xvars[i])
            for i in range(0, self.ly):
                y[i] = value(self.TRF.y[i+1])
            for i in range(0, self.lz):
                z[i] = value(self.TRF.zvars[i])

            for obj in model.component_data_objects(Objective,active=True):
                return True, obj()

        else:
            print("Waring: solver Status: " + str(results.solver.status))
            print("And Termination Conditions: " + str(results.solver.termination_condition))
            return False, 0
开发者ID:Pyomo,项目名称:pyomo,代码行数:25,代码来源:PyomoInterface.py

示例6: run_problem

def run_problem(purchases, sales, stella_correction, jammies_correction):
    opt = SolverFactory('glpk')

    (number_corr, price_corr, model, dual_model) = make_model(purchases,sales,stella_correction,jammies_correction)

    results = opt.solve(model)

    output = []
    solutions = results.get('Solution', [])
    if len(solutions) > 0:
        model.load(results)
        for (p,s) in model.pairings:
            ct = model.selected[p,s].value
            if ct > 0:
                output.append((purchases[p-1], sales[s-1], float(ct) / number_corr))


    ret = dict(pairs=output, full_result=results.json_repn())


    if results.solver.status == SolverStatus.ok:
        if results.solver.termination_condition == TerminationCondition.optimal:
            ret['status'] = "optimal"
            # the following procedure for getting the value is right from
            # the coopr source itself...
            key = results.solution.objective.keys()[0]
            ret['value'] = float(results.solution.objective[key].value) / price_corr / number_corr
            collect_dual(**locals())
        else:
            ret['status'] = "not solved"
    else:
        ret['status'] = "solver error"

    return ret
开发者ID:michaelryanmcneill,项目名称:comp521-mirror,代码行数:34,代码来源:compute.py

示例7: calculateSharesQ

def calculateSharesQ(expressionVars, relationSizes, reducerCapacity):
    """ Use the MINLP solver to calculate the shares of attribute variables

    input   expressionVars  A list of lists of expression vars
                            ex. [[[3], [1], [2]]
            relationSizes A list ex. [1000, 1000, 1000]
            numberReducers an integer ex. 32

    output (shares, com_cost) Two outputs.
            shares First argument is the shares DICT !! unordered
                    ex. {'1':2, '2': 1, '3': 16}
            com_cost The objective function's value give the shares
                    ex. 2600000
    """
    # print expressionVars
    uniqueVars = getUniqueExpressionVars(expressionVars)
    print uniqueVars
    shares = {}
    # if sum(relationSizes) < reducerCapacity*10:
    # skew_share = int(pow(np.prod(relationSizes)/100000 , 1.0/len(uniqueVars)))
    # shares = {str(var): skew_share for var in uniqueVars}
    # shares = {str(var): 1 for var in uniqueVars}

    # com_cost = sum(relationSizes)
    # return (shares, com_cost, com_cost/np.prod(shares.values()))
    # reducerCapacity = 100000

    objectiveExpression = constructObjective(expressionVars, relationSizes)
    print objectiveExpression
    budgetExpression_UB = constructCapacityConstraintUB(
        expressionVars, objectiveExpression, reducerCapacity)
    budgetExpression_LB = constructCapacityConstraintLB(
        expressionVars, objectiveExpression, reducerCapacity)

    # Create a solver factory using Couenne
    opt = SolverFactory('couenne')
    model = ConcreteModel()
    model.x = Var(uniqueVars, domain=PositiveIntegers)
    model.OBJ = Objective(expr=eval(objectiveExpression))
    model.Constraint1 = Constraint(expr=eval(budgetExpression_UB))
    # model.Constraint2 = Constraint(expr=eval(budgetExpression_LB))
    # Create a model instance and optimize
    instance = model.create_instance()
    results = opt.solve(instance)
    instance.display()
    # Save calculated shares
    for v in instance.component_objects(Var, active=True):
        varobject = getattr(instance, str(v))
        for index in varobject:
            # Round 2.999->3
            shares[str(varobject[index])[2:-1]
                   ] = (int(round(varobject[index].value)))
    # Save communication cost
    for o in instance.component_objects(Objective, active=True):
        oobject = getattr(instance, str(o))
        for idx in oobject:
            com_cost = value(oobject[idx])
    return (shares, com_cost, com_cost/np.prod(shares.values()))
开发者ID:nstasino,项目名称:sharesskew,代码行数:58,代码来源:minlpSolver.py

示例8: Model_Resolution

def Model_Resolution(model,datapath="Example/data.dat"):   
    '''
    This function creates the model and call Pyomo to solve the instance of the proyect 
    
    :param model: Pyomo model as defined in the Model_creation library
    :param datapath: path to the input data file
    
    :return: The solution inside an object call instance.
    '''
    
    from Constraints import  Net_Present_Cost, Solar_Energy,State_of_Charge,\
    Maximun_Charge, Minimun_Charge, Max_Power_Battery_Charge, Max_Power_Battery_Discharge, Max_Bat_in, Max_Bat_out, \
    Financial_Cost, Energy_balance, Maximun_Lost_Load,Scenario_Net_Present_Cost, Scenario_Lost_Load_Cost, \
    Initial_Inversion, Operation_Maintenance_Cost, Total_Finalcial_Cost, Battery_Reposition_Cost, Maximun_Diesel_Energy, Diesel_Comsuption,Diesel_Cost_Total
    
    
    # OBJETIVE FUNTION:
    model.ObjectiveFuntion = Objective(rule=Net_Present_Cost, sense=minimize)  
    
    # CONSTRAINTS
    #Energy constraints
    model.EnergyBalance = Constraint(model.scenario,model.periods, rule=Energy_balance)
    model.MaximunLostLoad = Constraint(model.scenario, rule=Maximun_Lost_Load) # Maximum permissible lost load
    model.ScenarioLostLoadCost = Constraint(model.scenario, rule=Scenario_Lost_Load_Cost)

    # PV constraints
    model.SolarEnergy = Constraint(model.scenario, model.periods, rule=Solar_Energy)  # Energy output of the solar panels
    # Battery constraints
    model.StateOfCharge = Constraint(model.scenario, model.periods, rule=State_of_Charge) # State of Charge of the battery
    model.MaximunCharge = Constraint(model.scenario, model.periods, rule=Maximun_Charge) # Maximun state of charge of the Battery
    model.MinimunCharge = Constraint(model.scenario, model.periods, rule=Minimun_Charge) # Minimun state of charge
    model.MaxPowerBatteryCharge = Constraint(rule=Max_Power_Battery_Charge)  # Max power battery charge constraint
    model.MaxPowerBatteryDischarge = Constraint(rule=Max_Power_Battery_Discharge)    # Max power battery discharge constraint
    model.MaxBatIn = Constraint(model.scenario, model.periods, rule=Max_Bat_in) # Minimun flow of energy for the charge fase
    model.Maxbatout = Constraint(model.scenario, model.periods, rule=Max_Bat_out) #minimun flow of energy for the discharge fase

    # Diesel Generator constraints
    model.MaximunDieselEnergy = Constraint(model.scenario, model.periods, rule=Maximun_Diesel_Energy) # Maximun energy output of the diesel generator
    model.DieselComsuption = Constraint(model.scenario, model.periods, rule=Diesel_Comsuption)    # Diesel comsuption 
    model.DieselCostTotal = Constraint(model.scenario, rule=Diesel_Cost_Total)
    
    # Financial Constraints
    model.FinancialCost = Constraint(rule=Financial_Cost) # Financial cost
    model.ScenarioNetPresentCost = Constraint(model.scenario, rule=Scenario_Net_Present_Cost)    
    model.InitialInversion = Constraint(rule=Initial_Inversion)
    model.OperationMaintenanceCost = Constraint(rule=Operation_Maintenance_Cost)
    model.TotalFinalcialCost = Constraint(rule=Total_Finalcial_Cost)
    model.BatteryRepositionCost = Constraint(rule=Battery_Reposition_Cost) 

    
    instance = model.create_instance(datapath) # load parameters       
    opt = SolverFactory('cplex') # Solver use during the optimization    
    results = opt.solve(instance, tee=True) # Solving a model instance 
    instance.solutions.load_from(results)  # Loading solution into instance
    return instance
开发者ID:squoilin,项目名称:MicroGrids,代码行数:55,代码来源:Model_Resolution.py

示例9: run_model

def run_model (input_data_file):
    list=[]
    insts=[]
    opt = SolverFactory("glpk")
    instance=model.create(input_data_file)
    res = opt.solve(instance)
    instance.load(res)
    list.append(res)
    insts.append(instance)
    print res
    return list, insts
开发者ID:UMWRG,项目名称:demos,代码行数:11,代码来源:trivial_example_type_format.py

示例10: test_instance_constraints

 def test_instance_constraints(model):
     instance = model.create_instance(report_timing=False)        
     for c in instance.component_objects(Constraint):
         c.activate()
         solver = SolverFactory(cfg.solver_name)
         solution = solver.solve(instance)
         if solution.solver.termination_condition == TerminationCondition.infeasible:
             pass
         else:
             print c.name
             c.activate()
开发者ID:anamileva,项目名称:energyPATHWAYS,代码行数:11,代码来源:dispatch_classes.py

示例11: solve

    def solve(self, solver='glpk', solver_io='lp', debug=False,
              duals=False, **kwargs):
        """ Method that takes care of the communication with the solver
        to solve the optimization model

        Parameters
        ----------

        self : pyomo.ConcreteModel
        solver str: solver to be used e.g. 'glpk','gurobi','cplex'
        solver_io str: str that defines the solver interaction
        (file or interface) 'lp','nl','python'
        **kwargs: other arguments for the pyomo.opt.SolverFactory.solve()
        method

        Returns
        -------
        self : solved pyomo.ConcreteModel() instance
        """

        from pyomo.opt import SolverFactory
        # Create a 'dual' suffix component on the instance
        # so the solver plugin will know which suffixes to collect
        if duals is True:
            # dual variables (= shadow prices)
            self.dual = po.Suffix(direction=po.Suffix.IMPORT)
            # reduced costs
            self.rc = po.Suffix(direction=po.Suffix.IMPORT)
        # write lp-file
        if debug == True:
            self.write('problem.lp',
                       io_options={'symbolic_solver_labels': True})
            # print instance
            # instance.pprint()

        # solve instance
        opt = SolverFactory(solver, solver_io=solver_io)
        # store results
        results = opt.solve(self, **kwargs)
        if debug == True:
            if (results.solver.status == "ok") and \
               (results.solver.termination_condition == "optimal"):
                # Do something when the solution in optimal and feasible
                self.solutions.load_from(results)

            elif (results.solver.termination_condition == "infeasible"):
                print("Model is infeasible",
                      "Solver Status: ", results.solver.status)
            else:
                # Something else is wrong
                print("Solver Status: ", results.solver.status, "\n"
                      "Termination condition: ",
                      results.solver.termination_condition)
开发者ID:chris-fleischer,项目名称:oemof_base_pypower,代码行数:53,代码来源:optimization_model.py

示例12: main

def main():

    # create the empty list of cuts to start
    cut_on = []
    cut_off = []

    done = False
    while not done:
        model = create_sudoku_model(cut_on, cut_off, board)

        # options = Options()
        # options.solver = 'glpk'
        # options.quiet = True
        # options.tee = True

        # results, opt = util.apply_optimizer(options, model)
        # instance.load(results)

        ## SOLVE ##
        opt = SolverFactory('glpk')

        # create model instance, solve
        # instance = model.create_instance()
        results = opt.solve(model)
        model.solutions.load_from(results)

        if str(results.Solution.Status) != 'optimal':
            break

        # add cuts
        new_cut_on = []
        new_cut_off = []
        for r in model.ROWS:
            for c in model.COLS:
                for v in model.VALUES:
                    # check if the binary variable is on or off
                    # note, it may not be exactly 1
                    if value(model.y[r,c,v]) >= 0.5:
                        new_cut_on.append((r,c,v))
                    else:
                        new_cut_off.append((r,c,v))

        cut_on.append(new_cut_on)
        cut_off.append(new_cut_off)

        print "Solution #" + str(len(cut_on))
        for i in xrange(1,10):
            for j in xrange(1,10):
                for v in xrange(1,10):
                    if value(model.y[i,j,v]) >= 0.5:
                        print v, " ",
            print
开发者ID:santiavenda2,项目名称:sudoku,代码行数:52,代码来源:pyomo_sudoku.py

示例13: run_pyomo

 def run_pyomo(self, model, data, **kwargs):
     """
     Pyomo optimization steps: create model instance from model formulation and data,
     get solver, solve instance, and load solution.
     """
     logging.debug("Creating model instance...")
     instance = model.create_instance(data)
     logging.debug("Getting solver...")
     solver = SolverFactory(cfg.solver_name)
     logging.debug("Solving...")
     solution = solver.solve(instance, **kwargs)
     logging.debug("Loading solution...")
     instance.solutions.load_from(solution)
     return instance
开发者ID:anamileva,项目名称:energyPATHWAYS,代码行数:14,代码来源:dispatch_classes.py

示例14: Model_Resolution_Dispatch

def Model_Resolution_Dispatch(model,datapath="Example/data_Dispatch.dat"):   
    '''
    This function creates the model and call Pyomo to solve the instance of the proyect 
    
    :param model: Pyomo model as defined in the Model_creation library
    
    :return: The solution inside an object call instance.
    '''
    from Constraints_Dispatch import  Net_Present_Cost,  State_of_Charge, Maximun_Charge, \
    Minimun_Charge, Max_Bat_in, Max_Bat_out, \
    Energy_balance, Maximun_Lost_Load, Generator_Cost_1_Integer,  \
    Total_Cost_Generator_Integer, \
    Scenario_Lost_Load_Cost, \
     Generator_Bounds_Min_Integer, Generator_Bounds_Max_Integer,Energy_Genarator_Energy_Max_Integer

    # OBJETIVE FUNTION:
    model.ObjectiveFuntion = Objective(rule=Net_Present_Cost, sense=minimize)  
    
    # CONSTRAINTS
    #Energy constraints
    model.EnergyBalance = Constraint(model.periods, rule=Energy_balance)  # Energy balance
    model.MaximunLostLoad = Constraint(rule=Maximun_Lost_Load) # Maximum permissible lost load
    
    # Battery constraints
    model.StateOfCharge = Constraint(model.periods, rule=State_of_Charge) # State of Charge of the battery
    model.MaximunCharge = Constraint(model.periods, rule=Maximun_Charge) # Maximun state of charge of the Battery
    model.MinimunCharge = Constraint(model.periods, rule=Minimun_Charge) # Minimun state of charge
    model.MaxBatIn = Constraint(model.periods, rule=Max_Bat_in) # Minimun flow of energy for the charge fase
    model.Maxbatout = Constraint(model.periods, rule=Max_Bat_out) #minimun flow of energy for the discharge fase
   
    #Diesel Generator constraints
    model.GeneratorBoundsMin = Constraint(model.periods, rule=Generator_Bounds_Min_Integer) 
    model.GeneratorBoundsMax = Constraint(model.periods, rule=Generator_Bounds_Max_Integer)
    model.GeneratorCost1 = Constraint(model.periods,  rule=Generator_Cost_1_Integer)
    model.EnergyGenaratorEnergyMax = Constraint(model.periods, rule=Energy_Genarator_Energy_Max_Integer)
    model.TotalCostGenerator = Constraint(rule=Total_Cost_Generator_Integer)
    
    # Financial Constraints
    model.ScenarioLostLoadCost = Constraint(rule=Scenario_Lost_Load_Cost)
    
    instance = model.create_instance("Example/data_dispatch.dat") # load parameters       
    opt = SolverFactory('cplex') # Solver use during the optimization    
#    opt.options['emphasis_memory'] = 'y'
#    opt.options['node_select'] = 3
    results = opt.solve(instance, tee=True,options_string="mipgap=0.03") # Solving a model instance 

    #    instance.write(io_options={'emphasis_memory':True})
    #options_string="mipgap=0.03", timelimit=1200
    instance.solutions.load_from(results) # Loading solution into instance
    return instance
开发者ID:squoilin,项目名称:MicroGrids,代码行数:50,代码来源:Model_Resolution.py

示例15: _populate_bundle_dual_master_model

    def _populate_bundle_dual_master_model(self, ph):

        current_iteration = ph._current_iteration

        # first step is to update the historical information from PH

        for scenario in ph._scenario_tree._scenarios:
            primal_objective_value = scenario._objective
            self._past_objective_values[(current_iteration, scenario._name)] = primal_objective_value

#        print "PAST OBJECTIVE FUNCTION VALUES=",self._past_objective_values

        assert current_iteration not in self._past_var_values
        iter_var_values = self._past_var_values[current_iteration] = {}
        for scenario in ph._scenario_tree._scenarios:
            iter_var_values[scenario._name] = copy.deepcopy(scenario._x)

#        print "PAST VAR VALUES=",self._past_var_values

        # propagate PH parameters to concrete model and re-preprocess.
        for scenario in ph._scenario_tree._scenarios:
            for tree_node in scenario._node_list[:-1]:
                new_w_k_parameter_name = \
                    "WDATA_"+str(tree_node._name)+"_"+str(scenario._name)+"_K"
                w_k_parameter = \
                    self._master_model.find_component(new_w_k_parameter_name)
                ph_weights = scenario._w[tree_node._name]

                for idx in w_k_parameter:
                    w_k_parameter[idx] = ph_weights[idx]

        # V bounds are per-variable, per-iteration
        for scenario in ph._scenario_tree._scenarios:
            scenario_name = scenario._name
            v_var = getattr(self._master_model, "V_"+str(scenario_name))
            expr = self._past_objective_values[(current_iteration, scenario_name)]
            for tree_node in scenario._node_list[:-1]:
                new_w_variable_name = "WVAR_"+str(tree_node._name)+"_"+str(scenario_name)
                w_variable = self._master_model.find_component(new_w_variable_name)
                expr += sum(iter_var_values[scenario_name][tree_node._name][var_id] * w_variable[var_id] for var_id in w_variable)

            self._master_model.V_Bound.add(v_var <= expr)

#        print "V_BOUNDS CONSTRAINT:"
#        self._master_model.V_Bound.pprint()


        solver = SolverFactory("cplex")
        results=solver.solve(self._master_model,tee=False,load_solutions=False)
        self._master_model.solutions.load_from(results)
开发者ID:Juanlu001,项目名称:pyomo,代码行数:50,代码来源:convexhullboundextension.py


注:本文中的pyomo.opt.SolverFactory类示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。