dimod.ConstrainedQuadraticModel.violations#

ConstrainedQuadraticModel.violations(sample_like: Sequence[float | floating | integer] | Mapping[Hashable, float | floating | integer] | Tuple[Sequence[float | floating | integer], Sequence[Hashable]] | Tuple[ndarray, Sequence[Hashable]] | ndarray | Sequence[Sequence[float | floating | integer]] | Tuple[Sequence[Sequence[float | floating | integer]], Sequence[Hashable]] | Sequence[Sequence[float | floating | integer] | Mapping[Hashable, float | floating | integer] | Tuple[Sequence[float | floating | integer], Sequence[Hashable]] | Tuple[ndarray, Sequence[Hashable]] | ndarray] | Iterator[Sequence[float | floating | integer] | Mapping[Hashable, float | floating | integer] | Tuple[Sequence[float | floating | integer], Sequence[Hashable]] | Tuple[ndarray, Sequence[Hashable]] | ndarray], *, skip_satisfied: bool = False, clip: bool = False) Dict[Hashable, float | floating | integer][source]#

Return a dict of violations for all constraints.

The dictionary maps constraint labels to the amount each constraint is violated. This method is a shortcut for dict(cqm.iter_violations(sample)).

Parameters:
  • sample_like – A sample. sample-like is an extension of NumPy’s array_like structure. See as_samples()..

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

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

Returns:

A dict of 2-tuples containing the constraint label and the amount of the constraint’s violation.

Examples

This example meets one constraint exactly, is well within the requirement of a second, and violates a third.

>>> 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'
>>> sample = {"i": 3, "j": 2, "k": 5}
>>> cqm.violations(sample)
{'equal': 0.0, 'less equal': -10.0, 'greater equal': 3.0}