From 0dffe7f5c57e9cc0fee9c513962d095ab490ec5c Mon Sep 17 00:00:00 2001 From: Anders Kaseorg Date: Tue, 8 Jan 2019 15:21:41 -0800 Subject: [PATCH] python: Allow negated literals in LinearExpression MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Booleans are already considered integers with value 0 or 1, so it’s natural to expect negated booleans to be considered integers with value 1 or 0. This makes it more convenient to define an antisymmetric array of booleans: you no longer have to choose between not being able to use greater[j, i] = greater[i, j].Not() in linear expressions and not being able to use greater[j, i] = 1 - greater[i, j] in boolean constraints. Signed-off-by: Anders Kaseorg --- ortools/sat/python/cp_model.py | 9 ++++----- 1 file changed, 4 insertions(+), 5 deletions(-) diff --git a/ortools/sat/python/cp_model.py b/ortools/sat/python/cp_model.py index 02e5c5acb1..a31aa2466d 100644 --- a/ortools/sat/python/cp_model.py +++ b/ortools/sat/python/cp_model.py @@ -131,8 +131,8 @@ class LinearExpression(object): elif isinstance(expr, IntVar): coeffs[expr] += coef elif isinstance(expr, _NotBooleanVariable): - raise TypeError( - 'Cannot interpret literals in a linear expression.') + constant += coef + coeffs[expr.Not()] -= coef else: raise TypeError('Unrecognized linear expression: ' + str(expr)) @@ -1346,7 +1346,7 @@ def EvaluateLinearExpression(expression, solution): elif isinstance(expr, IntVar): value += coef * solution.solution[expr.Index()] elif isinstance(expr, _NotBooleanVariable): - raise TypeError('Cannot interpret literals in a linear expression.') + value += coef * (1 - solution.solution[expr.Not().Index()]) return value @@ -1539,8 +1539,7 @@ class CpSolverSolutionCallback(pywrapsat.SolutionCallback): elif isinstance(expr, IntVar): value += coef * self.SolutionIntegerValue(expr.Index()) elif isinstance(expr, _NotBooleanVariable): - raise TypeError( - 'Cannot interpret literals in a linear expression.') + value += coef * (1 - self.SolutionIntegerValue(expr.Not().Index())) return value