From b6ad0e834be425b8319f986699c5775d049dd47d Mon Sep 17 00:00:00 2001 From: Michael Bynum Date: Fri, 23 Apr 2021 12:42:25 -0600 Subject: [PATCH 1/2] reduce errors logged with value when exception is False --- pyomo/core/expr/visitor.py | 9 ++++++--- 1 file changed, 6 insertions(+), 3 deletions(-) diff --git a/pyomo/core/expr/visitor.py b/pyomo/core/expr/visitor.py index 0d362ae5dc8..21038dbf320 100644 --- a/pyomo/core/expr/visitor.py +++ b/pyomo/core/expr/visitor.py @@ -929,6 +929,9 @@ def accept(node, data, child_result, child_idx): class _EvaluationVisitor(ExpressionValueVisitor): + def __init__(self, exception): + self.exception = exception + def visit(self, node, values): """ Visit nodes that have been expanded """ return node._apply_operation(values) @@ -946,9 +949,9 @@ def visiting_potential_leaf(self, node): return False, None if node.is_numeric_type(): - return True, value(node) + return True, value(node, exception=self.exception) elif node.is_logical_type(): - return True, value(node) + return True, value(node, exception=self.exception) else: return True, node @@ -1036,7 +1039,7 @@ def evaluate_expression(exp, exception=True, constant=False): if constant: visitor = _EvaluateConstantExpressionVisitor() else: - visitor = _EvaluationVisitor() + visitor = _EvaluationVisitor(exception=exception) try: return visitor.dfs_postorder_stack(exp) From 26b6f5850a47806a5baf17e221c5928da48b6032 Mon Sep 17 00:00:00 2001 From: Michael Bynum Date: Mon, 26 Apr 2021 12:03:32 -0600 Subject: [PATCH 2/2] ensure errors are not logged when using exception=False --- pyomo/core/tests/unit/test_numeric_expr.py | 14 ++++++++++++++ 1 file changed, 14 insertions(+) diff --git a/pyomo/core/tests/unit/test_numeric_expr.py b/pyomo/core/tests/unit/test_numeric_expr.py index 82da1cbcf98..4a1ebd4152e 100644 --- a/pyomo/core/tests/unit/test_numeric_expr.py +++ b/pyomo/core/tests/unit/test_numeric_expr.py @@ -22,6 +22,8 @@ from filecmp import cmp import pyomo.common.unittest as unittest +from pyomo.common.log import LoggingIntercept +from io import StringIO from pyomo.environ import ConcreteModel, AbstractModel, RangeSet, Var, Param, Set, Constraint, ConstraintList, Expression, Objective, Reals, ExternalFunction, PositiveReals, log10, exp, floor, ceil, log, cos, sin, tan, acos, asin, atan, sinh, cosh, tanh, acosh, asinh, atanh, sqrt, value, quicksum, sum_product, is_fixed, is_constant from pyomo.kernel import variable, expression, objective @@ -5244,5 +5246,17 @@ def con_rule(model): self.assertEqual(polynomial_degree(m.c1.body), 1) +class TestEvaluation(unittest.TestCase): + def test_log_error(self): + m = ConcreteModel() + m.x = Var() + e = m.x**2 + os = StringIO() + with LoggingIntercept(os, 'pyomo'): + e_val = value(e, exception=False) + self.assertIsNone(e_val) + self.assertEqual(os.getvalue(), '') + + if __name__ == "__main__": unittest.main()