简体   繁体   中英

Is it possible to convert a sympy expression to a pyomo expression?

I'm currently using sympy to parse a string equation and replace the variables with either values or Pyomo variables:

model = pe.ConcreteModel()
model.flow = pe.Var()

DEMAND = 100

equation = sympify('10 * DEMAND * FLOW', evaluate=False)

updated_equation = equation.subs('DEMAND', DEMAND).subs('FLOW', model.flow)

Does anyone know if it is then possible to convert this to a linear expression I can use in a Pyomo model?

Yes: if you look in pyomo.core.expr.sympy_tools , there are two methods:

  • sympyify_expression(expr) will take a Pyomo expression and return a sympy expression, with all Pyomo Var objects replaced by sympy real Symbols, along with a PyomoSympyBimap object that maps the Pyomo Var objects to the corresponding sympy Symbol objects
  • sympy2pyomo_expression(expr, object_map) will take a sympy expression (containing sympy Symbols), along with the PyomoSymbolBimap that relates the Symbols to Pyomo components and will return a native Pyomo expression.

What you are asking for is something slightly different: You are starting with a sympy expression that already contains Pyomo objects. You should be able to adapt the Sympy2PyomoVisitor class to work for your specific use case (you should only need to reimplement the beforeChild method to allow for the presence of Pyomo components)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM