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 general algebraic constraint.
E.g. for a constraint
model.con1 = Constraint(expr=exp(model.x_1) + 2*model.x_2 <= 2)
I would like to make a a query (like model.con1.variables
) which returns (a list of) the variables ([model.x_1,model.x_2]
).
In this documentation I find that for linear constraints, the parameter variables
exactly serves my purpose. However, the models I'm working with will also contain general algebraic constraints.
Chapter 14 of this book provides several details for the development of high-level algorithms using pyomo, but I did not find an answer to my question there. The only very clumsy approach I can think of is to use the to_string() method of the expression (returning exp( x_1 ) + x_2 <= 1.0
in our example), and then to search this string for the appearence of all variables. I'm sure there is a much better way using pyomo to access the variables occurring in a constraint.
Note that a similar, but less detailed and unanswered question has already been asked here.
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…