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.
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 to be true exactly when an integer variable equals a fixed value .
In CP-SAT, the biconditional is enforced as two implications:
We post each implication with OnlyEnforceIf:
model.Add(x == v).OnlyEnforceIf(b)
model.Add(x != v).OnlyEnforceIf(b.Not())
The first line says: when is true, then . The second says: when is false, then . Together they make track the truth value of in every solution. Posting only one of the two lines leaves the other direction unconstrained and is a frequent modeling bug.