如何从索引变量切片中获取pyomo VarData /值?

时间:2019-09-01 21:57:11

标签: python pyomo

我正在使用由多组索引的pyomo变量。我已经沿着一些集合创建了切片,并且希望使用这些切片来访问变量值(给定切片集合的索引)。

我希望可以使用的代码是:

from pyomo.environ import *

m = ConcreteModel()
m.time = Set(initialize=[1,2,3])
m.space = Set(initialize=[1,2,3])
m.comp = Set(initialize=['a','b','c'])
m.v = Var(m.time, m.space, m.comp, initialize=1)
slice = m.v[:, :, 'a']
for x in m.space:
    value_list = []
    for t in m.time:
        value_list.append(slice[t, x].value)
        # write value_list to csv file

但这给了我

>>> value_list
[<pyomo.core.base.indexed_component_slice._IndexedComponent_slice object at 0x7f4db9104a58>, <pyomo.core.base.indexed_component_slice._IndexedComponent_slice object at 0x7f4db9104a58>, <pyomo.core.base.indexed_component_slice._IndexedComponent_slice object at 0x7f4db9104a58>]

而不是我希望的值列表。

是否可以仅从通配符索引访问与变量片相对应的值?

我尝试使用_IndexedComponent_slice的某些方法,但未成功。例如:

>>> for item in slice.wildcard_items(): item
... 
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/home/rparker1/Idaes/pyomo/pyomo/core/base/indexed_component_slice.py", line 194, in <genexpr>
    return ((_iter.get_last_index_wildcards(), _) for _ in _iter)
  File "/home/rparker1/Idaes/pyomo/pyomo/core/base/indexed_component_slice.py", line 350, in __next__
    _comp = _comp.__getitem__( _call[1] )
AttributeError: '_GeneralVarData' object has no attribute '__getitem__'

我希望有一种方法可以给我一个将通配符索引映射到vardata对象的字典,但是找不到。非常感谢找到这样的词典或其他解决方案的帮助。

1 个答案:

答案 0 :(得分:0)

_IndexedComponent_slice对象有些棘手,因为它们旨在与分层模型一起使用。因此,应该将它们更多地看作是特殊的迭代器,而不是字典的视图。尤其是,这些“切片状”对象将__getitem____getattr____call__的分辨率推迟到迭代时间。因此,当您说slice.value时,直到您遍历切片都不会真正进行该属性查找。

获取变量值的最简单方法是遍历切片:

value_list = list(m.v[:, :, 'a'].value)

如果您想要一个可以像字典一样对待的新组件(就像原始的Var一样),那么您想要使用切片创建一个Reference组件:

r = Reference(m.v[:, :, 'a'])

这些对象可以像任何其他组件一样附加到模型,并且(对于常规切片)将采用引用对象的ctype(因此,在这种情况下,r的外观和作用就像Var)。