我是Pyomo/Python的新用户,我只是想知道如何在类类型的Pyomo模型中显示最佳变量值。
我刚刚尝试了Pyomo示例库中的标准示例“最小成本流模型”。该代码在中提供https://github.com/Pyomo/PyomoGallery/wiki/Min-cost-flow
在代码的底部,它说:
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'"
你能帮我吗?谢谢!
加布里埃尔
解决方案后显示模型结果的最直接方法是使用model.display()
函数。在这种情况下,self.m.display()。
show()
函数也适用于Var
对象,所以如果您有一个变量Self. m. x
,您可以执行self.m.x.display()
。