I am a new Pyomo/Python user, and I am just wondering how to display the optimal variable values in a class-type Pyomo model.
I have just tried the standard example from Pyomo example library, the "min-cost-flow model". The code is available in在代码底部,它说:
sp = MinCostFlow('nodes.csv', 'arcs.csv')
sp.solve()
print('\n\n---------------------------')
print('Cost: ', sp.m.OBJ())
,输出为
Academic license - for non-commercial use only
Read LP format model from file.
Reading time = 0.00 seconds
x8: 7 rows, 8 columns, 16 nonzeros
No parameters matching 'mip_tolerances_integrality' found
No parameters matching 'mip_tolerances_mipgap' found
Optimize a model with 7 rows, 8 columns and 16 nonzeros
Coefficient statistics:
Matrix range [1e+00, 1e+00]
Objective range [1e+00, 5e+00]
Bounds range [0e+00, 0e+00]
RHS range [1e+00, 1e+00]
Presolve removed 7 rows and 8 columns
Presolve time: 0.00s
Presolve: All rows and columns removed
Iteration Objective Primal Inf. Dual Inf. Time
0 5.0000000e+00 0.000000e+00 0.000000e+00 0s
Solved in 0 iterations and 0.01 seconds
Optimal objective 5.000000000e+00
我只能得到最优目标,但是最优变量值呢?我还搜索了文档,该文档告诉我使用以下内容:
print("x[2]=",pyo.value(model.x[2])).
但它不适用于最小成本流模型之类的类类型模型。
我还试图修改该类中的函数定义:
def solve(self):
"""Solve the model."""
solver = pyomo.opt.SolverFactory('gurobi')
results = solver.solve(self.m, tee=True, keepfiles=False, options_string="mip_tolerances_integrality=1e-9, mip_tolerances_mipgap=0")
print('\n\n---------------------------')
print('First Variable: ', self.m.Y[0])
但是效果不佳。输出为:
KeyError: "Index '0' is not valid for indexed component 'Y'"
您能帮我吗?谢谢!
Gabriel
答案 0 :(得分:1)
解决方案后显示模型结果的最直接方法是使用model.display()
函数。就您而言,self.m.display()
。
display()
函数也适用于Var
对象,因此,如果您有变量self.m.x
,则可以执行self.m.x.display()
。