or-toolsconstraint-programmingoperations-researchcp-sat

Model infeasible when fixing some variables in OrTools CP-SAT


I have a boolean variable in Ortools CP-SAT, let's say x. That variable is in a constraint say y = -5 * x. I have two other constraints in the model that are model.Add(y >= 0).OnlyEnforceIf(z) and model.Add(y < 0).OnlyEnforceIf(z.Not()). When I try to fix x = 1 and solve it, I am receiving as answer that the model is infeasible? Does anyone know the reason? I was expecting it to be feasible.


Solution

  • Below code snippet works out for me. I haven't specified the objective function, since I am not sure of it.

    from ortools.sat.python import cp_model as cp
    
    model = cp.CpModel()
    
    x = model.NewBoolVar("")
    model.Add(x == 1)
    
    z = model.NewBoolVar("")
    y = model.NewIntVar(-100, 100, name = "")
    
    model.Add(y == -5 * x)
    
    model.Add(y >= 0).OnlyEnforceIf(z)
    model.Add(y < 0).OnlyEnforceIf(z.Not())
    
    
    solver = cp.CpSolver() 
    # model.Minimize(y)
    solver.Solve(model) # status = 4 => optimal
    
    solver.Value(x) # x = 1
    solver.Value(z) # z = 0
    solver.Value(y) # y = -5