dimod.ConstrainedQuadraticModel.add_constraint_from_comparison

ConstrainedQuadraticModel.add_constraint_from_comparison(comp: dimod.sym.Comparison, label: Optional[Hashable] = None, copy: bool = True) Hashable[source]

Add a constraint from a comparison.

Parameters
  • comp – Comparison object.

  • label – Label for the constraint. Must be unique. If no label is provided, one is generated using uuid.

  • copy – If True, the model used in the comparison is copied. You can set to False to improve performance, but subsequently mutating the model can cause issues.

Returns

Label of the added constraint.

Examples

>>> from dimod import ConstrainedQuadraticModel, Integer
>>> i = Integer('i')
>>> cqm = ConstrainedQuadraticModel()
>>> cqm.add_constraint_from_comparison(i <= 3, label='Max i')
'Max i'
>>> print(cqm.constraints["Max i"].to_polystring())
i <= 3

Adding a constraint without copying the comparison’s model requires caution:

>>> cqm.add_constraint_from_comparison(i >= 1, label="Risky constraint", copy=False)
'Risky constraint'
>>> i *= 2
>>> print(cqm.constraints["Risky constraint"].to_polystring())
2*i >= 1