切换到Pyomo-集合的语法问题



我已经使用了代数建模语言AMPL,但现在我正在切换到python和Pyomo。

不过,我对它的语法有点吃力。在AMPL中,我会有这样的东西:

param M; 
param n{i in 0..M};
var b{k in 0..M-1, j in 1..n[k+1]};

如何在Pyomo中实现最后一行?

非常感谢您的帮助,谢谢!

谨致问候,Johannes

欢迎访问本网站。

下面是一个例子,我认为这是你想要的。有许多方法可以在pyomo中构建稀疏集。你可以做到"在侧面";在纯python中(如下面的示例(,使用集合理解或其他方法,或者您可以创建一个返回相同的规则。文档中有一个不错的例子。

# sparse set example
import pyomo.environ as pyo
M = 4
mdl = pyo.ConcreteModel('sparse set example')
mdl.A =  pyo.Set(initialize=range(M))
sparse_index = {(k, j) for k in mdl.A for j in range(1, k+1)}    # just a little helper set-comprehension
mdl.LT = pyo.Set(within=mdl.A * mdl.A, initialize=sparse_index)  # "within" is optional...good for error checking
mdl.x =  pyo.Var(mdl.LT, domain=pyo.NonNegativeReals)
mdl.pprint()

收益率:

3 Set Declarations
A : Size=1, Index=None, Ordered=Insertion
Key  : Dimen : Domain : Size : Members
None :     1 :    Any :    4 : {0, 1, 2, 3}
LT : Size=1, Index=None, Ordered=Insertion
Key  : Dimen : Domain    : Size : Members
None :     2 : LT_domain :    6 : {(2, 1), (3, 1), (1, 1), (3, 3), (2, 2), (3, 2)}
LT_domain : Size=1, Index=None, Ordered=True
Key  : Dimen : Domain : Size : Members
None :     2 :    A*A :   16 : {(0, 0), (0, 1), (0, 2), (0, 3), (1, 0), (1, 1), (1, 2), (1, 3), (2, 0), (2, 1), (2, 2), (2, 3), (3, 0), (3, 1), (3, 2), (3, 3)}
1 Var Declarations
x : Size=6, Index=LT
Key    : Lower : Value : Upper : Fixed : Stale : Domain
(1, 1) :     0 :  None :  None : False :  True : NonNegativeReals
(2, 1) :     0 :  None :  None : False :  True : NonNegativeReals
(2, 2) :     0 :  None :  None : False :  True : NonNegativeReals
(3, 1) :     0 :  None :  None : False :  True : NonNegativeReals
(3, 2) :     0 :  None :  None : False :  True : NonNegativeReals
(3, 3) :     0 :  None :  None : False :  True : NonNegativeReals
4 Declarations: A LT_domain LT x

最新更新