使用集合切换到Pyomo语法问题

2024-06-16 08:44:33 发布

您现在位置:Python中文网/ 问答频道 /正文

我已经使用了代数建模语言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中的最后一行

非常感谢您的帮助,谢谢

致以最良好的祝愿, 约翰尼斯


Tags: in内容paramvar语法pyomo代数我会
1条回答
网友
1楼 · 发布于 2024-06-16 08:44:33

欢迎来到这个网站

下面是一个例子,我认为这是你想要的。有很多方法可以在pyomo中构建稀疏集。您可以在纯python(如下面的示例)中使用集合理解或其他方法“在一旁”完成,或者您可以创建一个返回相同结果的规则。在documentation中有一个不错的例子

# 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

相关问题 更多 >