简体   繁体   中英

Using external functions within Pyomo constraints

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. Eg 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?

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.

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