linear-programmingor-toolsmixed-integer-programmingcp-sat

How to ensure that a value is a member of a set of decision variables in ortools


I want to implement constraints which ensures that a value is part of a set of decision variables. So for e.g. let dv[i] be a set of decision variables indexed by i. Say, the domain is restricted between 0-10. I want that it should be ensured that a value 4 (say) is a member of dv.

from ortools.sat.python import cp_model as cp

model = cp.CpModel()
dv = [model.NewIntVar(lb=0, ub=10, name = f"dv[{_+1}]") for _ in range(5)]

# this val should be a member of dv
val = 4

Solution

  • Below is one possible way to ensure that a pre-determined value is a member of decision variables.

    from ortools.sat.python import cp_model as cp
    
    model = cp.CpModel()
    dv = [model.new_int_var(lb=0, ub=10, name = f"dv[{_+1}]") for _ in range(5)]
    
    val = 4
    
    n = len(dv)
    b = [model.new_bool_var(f"b[{i}]")  for i in range(n)]
    for i in range(n):
        model.add((dv[i] == val)).only_enforce_if(b[i])
        model.add((dv[i] != val)).only_enforce_if(~b[i])
    model.add_bool_or(b)
    
    model.maximize(sum(dv))
    solver = cp.CpSolver()
    status = solver.solve(model)
    
    print([solver.value(dv[i]) for i in range(5)])
    # results in : [10, 10, 10, 10, 4]
    # no constraints are imposed to place 4 in any specific position