or-toolscp-sat

How to add a constraint that a linear expression is outside bounds that are variables?


I want to add the constraint that abs(x) >= y with x and y being variables. The following code fails because AddBoolOr doesn't suppport BoundedLinearExpression as arguments.

model = cp_model.CpModel()

x = model.NewIntVar(-10, 10, 'x')  # Example domain for x
y = model.NewIntVar(0, 10, 'y')  # Example domain for y, ensuring y is non-negative

model.AddBoolOr(x < -y, x > y)

Solution

  •    abs_x = model.new_int_var(0, 10, 'abs_x')
       model.add_abs_equality(abs_x, x)
       model.add(abs_x > y)
    

    or

       b = model.new_bool_var('abs_x gt y')
       model.add(x > y).only_enforce_if(b)
       model.add(x < -y).only_enforce_if(~b)