本文整理匯總了Python中pyomo.opt.SolverFactory方法的典型用法代碼示例。如果您正苦於以下問題:Python opt.SolverFactory方法的具體用法?Python opt.SolverFactory怎麽用?Python opt.SolverFactory使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在類pyomo.opt
的用法示例。
在下文中一共展示了opt.SolverFactory方法的10個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。
示例1: find_solver
# 需要導入模塊: from pyomo import opt [as 別名]
# 或者: from pyomo.opt import SolverFactory [as 別名]
def find_solver():
dispatch_solver = _ConfigParser.get('opt', 'dispatch_solver')
# TODO: is replacing spaces just stripping surrounding whitespace? If so, use splitclean instead
requested_solvers = _ConfigParser.get('opt', 'dispatch_solver').replace(' ', '').split(',')
solver_name = None
# inspired by the solver detection code at https://software.sandia.gov/trac/pyomo/browser/pyomo/trunk/pyomo/scripting/driver_help.py#L336
# suppress logging of warnings for solvers that are not found
logger = logging.getLogger('pyomo.solvers')
_level = logger.getEffectiveLevel()
logger.setLevel(logging.ERROR)
for requested_solver in requested_solvers:
logging.debug("Looking for %s solver" % requested_solver)
if SolverFactory(requested_solver).available(False):
solver_name = requested_solver
logging.debug("Using %s solver" % requested_solver)
break
# restore logging
logger.setLevel(_level)
assert solver_name is not None, "Dispatch could not find any of the solvers requested in your configuration (%s) please see README.md, check your configuration, and make sure you have at least one requested solver installed." % ', '.join(requested_solvers)
return solver_name
示例2: __init__
# 需要導入模塊: from pyomo import opt [as 別名]
# 或者: from pyomo.opt import SolverFactory [as 別名]
def __init__(self, action_set, x = None, **kwargs):
self.built = False
#setup the optimizer here:
self._optimizer = SolverFactory('cbc')
self._results = None
#todo: Alex fill out these functions
## todo: check what each of these does in CPLEX.
self._set_mip_time_limit = lambda mip, time_limit: True #_set_mip_time_limit(self, mip, time_limit)
self._set_mip_node_limit = lambda mip, node_limit: True #_set_mip_node_limit(self, mip, node_limit)
## todo: not sure what to put for this. let's talk about what the cplex display flag does.
self._set_mip_display = lambda mip, display_flag: True #_set_mip_display(self, mip, display)
self._apriori_infeasible = False
super().__init__(action_set = action_set, x = x, **kwargs)
#### building MIP ####
示例3: run_pyomo
# 需要導入模塊: from pyomo import opt [as 別名]
# 或者: from pyomo.opt import SolverFactory [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
示例4: solve_optimization_period
# 需要導入模塊: from pyomo import opt [as 別名]
# 或者: from pyomo.opt import SolverFactory [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)
示例5: test_instance_constraints
# 需要導入模塊: from pyomo import opt [as 別名]
# 或者: from pyomo.opt import SolverFactory [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()
示例6: run_optimization
# 需要導入模塊: from pyomo import opt [as 別名]
# 或者: from pyomo.opt import SolverFactory [as 別名]
def run_optimization(params, return_model_instance=False):
try:
model, solver_name = params
instance = model.create_instance()
solver = SolverFactory(solver_name)
solution = solver.solve(instance)
instance.solutions.load_from(solution)
except Exception as e:
traceback.print_exc()
raise e
return instance if return_model_instance else dispatch_classes.all_results_to_list(instance)
# Applies method to data using parallel processes and returns the result, but closes the main process's database
# connection first, since otherwise the connection winds up in an unusable state on macOS.
示例7: Model_Resolution
# 需要導入模塊: from pyomo import opt [as 別名]
# 或者: from pyomo.opt import SolverFactory [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
#\
示例8: solve_pyomo_model
# 需要導入模塊: from pyomo import opt [as 別名]
# 或者: from pyomo.opt import SolverFactory [as 別名]
def solve_pyomo_model(self, solver='glpk', nproc=1, debug_mode=False, maxiter=10):
"""
Solve Pyomo model (must be called after create_pyomo_model)
:param solver: (string) solver name. glpk, cplex, cbc, gurobi.
:param nproc: (int) number of processors. 1=serial.
:param debug_mode: (boolean) Whether to run in debug mode.
Use when there may be infeasibilities in the network.
:param maxiter: (int) maximum iterations for debug mode.
:returns: nothing, but assigns results to self.model.solutions.
:raises: RuntimeError, if problem is found to be infeasible.
"""
from pyomo.opt import SolverFactory
opt = SolverFactory(solver)
if nproc > 1 and solver is not 'glpk':
opt.options['threads'] = nproc
if debug_mode:
run_again = True
i = 0
vol_total = 0
while run_again and i < maxiter:
print('-----Solving Pyomo Model (debug=%s)' % debug_mode)
self.results = opt.solve(self.model)
print('Finished. Fixing debug flows...')
run_again,vol = self.fix_debug_flows()
i += 1
vol_total += vol
if run_again:
print(('Warning: Debug mode maximum iterations reached.'
' Will still try to solve without debug mode.'))
else:
print('All debug flows eliminated (iter=%d, vol=%0.2f)' % (i,vol_total))
else:
print('-----Solving Pyomo Model (debug=%s)' % debug_mode)
self.results = opt.solve(self.model, tee=False)
if self.results.solver.termination_condition == TerminationCondition.optimal:
print('Optimal Solution Found (debug=%s).' % debug_mode)
self.model.solutions.load_from(self.results)
else:
raise RuntimeError('Problem Infeasible. Run again starting from debug mode.')
示例9: Model_Resolution_Integer
# 需要導入模塊: from pyomo import opt [as 別名]
# 或者: from pyomo.opt import SolverFactory [as 別名]
def Model_Resolution_Integer(model,datapath="Example/data_Integer.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_Integer 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, Generator_Cost_1_Integer, \
Total_Cost_Generator_Integer, Initial_Inversion, Operation_Maintenance_Cost,Total_Finalcial_Cost,\
Battery_Reposition_Cost, Scenario_Lost_Load_Cost, Sceneario_Generator_Total_Cost, \
Scenario_Net_Present_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.scenario,model.periods, rule=Energy_balance) # Energy balance
model.MaximunLostLoad = Constraint(model.scenario,rule=Maximun_Lost_Load) # Maximum permissible lost load
# 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.GeneratorBoundsMin = Constraint(model.scenario,model.periods, rule=Generator_Bounds_Min_Integer)
model.GeneratorBoundsMax = Constraint(model.scenario,model.periods, rule=Generator_Bounds_Max_Integer)
model.GeneratorCost1 = Constraint(model.scenario, model.periods, rule=Generator_Cost_1_Integer)
model.EnergyGenaratorEnergyMax = Constraint(model.scenario,model.periods, rule=Energy_Genarator_Energy_Max_Integer)
model.TotalCostGenerator = Constraint(model.scenario, rule=Total_Cost_Generator_Integer)
# Financial Constraints
model.FinancialCost = Constraint(rule=Financial_Cost) # Financial 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)
model.ScenarioLostLoadCost = Constraint(model.scenario, rule=Scenario_Lost_Load_Cost)
model.ScenearioGeneratorTotalCost = Constraint(model.scenario, rule=Sceneario_Generator_Total_Cost)
model.ScenarioNetPresentCost = Constraint(model.scenario, rule=Scenario_Net_Present_Cost)
instance = model.create_instance("Example/data_Integer.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.07") # 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
示例10: Model_Resolution_Dispatch
# 需要導入模塊: from pyomo import opt [as 別名]
# 或者: from pyomo.opt import SolverFactory [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