【问题标题】:Switching to Pyomo - Syntax issue with sets切换到 Pyomo - 集合的语法问题
【发布时间】:2021-07-10 08:48:56
【问题描述】:

我使用过代数建模语言 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 中实现最后一行?

非常感谢任何帮助,谢谢!

最好的问候, 约翰内斯

【问题讨论】:

    标签: python pyomo ampl


    【解决方案1】:

    欢迎来到本站。

    以下是我认为可以满足您要求的示例。在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
    

    【讨论】:

    • 非常感谢!我会试试看,这看起来很有希望:)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-03-19
    • 1970-01-01
    • 2021-03-10
    • 1970-01-01
    • 2013-07-26
    相关资源
    最近更新 更多