or-toolscp-sat

Implement a sumprod of pairs of newintvar and boolean variables in OR-tools


Is there an OR-tools way to create an equality constraint with a sumprod of pairs of ortools variables (newintvar with boolean var)?

Without having to go through intermediate variables and MultiplicationEquality constraints.

pairlist = [[newintvar1,booleanvar1],
[newintvar2,booleanvar2],
[newintvar3,booleanvar3],
[newintvar4,booleanvar4],
[newintvar5,booleanvar5],...]

add(myNewintvar == sum(a[0]*a[1] for a in pairlist))

Thanks in advance :)


Solution

  • I have added a sample code with an helper function to build the product of a Boolean variable and an integer variable.

    See the product sample.

    The relevant helper is:

    def build_product_var(
        model: cp_model.CpModel, b: cp_model.IntVar, x: cp_model.IntVar, name: str
    ) -> cp_model.IntVar:
        """Builds the product of a Boolean variable and an integer variable."""
        p = model.new_int_var_from_domain(
            cp_model.Domain.from_flat_intervals(x.proto.domain).union_with(
                cp_model.Domain(0, 0)
            ),
            name,
        )
        model.add(p == x).only_enforce_if(b)
        model.add(p == 0).only_enforce_if(~b)
        return p