3

我的模型中有多个级别的索引,pyomo我需要能够像这样索引变量:

model.b['a',1]

但这似乎由于某种原因是不可能的。我可以像这样使用多级索引:

model = ConcreteModel()
model.W = RangeSet(0,1)
model.I = RangeSet(0,4)
model.J = RangeSet(0,4)
model.K = RangeSet(0,3)

model.B = Var(model.W, model.I, model.J, model.K)
model.B[1,2,3,0]  # access the variable using the indices - THIS WORKS!!

但这不起作用,但是:

model = ConcreteModel()
model.W = Set(['a','b'])
model.I = RangeSet(0,4)

model.b = Var(model.W, model.I)  # I can't even create this - throws exception

...它抛出异常:

TypeError: Cannot index a component with an indexed set

为什么第一个有效,第二个无效?

4

1 回答 1

4

问题是当你写

model.W = Set(['a','b'])

您实际上是在创建一个索引 Set 对象,而不是使用提供的列表中的值的 Set。这是因为所有 Pyomo 组件构造函数都将位置参数视为索引集。

您可以通过在值列表之前添加“初始化”关键字来解决此问题

model.W = Set(initialize=['a','b'])

如果您提供整数列表而不是字符串,情况也是如此

model.I = Set(initialize=[0,1,2,3,4])
于 2016-10-06T21:31:20.237 回答