【问题标题】:Pyomo output errorPyomo 输出错误
【发布时间】:2015-03-18 21:56:20
【问题描述】:

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

【问题讨论】:

    标签: python python-2.7 pyomo


    【解决方案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
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-03-04
      • 2016-08-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-10-16
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多