由带有 Pyomo 的索引集索引的变量 [英] Variable indexed by an indexed Set with Pyomo
问题描述
我试图弄清楚如何使用索引集索引变量:
im trying to figure out how to index a variable with an indexed Set:
例如:
model = AbstractModel()
model.J = Set()
model.O = Set(model.J)
我想定义一个索引在两个集合上的变量.有人能帮我吗?我尝试了以下方法:
I want to define a variable indexed over both Sets. Can Someone help me? I tried the following:
model.eb=Param(model.J, model.O)
这给了
TypeError("Cannot index a component with an indexed set")
有人对如何正确定义此变量有任何建议吗?
Has anyone any suggestions on how to define this variable properly?
推荐答案
Pyomo 不支持这样的索引集(我实际上不知道 Pyomo 中索引集的用例,尽管它们似乎是 GAMS 中的一个东西).您可以按如下方式进行处理(此处使用 ConcreteModel
进行说明):
Pyomo doesn't support indexed Sets like that (I'm actually unaware of use cases for indexed sets in Pyomo, although they seem to be a thing in GAMS). You could approach this as follows (using ConcreteModel
here, for illustration):
为作业和操作的所有唯一值定义集合(我假设您有一些将操作映射到作业的数据结构):
Define Sets for all unique values of jobs and operations (I assume you have some data structure which maps the operations to the jobs):
import pyomo.environ as po
import itertools
model = po.ConcreteModel()
map_J_O = {'J1': ['O11', 'O12'],
'J2': ['O21']}
unique_J = map_J_O.keys()
model.J = po.Set(initialize=unique_J)
unique_O = set(itertools.chain.from_iterable(map_J_O.values()))
model.O = po.Set(initialize=unique_O)
然后你可以定义一个包含 J 和 O 的所有有效组合的组合集:
Then you could define a combined Set which contains all valid combinations of J and O:
model.J_O = po.Set(within=model.J * model.O,
initialize=[(j, o) for j in map_J_O for o in map_J_O[j]])
model.J_O.display()
# Output:
#J_O : Dim=0, Dimen=2, Size=3, Domain=J_O_domain, Ordered=False, Bounds=None
# [('J1', 'O11'), ('J1', 'O12'), ('J2', 'O21')]
使用组合集创建参数:
model.eb = po.Param(model.J_O)
最后一行会抛出一个错误,参数是使用任何无效的 J 和 O 组合初始化的.或者,您也可以为所有组合初始化参数
This last line will throw an error the parameter is initialized using any non-valid combination of J and O. Alternatively, you can also initialize the parameter for all combinations
po.Param(model.J * model.O)
并且只初始化有效的组合,但这可能会在以后咬你.此外,model.J_O
也可能适用于变量和约束,具体取决于您的模型公式.
and only initialize for the valid combinations, but this might bite you later. Also, model.J_O
might be handy also for variables and constraints, depending on your model formulation.
这篇关于由带有 Pyomo 的索引集索引的变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!