Using external functions within Pyomo constraints

Viewed 27

I need to use an external python function to create a constraint in a pyomo model, but I do not trust that it works as it should. E.g. if I have the following external function

# External function
def total_cost(length, flow):
    return length * floww * 1000

and then I want to call it when creating a pyomo model object but 'length' and 'flow' values are variables within my model, will that work as it should? Anyone has any experience with this?

1 Answers

Your example should work fine for most cases. There are three exceptions you want to watch out for (but these apply to normal constraint rules as well):

  1. Don't explicitly take the value of a variable when building a constraint expression because the variable will be replaced with a constant numeric value in the expression tree (and not sent to the solver)
  2. Don't write conditionals (if-statements) that depend on the value of a variable
  3. Only use Pyomo provided intrinsic math functions (sin, cos, exp, etc.) when writing constraints

I also recommend calling pprint on your constraint after it has been constructed to verify that the constraint expression is what you expect. If the constraint is too long/messy then you could print the subexpressions returned by your functions and verify that you are getting Pyomo expression objects rather than constant numeric values.

Related