dimod.ConstrainedQuadraticModel.iter_constraint_data#

ConstrainedQuadraticModel.iter_constraint_data(sample_like: SamplesLike, *, labels: Optional[Iterable[Hashable]] = None) Iterator[ConstraintData][source]#

Yield information about the constraints for the given sample.

Note that this method iterates over constraints in the same order as they appear in constraints.

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

  • labels – A subset of the constraint labels over which to iterate.

Yields:

A collections.namedtuple with the following fields.

  • label: Constraint label.

  • lhs_energy: Energy of the left-hand side of the constraint.

  • rhs_energy: Energy of the right-hand side of the constraint.

  • sense: dimod.sym.Sense of the constraint.

  • activity: Equals lhs_energy - rhs_energy.

  • violation: Ammount by which the constraint is violated, if positive, or satisfied, if negative. Determined by the type of constraint.

Examples

The sample in this example sets a value of 2 for two constraints, \(i \le 3\) and \(j \ge 3\), which satisfies the first and violates the second by the same ammount, flipping the sign of the violation field.

>>> cqm = dimod.ConstrainedQuadraticModel()
>>> i, j = dimod.Integers(["i", "j"])
>>> cqm.add_constraint_from_comparison(i <= 3, label="Upper limit")
'Upper limit'
>>> cqm.add_constraint_from_comparison(j >= 3, label="Lower limit")
'Lower limit'
>>> for constraint in cqm.iter_constraint_data({"i": 2, "j": 2}):
...     print(constraint.label, constraint.violation)
Upper limit -1.0
Lower limit 1.0