dimod.ConstrainedQuadraticModel.add_discrete_from_iterable#
- ConstrainedQuadraticModel.add_discrete_from_iterable(variables: Iterable[Hashable], label: Hashable | None = None, check_overlaps: bool = True) Hashable [source]#
Add a one-hot constraint from an iterable.
One-hot constraints can represent discrete variables (for example a
color
variable that has values{"red", "blue", "green"}
) by requiring that only one of a set of two or more binary variables is assigned a value of 1.These constraints support only
BINARY
variables and must be disjoint; that is, variables in such a constraint must not be used elsewhere in the model.Constraints added by this method are guaranteed to be satisfied in solutions returned by the
LeapHybridCQMSampler
hybrid sampler.- Parameters:
variables – An iterable of variables.
label – Label for the constraint. Must be unique. If no label is provided, then one is generated using
uuid
.check_overlaps – If True we perform a variable overlap check. In particular, if the variables already exist, we make sure they’re not used in another discrete constraint.
- Returns:
Label of the added constraint.
Examples
>>> cqm = dimod.ConstrainedQuadraticModel() >>> color = ["red", "blue", "green"] >>> for v in color: ... cqm.add_variable('BINARY', v) 'red' 'blue' 'green' >>> cqm.add_discrete(color, label='one-color') 'one-color' >>> print(cqm.constraints['one-color'].to_polystring()) red + blue + green == 1.0