Skip to main content
 首页 » 编程设计

python之如何在带有集合和范围集的 pyomo 中使用多级索引

2024年08月22日34mfryf

我在 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 

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

请您参考如下方法:

问题是当你写

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

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

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

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

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

model.I = Set(initialize=[0,1,2,3,4])