gpt4 book ai didi

python - Pyomo 输出错误

转载 作者:太空宇宙 更新时间:2023-11-03 17:50:45 27 4
gpt4 key购买 nike

我正在使用 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'

最佳答案

FlowBalance_rule 中存在以下拼写错误

sum(model.Flow[node, j] for j in model.Nodes if (j,node) in model.Arcs)

其中 model.Arcs 中的索引 model.Flow[node,j] 和条件 if (j,node) 导致了错误。

我假设您想翻转条件元组的顺序,以下工作

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

关于python - Pyomo 输出错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29133456/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com