为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

萧十郎 2023-05-09 10:38:59
我正在尝试编写一个 Pyomo 模型,其中我有一组变量,由 {1,2,...,N} 中的 aj 索引,并且对于每个 j,{1,...,N_j} 中的 ai。我现在的代码是:n0=28n1=8n2=8n3=8n4=10N=[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.我认为错误可能是我无法在列表中写入变量,但我想不出任何其他解决方案。
查看完整描述

1 回答

?
明月笑刀无情

TA贡献1828条经验 获得超4个赞

你有 2 个选择....要么用你想要的索引手动构建一个集合(我下面的例子)并在整个模型中使用它,或者你可以(小心地)只在你使用和循环时创建/调用I合法J索引或即时制作合法索引。


# 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]


查看完整回答
反对 回复 2023-05-09
  • 1 回答
  • 0 关注
  • 79 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信