如何使用 Pyomo 创建索引 VarList?

问题描述 投票:0回答:1

我知道

VarList
用于在
Pyomo
中动态添加变量。但我从未见过允许使用索引“即时”添加变量的 VarList。

下面我展示了实际和期望的行为:

import pyomo.environ as pe

### actual behavior
m = pe.ConcreteModel()
m.x = pe.VarList()
for i in range(2):
    for j in range(2):
        new_v = m.x.add()

print(list(m.x._index_set))
### desired behavior
m = pe.ConcreteModel()
m.x = pe.VarList()
for i in range(2):
    for j in range(2):
        new_v = m.x.add((i,j))

print(list(m.x._index_set))
### ideally this would print: [(0,0), (1,0), (0,1), (1,1)]

这样的功能将允许我将来访问

VarList
,如下所示:
m.x[i,j]

我见过这个问题:Pyomo 和 VarList - 自动生成变量,但它在答案中没有使用 VarList,因此不支持动态添加变量。

python pyomo
1个回答
0
投票

简短的回答是,您无法创建索引

VarList
组件。原因归结为 Pyomo 如何实现索引集:对于“索引 VarList”,您确实需要一组独立的集合(Pyomo 支持) - 但您希望通过集合的集合来索引 Var(Pyomo 当前所做的)由于多种原因不支持)。

也就是说,您可以通过使用非有限集对 Var 进行索引来获得(几乎完全)您想要的行为:

>>> m = ConcreteModel()
>>> m.x = Var(PositiveIntegers, PositiveIntegers, dense=False)
>>> m = ConcreteModel()
>>> m.x = Var(NonNegativeIntegers, NonNegativeIntegers, dense=False)
>>> for i in range(2):
...     for j in range(2):
...         new_v = m.x[i,j] = 0
...
>>> m.x.pprint()
x : Size=4, Index=x_index
    Key    : Lower : Value : Upper : Fixed : Stale : Domain
    (0, 0) :  None :     0 :  None : False : False :  Reals
    (0, 1) :  None :     0 :  None : False : False :  Reals
    (1, 0) :  None :     0 :  None : False : False :  Reals
    (1, 1) :  None :     0 :  None : False : False :  Reals
© www.soinside.com 2019 - 2024. All rights reserved.