我正在使用pyomo包来实现优化问题。我正在尝试在pyomo在线文档中提供的一个示例问题。但是,当我试图解决它时,我遇到了错误。
使用的python代码:
from __future__ import division
from pyomo.environ import *
model = AbstractModel()
model.Nodes = Set()
model.Arcs = Set(dimen=2)
model.Flow = Var(model.Arcs, domain=NonNegativeReals)
model.FlowCost = Param(model.Arcs)
model.Demand = Param(model.Nodes)
model.Supply = Param(model.Nodes)
def Obj_rule(model):
return summation(model.FlowCost, model.Flow)
model.Obj = Objective(rule=Obj_rule, sense=minimize)
def FlowBalance_rule(model, node):
return model.Supply[node] \
+ sum(model.Flow[i, node] for i in model.Nodes if (i,node) in model.Arcs) \
- model.Demand[node] \
- sum(model.Flow[node, j] for j in model.Nodes if (j,node) in model.Arcs) \
== 0
model.FlowBalance = Constraint(model.Nodes, rule=FlowBalance_rule)
并且,数据文件是:
set Nodes := CityA CityB CityC ;
set Arcs :=
CityA CityB
CityA CityC
CityC CityB
;
param : FlowCost :=
CityA CityB 1.4
CityA CityC 2.7
CityC CityB 1.6
;
param Demand :=
CityA 0
CityB 1
CityC 1
;
param Supply :=
CityA 2
CityB 0
CityC 0
;
当我尝试解决此问题时,我收到以下错误。
[ 0.00] Setting up Pyomo environment
[ 0.00] Applying Pyomo preprocessing actions
[ 0.01] Creating model
ERROR: Rule failed when generating expression for constraint FlowBalance with index CityB:
KeyError: "Error accessing indexed component: Index '('CityB', 'CityC')' is not valid for array component 'Flow'"
ERROR: Constructing component 'FlowBalance' from data=None failed:
KeyError: "Error accessing indexed component: Index '('CityB', 'CityC')' is not valid for array component 'Flow'"
ERROR: Unexpected exception while running model test.py:
Error accessing indexed component: Index '('CityB', 'CityC')' is not valid for array component 'Flow'
答案 0 :(得分:1)
FlowBalance_rule
sum(model.Flow[node, j] for j in model.Nodes if (j,node) in model.Arcs)
索引model.Flow[node,j]
和条件if (j,node) in model.Arcs
导致错误。
我假设您要翻转条件元组的顺序,以下作品
def FlowBalance_rule(model, node):
return model.Supply[node] \
+ sum(model.Flow[i, node] for i in model.Nodes if (i,node) in model.Arcs) \
- model.Demand[node] \
- sum(model.Flow[node, j] for j in model.Nodes if (node,j) in model.Arcs) \
== 0