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 objectssympy2pyomo_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)