Pyomo:从Python代码访问解决方案 [英] Pyomo: Access Solution From Python Code
问题描述
我有一个线性整数程序要解决.我安装了求解器glpk(感谢此答案)和pyomo.我写了这样的代码:
I have a linear integer programme I want to solve. I installed solver glpk (thanks to this answer) and pyomo. I wrote code like this:
from pyomo.environ import *
from pyomo.opt import SolverFactory
a = 370
b = 420
c = 2
model = ConcreteModel()
model.x = Var([1,2], domain=NonNegativeIntegers)
model.Objective = Objective(expr = a * model.x[1] + b * model.x[2], sense=minimize)
model.Constraint1 = Constraint(expr = model.x[1] + model.x[2] == c)
# ... more constraints
opt = SolverFactory('glpk')
results = opt.solve(model)
这将产生文件results.yaml
的解决方案.
This produces solution to file results.yaml
.
我要使用相同的模型解决许多问题,但使用不同的a
,b
和c
值.我想为a
,b
和c
分配不同的值,求解模型,获得model.x[1]
和model.x[2]
的解决方案,并列出a
,b
,model.x[1]
和model.x[2]
.我阅读了文档,但是示例仅将解决方案写入文件,例如results.yaml
.
I have many problems I want to solve using the same model but with different a
, b
, and c
values. I want to assign different values to a
, b
, and c
, solve the model, obtain solution of model.x[1]
and model.x[2]
, and have a listing of a
, b
, c
, model.x[1]
and model.x[2]
. I read documentation but examples only write solutions to file such as results.yaml
.
我可以通过任何方式访问代码中的解决方案值吗?
Is there any way I can access to solution values from code?
谢谢
推荐答案
我不确定这是否是您要寻找的东西,但这是在某些脚本中打印一些变量的一种方式.
I'm not sure if this is what you are looking for, but this is a way that I have some variables being printed in one of my scripts.
from pyomo.environ import *
from pyomo.opt import SolverFactory
from pyomo.core import Var
M = AbstractModel()
opt = SolverFactory('glpk')
# Vars, Params, Objective, Constraints....
instance = M.create_instance('input.dat') # reading in a datafile
results = opt.solve(instance, tee=True)
results.write()
instance.solutions.load_from(results)
for v in instance.component_objects(Var, active=True):
print ("Variable",v)
varobject = getattr(instance, str(v))
for index in varobject:
print (" ",index, varobject[index].value)
这篇关于Pyomo:从Python代码访问解决方案的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!