I am working on an algorithm in python that needs to modify concrete (mixed-integer nonlinear) pyomo models. In particular, I need to know which variables are present in a
model.con1.body._args
gives you just this list of variables.
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))