Access all variables occurring in a pyomo constraint

假装没事ソ 提交于 2019-12-01 01:24:32

You do not want to directly query the _args attribute of the expression returned by model.con1.body. Methods and attributes beginning with an underscore are considered private and should not be used by general users (they are undocumented and subject to change with no notice or deprecation warning). Second, the _args attribute only returns the children of that node in the expression tree. For linear expressions, there is a high probability that those are the variables, but it is not guaranteed. For nonlinear expressions (and general expressions), the members of _args are almost guaranteed to be other expression objects.

You can get the variables that appear in any Pyomo expression using the identify_variables generator:

from pyomo.environ import *
from pyomo.core.base.expr import identify_variables

m = ConcreteModel()
m.x_1 = Var()
m.x_2 = Var()
m.c = Constraint(expr=exp(model.x_1) + 2*model.x_2 <= 2)
vars = list(identify_variables(m.c.body))

model.con1.body._args gives you just this list of variables.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!