dimod.ConstrainedQuadraticModel.add_constraint_from_comparison#

ConstrainedQuadraticModel.add_constraint_from_comparison(comp: Comparison, label: Hashable | None = None, copy: bool = True, weight: float | None = None, penalty: str = 'linear') Hashable[source]#

Add a constraint from a symbolic comparison.

For a more detailed discussion of symbolic model manipulation, see Symbolic Math.

Parameters:
  • comp – Comparison object, generally constructed using symbolic math. The right-hand side of any symbolic equation must be an integer or float.

  • 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.

  • weight – Weight for a soft constraint. Must be a positive number. If None or float('inf'), the constraint is hard. In feasible solutions, all the model’s hard constraints must be met, while soft constraints might be violated to achieve overall good solutions.

  • penalty – Penalty type for a soft constraint (a constraint with its weight parameter set). Supported values are 'linear' and 'quadratic'. Ignored if weight is None. 'quadratic' is supported for a constraint with binary variables only.

Returns:

Label of the added constraint.

Example

Encode a constraint.

\[x + y + xy <= 1\]

First create the relevant variables and the model.

>>> x, y = dimod.Binaries(['x', 'y'])
>>> cqm = dimod.ConstrainedQuadraticModel()

And add the constraint to the model.

>>> cqm.add_constraint(x + y + x*y <= 1, label='c0')
'c0'
>>> cqm.constraints['c0'].to_polystring()
'x + y + x*y <= 1.0'

Example

Encode a constraint with a symbolic right-hand side.

\[x + y \le x y\]

First create the relevant variables and the model.

>>> x, y = dimod.Binaries(['x', 'y'])
>>> cqm = dimod.ConstrainedQuadraticModel()

Trying to directly compare the left-hand and right-hand side of the equation will raise an error, because the right-hand side is not an integer or float.

>>> try:
...     cqm.add_constraint(x + y <= x * y)
... except TypeError:
...     print("Not allowed!")
Not allowed!

To avoid this, simply subtract the right-hand side from both sides.

\[x + y - xy \le 0\]

The constraint can then be added.

>>> cqm.add_constraint(x + y - x*y <= 0, label="c0")
'c0'