简体   繁体   English

在 Pyomo 约束中使用外部函数

[英]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.我需要使用外部 python function 在 pyomo model 中创建约束,但我不相信它可以正常工作。 Eg if I have the following external function例如,如果我有以下外部 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?然后我想在创建 pyomo model object 时调用它,但“长度”和“流量”值是我的 model 中的变量,它会正常工作吗? 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)构建约束表达式时不要显式获取变量的value ,因为该变量将被表达式树中的常量数值替换(而不是发送到求解器)
  2. Don't write conditionals (if-statements) that depend on the value of a variable不要编写依赖于变量值的条件(if 语句)
  3. Only use Pyomo provided intrinsic math functions (sin, cos, exp, etc.) when writing constraints编写约束时仅使用 Pyomo 提供的内在数学函数(sin、cos、exp 等)

I also recommend calling pprint on your constraint after it has been constructed to verify that the constraint expression is what you expect.我还建议在构造约束后调用pprint来验证约束表达式是否符合您的期望。 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.如果约束太长/太乱,那么您可以print函数返回的子表达式并验证您获得的是 Pyomo 表达式对象而不是常量数值。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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