Pyomo -- 使用 (python) 个集合的列表初始化一个 Set()

Pyomo -- initialize a Set() with a list of (python) sets

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

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;DR:我正在研究网络拦截模型。我的模型集代表网络中的一组路径。我想使用 (python) 集来存储路径,因为模型约束仅限于可行路径。因此,我需要检查路径中是否有任何边被禁止,而哈希函数将允许我有效地检查路径上是否有被禁止的边。换句话说,我稍后有一个功能:

def is_feasible(model, path):
    return any([edge in path and model.Interdicts[edge].value] for edge in model.edges)

其中 path 是我的 Set 的一个元素,model.Interdicts 是一个 Var(model.edges, within = binary)

我的后备方案是使用引用外部列表中路径的索引来初始化我的 Set,但随后我不得不将我的 pyomo 模型与非模型元素混合以评估模型约束,这真是令人头疼(但大多数网络拦截建模也是如此......)

首先,假设您可以创建一个如下所示的 Pyomo Set 对象,您可能无法将其用作其他组件的索引集中,因为条目不可散列。这相当于执行以下操作

>>> 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 对象填充其底层存储 set 的事实有关,Python 没有允许(与使用 set 作为字典的键相同的问题)。