本文整理汇总了Python中pyomo.opt.SolverFactory.solve方法的典型用法代码示例。如果您正苦于以下问题:Python SolverFactory.solve方法的具体用法?Python SolverFactory.solve怎么用?Python SolverFactory.solve使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类pyomo.opt.SolverFactory
的用法示例。
在下文中一共展示了SolverFactory.solve方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: solve
# 需要导入模块: from pyomo.opt import SolverFactory [as 别名]
# 或者: from pyomo.opt.SolverFactory import solve [as 别名]
def solve(self,
solver,
io,
io_options,
solver_options,
symbolic_labels,
load_solutions):
""" Optimize the model """
assert self.model is not None
opt = SolverFactory(solver, solver_io=io)
opt.options.update(solver_options)
if io == 'nl':
assert opt.problem_format() == ProblemFormat.nl
elif io == 'lp':
assert opt.problem_format() == ProblemFormat.cpxlp
elif io == 'mps':
assert opt.problem_format() == ProblemFormat.mps
#elif io == 'python':
# print opt.problem_format()
# assert opt.problem_format() is None
try:
if isinstance(opt, PersistentSolver):
opt.set_instance(self.model, symbolic_solver_labels=symbolic_labels)
if opt.warm_start_capable():
results = opt.solve(warmstart=True,
load_solutions=load_solutions,
**io_options)
else:
results = opt.solve(load_solutions=load_solutions,
**io_options)
else:
if opt.warm_start_capable():
results = opt.solve(
self.model,
symbolic_solver_labels=symbolic_labels,
warmstart=True,
load_solutions=load_solutions,
**io_options)
else:
results = opt.solve(
self.model,
symbolic_solver_labels=symbolic_labels,
load_solutions=load_solutions,
**io_options)
return opt, results
finally:
pass
#opt.deactivate()
del opt
return None, None
示例2: run_problem
# 需要导入模块: from pyomo.opt import SolverFactory [as 别名]
# 或者: from pyomo.opt.SolverFactory import solve [as 别名]
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
示例3: solve_instance
# 需要导入模块: from pyomo.opt import SolverFactory [as 别名]
# 或者: from pyomo.opt.SolverFactory import solve [as 别名]
def solve_instance(instance):
solver = SolverFactory('couenne')
results = solver.solve(instance, tee=True)
instance.solutions.load_from(results)
return instance
示例4: solveModel
# 需要导入模块: from pyomo.opt import SolverFactory [as 别名]
# 或者: from pyomo.opt.SolverFactory import solve [as 别名]
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
示例5: solve_optimization_period
# 需要导入模块: from pyomo.opt import SolverFactory [as 别名]
# 或者: from pyomo.opt.SolverFactory import solve [as 别名]
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)
示例6: solve
# 需要导入模块: from pyomo.opt import SolverFactory [as 别名]
# 或者: from pyomo.opt.SolverFactory import solve [as 别名]
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()
示例7: calculateSharesQ
# 需要导入模块: from pyomo.opt import SolverFactory [as 别名]
# 或者: from pyomo.opt.SolverFactory import solve [as 别名]
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()))
示例8: Model_Resolution
# 需要导入模块: from pyomo.opt import SolverFactory [as 别名]
# 或者: from pyomo.opt.SolverFactory import solve [as 别名]
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
示例9: run_model
# 需要导入模块: from pyomo.opt import SolverFactory [as 别名]
# 或者: from pyomo.opt.SolverFactory import solve [as 别名]
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
示例10: test_instance_constraints
# 需要导入模块: from pyomo.opt import SolverFactory [as 别名]
# 或者: from pyomo.opt.SolverFactory import solve [as 别名]
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()
示例11: solve
# 需要导入模块: from pyomo.opt import SolverFactory [as 别名]
# 或者: from pyomo.opt.SolverFactory import solve [as 别名]
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)
示例12: main
# 需要导入模块: from pyomo.opt import SolverFactory [as 别名]
# 或者: from pyomo.opt.SolverFactory import solve [as 别名]
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
示例13: Model_Resolution_Dispatch
# 需要导入模块: from pyomo.opt import SolverFactory [as 别名]
# 或者: from pyomo.opt.SolverFactory import solve [as 别名]
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
示例14: _populate_bundle_dual_master_model
# 需要导入模块: from pyomo.opt import SolverFactory [as 别名]
# 或者: from pyomo.opt.SolverFactory import solve [as 别名]
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)
示例15: run_pyomo
# 需要导入模块: from pyomo.opt import SolverFactory [as 别名]
# 或者: from pyomo.opt.SolverFactory import solve [as 别名]
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