【问题标题】:Pyomo constraints - 'list' object has no attributePyomo 约束 - 'list' 对象没有属性
【发布时间】:2021-12-26 16:03:38
【问题描述】:

我正在创建一个 pyomo 约束,以便在每个 t 值处 Eout_pv[t]

在下面的代码中,我首先创建集合、参数、变量。然后我创建约束。

model.T = Set(initialize=df.index.tolist(), ordered=True)
model.PV_gen = Param(model.T, initialize=df.pv_gen.tolist())

model.Eout_pv = Var(model.T, bounds=(0, 100))

def pv_export(model, t):
    return model.Eout_pv[t] <= model.PV_gen[t]   
model.pv_export = Constraint(model.T, rule=pv_export)

当我运行它时,我收到消息“AttributeError: 'list' object has no attribute 'is_expression_type'”

如果有任何帮助,我将不胜感激

下面的完整错误消息

---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
<ipython-input-47-3de19250551e> in <module>
      2 
      3 start_time = time.time()
----> 4 output_df = optimize_year(df, first_model_period, last_model_period, result_time_step)
      5 print("--- %s seconds ---" % (time.time() - start_time))

<ipython-input-47-a84557fa2321> in optimize_year(df, first_model_period, last_model_period, time_step)
     72         return model.Eout_pv[t] <= model.PV_gen[t]
     73 
---> 74     model.pv_export = Constraint(model.T, rule=pv_export)
     75 
     76     def total_export(model, t):

C:\ProgramFiles2\Anaconda\lib\site-packages\pyomo\core\base\block.py in __setattr__(self, name, val)
    541                 # Pyomo components are added with the add_component method.
    542                 #
--> 543                 self.add_component(name, val)
    544             else:
    545                 #

C:\ProgramFiles2\Anaconda\lib\site-packages\pyomo\core\base\block.py in add_component(self, name, val)
   1079                              _blockName, str(data))
   1080             try:
-> 1081                 val.construct(data)
   1082             except:
   1083                 err = sys.exc_info()[1]

C:\ProgramFiles2\Anaconda\lib\site-packages\pyomo\core\base\constraint.py in construct(self, data)
    774             for ndx in self._index:
    775                 try:
--> 776                     tmp = apply_indexed_rule(self,
    777                                              _init_rule,
    778                                              _self_parent,

C:\ProgramFiles2\Anaconda\lib\site-packages\pyomo\core\base\misc.py in apply_indexed_rule(obj, rule, model, index, options)
     59                 return rule(model)
     60             else:
---> 61                 return rule(model, index)
     62         else:
     63             if index.__class__ is tuple:

<ipython-input-47-a84557fa2321> in pv_export(model, t)
     70     def pv_export(model, t):
     71         "Maximum PV export within a single period"
---> 72         return model.Eout_pv[t] <= model.PV_gen[t]
     73 
     74     model.pv_export = Constraint(model.T, rule=pv_export)

pyomo\core\expr\numvalue.pyx in pyomo.core.expr.numvalue.NumericValue.__le__()

pyomo\core\expr\logical_expr.pyx in pyomo.core.expr.logical_expr._generate_relational_expression()

AttributeError: 'list' object has no attribute 'is_expression_type'

【问题讨论】:

    标签: python constraints attributeerror pyomo


    【解决方案1】:

    model.PV_gen 是一个 param,它依赖于 model.T。这意味着对于T 的每个值,PV_gen 都会有一个值。您需要使用dict 而不是list 来初始化参数。例如:

    from pyomo.environ import *
    
    T=[1,2,3]
    PV={1:20, 2:560, 3: 890}
    model=ConcreteModel()
    model.T = Set(initialize=T, ordered=True)
    model.PV_gen = Param(model.T, initialize=PV)
    
    model.Eout_pv = Var(model.T, bounds=(0, 100))
    
    def pv_export(model, t):
        return model.Eout_pv[t] <= model.PV_gen[t]   
    model.pv_export = Constraint(model.T, rule=pv_export)
    

    【讨论】:

    • 非常感谢!它奏效了。我真的很感激。
    【解决方案2】:

    @pybegginer 的回答是完全正确的。但是,我还想指出 Pyomo 对 numpy/pandas 数据类型的原生支持正在改进。在 Pyomo 6.2 中(将于 2021 年 11 月 17 日左右发布);以下(更自然的语法)将起作用:

    from pyomo.common.dependencies import pandas as pd, pandas_available
    from pyomo.environ import *
    df = pd.DataFrame(index=['20-1', '20-2', '20-3'],
                      data={'pv_gen': [1, 2, 4]})
    print(df)
    

    给出:

          pv_gen
    20-1       1
    20-2       2
    20-3       4
    

    然后:

    model = ConcreteModel()
    
    model.T = Set(initialize=df.index, ordered=True)
    model.PV_gen = Param(model.T, initialize=df.pv_gen)
    
    model.Eout_pv = Var(model.T, bounds=(0, 100))
    
    def pv_export(model, t):
        return model.Eout_pv[t] <= model.PV_gen[t]   
    model.pv_export = Constraint(model.T, rule=pv_export)
    
    model.pprint()
    

    会回来

    1 Set Declarations
        T : Size=1, Index=None, Ordered=Insertion
            Key  : Dimen : Domain : Size : Members
            None :     1 :    Any :    3 : {'20-1', '20-2', '20-3'}
    
    1 Param Declarations
        PV_gen : Size=3, Index=T, Domain=Any, Default=None, Mutable=False
            Key  : Value
            20-1 :     1
            20-2 :     2
            20-3 :     4
    
    1 Var Declarations
        Eout_pv : Size=3, Index=T
            Key  : Lower : Value : Upper : Fixed : Stale : Domain
            20-1 :     0 :  None :   100 : False :  True :  Reals
            20-2 :     0 :  None :   100 : False :  True :  Reals
            20-3 :     0 :  None :   100 : False :  True :  Reals
    
    1 Constraint Declarations
        pv_export : Size=3, Index=T, Active=True
            Key  : Lower : Body          : Upper : Active
            20-1 :  -Inf : Eout_pv[20-1] :   1.0 :   True
            20-2 :  -Inf : Eout_pv[20-2] :   2.0 :   True
            20-3 :  -Inf : Eout_pv[20-3] :   4.0 :   True
    

    OP 的原始模型仍然会产生错误;但是,这将是出于不同的原因:使用 model.T = Set(initialize=df.index.tolist(), ordered=True) 初始化 Set 会给出一个带有 DataFrame 索引值的 Set(如上例所示)。但是,当您使用列表初始化索引参数时,列表的“索引”是整数0..len(list_data)-1(即,它是使用dict(enumerate(list_data)) 初始化的简写。因为PV_gen 的索引是DataFrame 的索引列,您最终会遇到错误:

    KeyError: "Index '0' is not valid for indexed component 'PV_gen'"
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-12-10
      • 2021-03-06
      • 2020-08-09
      • 2019-03-19
      • 2021-01-04
      • 2014-06-05
      • 2021-07-26
      • 2019-04-29
      相关资源
      最近更新 更多