我想测试两个 pyomo 表达式是否具有相同的表达式树。我想这样做是因为我正在编写单元测试以确保程序在模型中创建正确的约束。
现在,我正在比较两个表达式的字符串表示。但我认为这种方法是脆弱的,原因有二。首先,数值误差可能会使两个约束看起来不同。例如,我们可以有两个相同的约束,但一个约束为 0.00,另一个约束为 0.0001。其次,我也不知道pyomo.core.expr
模块的API是否稳定,因为文档(link)的developer reference
部分有描述。
测试两个表达式是否具有相同的表达式树的好方法是什么?
目前的解决方案:
from pyomo.core.expr import current as pyo_expr
import pyomo.environ as pyo
def assert_same_expression(expr1, expr2):
x = [pyo_expr.expression_to_string(e) for e in (expr1, expr2)]
msg = "The string representations of the two expressions are:\n" \
" {0}\n" \
" {1},\n" \
"which are not the same.".format(x[0], x[1])
assert x[0] == x[1], msg
def main():
m = pyo.ConcreteModel()
m.x = pyo.Var()
m.y = pyo.Var()
expr1 = m.x > m.y
expr2 = m.x < m.y
assert_same_expression(expr1, expr2)
main()