如何在 pyomo 中检索 objective 函数的含义

How to retrieve the sense of an objective function in pyomo

所以问题如下:

我正在研究一种算法,其中一个参数是优化问题是最大化问题还是最小化问题。从优化模型来看,代码如下所示:

model.obj = pyo.Objective(expr= sum(model.c[i]*model.x[i] for i in model.i),
                      sense=maximize)

pprint() 的输出如下所示:

obj : Size=1, Index=None, Active=True
Key  : Active : Sense    : Expression
None :   True : maximize : 1.2*x[1] + 2*x[2]

如何从 model.obj 中检索元素“最大化”?

pyo.Objective 模型对象似乎包含您要查找的属性。在 ipython 中进行了一些探索之后:

In [1]: import pyomo.environ as pyo

In [2]: m = pyo.ConcreteModel()

In [3]: m.obj = pyo.Objective(expr=1, sense=pyo.maximize)

In [4]: m.pprint()
1 Objective Declarations
    obj : Size=1, Index=None, Active=True
        Key  : Active : Sense    : Expression
        None :   True : maximize :        1.0

1 Declarations: obj

In [5]: m.obj.sense
Out[5]: -1

In [6]: m.obj = pyo.Objective(expr=1, sense=pyo.minimize)
WARNING: Implicitly replacing the Component attribute obj (type=<class
    'pyomo.core.base.objective.ScalarObjective'>) on block unknown with a new
    Component (type=<class 'pyomo.core.base.objective.ScalarObjective'>). This
    is usually indicative of a modelling error. To avoid this warning, use
    block.del_component() and block.add_component().

In [7]: m.obj.sense
Out[7]: 1