Channeling Between Integer and Boolean Variables

How to link an integer variable to one or more Boolean indicator variables in CP-SAT using OnlyEnforceIf, covering equality indicators, threshold indicators, one-hot encodings, and counting via channeled Booleans.

Step 1 of 157%

Tutorial

Introduction to Channeling

A channeling constraint links an integer variable to one or more Boolean variables so that the Boolean reflects some property of the integer. The most basic case is the equality indicator: we want a Boolean bb to be true exactly when an integer variable xx equals a fixed value vv.

In CP-SAT, the biconditional b(x=v)b \Leftrightarrow (x = v) is enforced as two implications:

b(x=v)and¬b(xv).b \Rightarrow (x = v) \qquad \text{and} \qquad \neg b \Rightarrow (x \neq v).

We post each implication with OnlyEnforceIf:

model.Add(x == v).OnlyEnforceIf(b)
model.Add(x != v).OnlyEnforceIf(b.Not())

The first line says: when bb is true, then x=vx = v. The second says: when bb is false, then xvx \neq v. Together they make bb track the truth value of x=vx = v in every solution. Posting only one of the two lines leaves the other direction unconstrained and is a frequent modeling bug.

navigate · Enter open · Esc close · ⌘K/Ctrl K toggle