Pyomo中的稀疏集,用于表示图形/网络模型中的弧/边集

时间:2019-09-26 08:31:18

标签: python networkx pyomo directed-graph undirected-graph

我不知道如何在pyomo中定义边集。

我有一个非常低密度(稀疏)网络(又称图形),其中边的数量远少于完全连接的图形。

我想定义一个边集,以便构造与边有关的约束。但是,我无法确定pyomo希望我做什么,而我所做的一切都会导致无法解决的错误消息。

import pyomo
import pyomo.environ as pe
edges = [(0,1),(0,2),(1,2),(2,3),(2,4),(3,4)]

model = pe.ConcreteModel()
model.E = pe.Set(initialize=lambda _,i : edges[i]) # Edge set

上面的代码抛出错误

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "C:\Users\Joey\Python37\lib\site-packages\pyomo\core\base\block.py", line 568, in __setattr__
    self.add_component(name, val)
  File "C:\Users\Joey\Python37\lib\site-packages\pyomo\core\base\block.py", line 1008, in add_component
    val.construct(data)
  File "C:\Users\Joey\Python37\lib\site-packages\pyomo\core\base\sets.py", line 1221, in construct
    self.add(val)
  File "C:\Users\Joey\Python37\lib\site-packages\pyomo\core\base\sets.py", line 821, in add
    self._verify(tmp)
  File "C:\Users\Joey\Python37\lib\site-packages\pyomo\core\base\sets.py", line 772, in _verify
    raise ValueError("The value="+str(element)+" is a tuple for set="+self.name+", which has dimen="+str(self.dimen))
ValueError: The value=(0, 2) is a tuple for set=E, which has dimen=1

给定的边完全由元组标识。边缘连接节点0和节点1应该是(0,1)。该元组应为其标识符。这样的标识符列表的维度为1。因此,我不确定pyomo希望我做什么。

1 个答案:

答案 0 :(得分:0)

因此,事实证明dim是集合本身的维度。 dimen是每个集合元素必须包含的元素数目,而不是集合的维数。 Pyomo默认假定dimen=1,这意味着Set将不接受一个元组作为set元素,因为它具有多个元素。设置dimen=None会禁用此参数检查。

因此,一种方法是传递initialize的边列表,尺寸为2或None

model.E = pe.Set(initialize=edges, dimen=2)

集合构造函数不知道元素数量,因此实际上不起作用:

model.E = pe.Set(initialize=lambda _,i: edges[i], dimen=2) # Edge set

错误:

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "C:\Users\Joey\Python37\lib\site-packages\pyomo\core\base\block.py", line 568, in __setattr__
    self.add_component(name, val)
  File "C:\Users\Joey\Python37\lib\site-packages\pyomo\core\base\block.py", line 1008, in add_component
    val.construct(data)
  File "C:\Users\Joey\Python37\lib\site-packages\pyomo\core\base\sets.py", line 1223, in construct
    val = apply_indexed_rule(self, self.initialize, self._parent(), ctr)
  File "C:\Users\Joey\Python37\lib\site-packages\pyomo\core\base\misc.py", line 61, in apply_indexed_rule
    return rule(model, index)
  File "<stdin>", line 1, in <lambda>
IndexError: list index out of range

所以您必须使用

model.E = pe.Set(initialize=
    (edges[i] for i in range(len(edges))), dimen=2) # Edge set