dimod.ConstrainedQuadraticModel.iter_violations

ConstrainedQuadraticModel.iter_violations(sample_like, *, skip_satisfied: bool = False, clip: bool = False) Iterator[Tuple[Hashable, Union[int, float, numpy.number]]][source]

Yield violations for all constraints.

Parameters
  • sample_like – A sample over the CQM variables.

  • skip_satisfied – If True, does not yield constraints that are satisfied.

  • clip – If True, negative violations are rounded up to 0.

Yields

A 2-tuple containing the constraint label and the amount of constraints violation.

Example

Construct a constrained quadratic model.

>>> i, j, k = dimod.Binaries(['i', 'j', 'k'])
>>> cqm = dimod.ConstrainedQuadraticModel()
>>> cqm.add_constraint(i + j + k == 10, label='equal')
'equal'
>>> cqm.add_constraint(i + j <= 15, label='less equal')
'less equal'
>>> cqm.add_constraint(j - k >= 0, label='greater equal')
'greater equal'

Check the violations of a sample that satisfies all constraints.

>>> sample = {'i': 3, 'j': 5, 'k': 2}
>>> for label, violation in cqm.iter_violations(sample, clip=True):
...     print(label, violation)
equal 0.0
less equal 0.0
greater equal 0.0

Check the violations for a sample that does not satisfy all of the constraints.

>>> sample = {'i': 3, 'j': 2, 'k': 5}
>>> for label, violation in cqm.iter_violations(sample, clip=True):
...     print(label, violation)
equal 0.0
less equal 0.0
greater equal 3.0
>>> sample = {'i': 3, 'j': 2, 'k': 5}
>>> for label, violation in cqm.iter_violations(sample, skip_satisfied=True):
...     print(label, violation)
greater equal 3.0