Pyomo——使用(python)集合列表初始化集合()

Pyomo——使用(python)集合列表初始化集合(),python,pyomo,Python,Pyomo,我可以用集合列表在pyomo中初始化集合吗?换句话说,我想这样做: from pyomo.environ import * model = AbstractModel() a = set([1,2,3]) b = set([4,5,6]) model.c = Set(initialize = [a,b]) instance = model.create_instance() 不幸的是,这给了我一个错误: ERROR: Constructing component 'a' from data

我可以用集合列表在pyomo中初始化集合吗?换句话说,我想这样做:

from pyomo.environ import *

model = AbstractModel()
a = set([1,2,3])
b = set([4,5,6])
model.c = Set(initialize = [a,b])

instance = model.create_instance()
不幸的是,这给了我一个错误:

ERROR: Constructing component 'a' from data=None failed:
TypeError: Problem inserting set([1, 2, 3]) into set c
有没有其他方法可以达到我所缺少的效果

TL;博士:我正在研究一种网络拦截模型。我的模型集表示网络中的一组路径。我想使用python集来存储路径,因为模型约束仅限于可行路径。因此,我需要检查路径中的任何边是否被阻断,哈希函数将允许我有效地检查被阻断的边是否发生在路径上。换句话说,我以后有一个函数:

def is_feasible(model, path):
    return any([edge in path and model.Interdicts[edge].value] for edge in model.edges)
其中path是我的集合的一个元素,model.intercuts是Varmodel.edges,in=binary


我的退路是使用引用外部列表中路径的索引来初始化我的集合,但随后我不得不将我的pyomo模型与非模型元素混合,以评估模型约束,这是一个真正令人头痛的问题,但大多数网络阻断建模也是如此…

首先,假设您可以创建一个类似这样的pyomoset对象,您可能无法将其用作其他组件的索引集中,因为这些项是不可散列的。这相当于执行以下操作

>>> x = set([1,2,3])
>>> y = dict()
>>> y[x] = 1
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: unhashable type: 'set'
因此,您可能不得不求助于使用类似于frozenset的内容作为集合中的元素

我正计划在这一点上说一些其他的东西,关于Pyomo Set对象如何要求所有条目都具有相同的维度,例如,相同大小的元组,但是使用frozenset似乎也可以避免这个问题。您最初看到的错误源与Pyomo Set对象试图用您提供的Set对象填充其底层存储集这一事实有关,Python不允许出现与使用Set作为字典键相同的问题。

Perfect!我将上述代码中的a=set[1,2,3]和b=set[4,5,6]分别替换为a=frozenset[1,2,3]和b=frozenset[4,5,6],这是有效的。非常感谢。