Access all variables occurring in a pyomo constraint

后端 未结 2 948
日久生厌
日久生厌 2020-12-17 07:39

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

相关标签:
2条回答
  • 2020-12-17 07:53

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

    0 讨论(0)
  • 2020-12-17 08:20

    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))
    
    0 讨论(0)
提交回复
热议问题