如何使用 for 循环编写 Pyomo 变量

How to write Pyomo variables with for loops

我正在尝试编写一个 Pyomo 模型,其中我有一组变量,由 {1,2,...,N} 中的 j 索引,并且对于每个 j,{1,.. .,N_j}.

我现在的代码是:

n0=28
n1=8
n2=8
n3=8
n4=10

N=[n0, n1, n2, n3, n4]
rN=range(5)

model = ConcreteModel()

model.J = [RangeSet(1,N[i]) for i in rN]
model.X = [Var(model.J[i], within=NonNegativeReals) for i in rN]

当我尝试访问变量时,出现错误:

>>>model.X[0][0]
Traceback (most recent call last):

  File "<ipython-input-177-297a76d94388>", line 1, in <module>
    model.X[0][0]

  File "/path/anaconda3/lib/python3.7/site- 
packages/pyomo/core/base/indexed_component.py", line 374, in __getitem__
    self._not_constructed_error(index)

  File "/path/anaconda3/lib/python3.7/site- 
   packages/pyomo/core/base/indexed_component.py", line 520, in _not_constructed_error
    "not been constructed." % (self.name, idx_str,))

ValueError: Error retrieving component IndexedVar[1]: The component has not been constructed.

我认为错误可能是我无法在列表中写入变量,但我想不出任何其他解决方案。

你有 2 个选择....要么用你想要的索引手动构建一个集合(我下面的例子)并在整个模型中使用它,要么你可以(小心地)只 create/call 合法通过循环或动态创建合法索引来使用 IJ 时的索引。

# ragged set
from pyomo.environ import *

model = ConcreteModel()

# SETS
model.J = Set(initialize=range(3))
model.I = Set(initialize=range(3))

# construct the ragged set
ij = [(i, j) for j in range(3) for i in range(j + 1)]
model.IJ = Set(within=model.I * model.J, initialize=ij)

# VARIABLE
model.x = Var(model.IJ, domain=NonNegativeReals)

model.pprint()

产量:

4 Set Declarations
    I : Dim=0, Dimen=1, Size=3, Domain=None, Ordered=False, Bounds=(0, 2)
        [0, 1, 2]
    IJ : Dim=0, Dimen=2, Size=6, Domain=IJ_domain, Ordered=False, Bounds=None
        [(0, 0), (0, 1), (0, 2), (1, 1), (1, 2), (2, 2)]
    IJ_domain : Dim=0, Dimen=2, Size=9, Domain=None, Ordered=False, Bounds=None
        Virtual
    J : Dim=0, Dimen=1, Size=3, Domain=None, Ordered=False, Bounds=(0, 2)
        [0, 1, 2]

1 Var Declarations
    x : Size=6, Index=IJ
        Key    : Lower : Value : Upper : Fixed : Stale : Domain
        (0, 0) :     0 :  None :  None : False :  True : NonNegativeReals
        (0, 1) :     0 :  None :  None : False :  True : NonNegativeReals
        (0, 2) :     0 :  None :  None : False :  True : NonNegativeReals
        (1, 1) :     0 :  None :  None : False :  True : NonNegativeReals
        (1, 2) :     0 :  None :  None : False :  True : NonNegativeReals
        (2, 2) :     0 :  None :  None : False :  True : NonNegativeReals

5 Declarations: J I IJ_domain IJ x
[Finished in 2.5s]