dimod.cqm_to_bqm#

cqm_to_bqm(cqm: ConstrainedQuadraticModel, lagrange_multiplier: float | floating | integer | None = None) tuple[BinaryQuadraticModel, CQMToBQMInverter][source]#

Construct a binary quadratic model from a constrained quadratic model.

Parameters:
  • cqm – A constrained quadratic model. All constraints must be linear and all integer variables must have a lower bound of 0.

  • lagrange_multiplier – The penalty strength used when converting constraints into penalty models. Defaults to 10x the largest bias in the objective.

Returns:

A 2-tuple containing a binary quadratic model and a function that converts samples over the binary quadratic model back into samples for the constrained quadratic model.

Example

Start with a constrained quadratic model

>>> num_widget_a = dimod.Integer('num_widget_a', upper_bound=7)
>>> num_widget_b = dimod.Integer('num_widget_b', upper_bound=3)
>>> cqm = dimod.ConstrainedQuadraticModel()
>>> cqm.set_objective(-3 * num_widget_a - 4 * num_widget_b)
>>> cqm.add_constraint(num_widget_a + num_widget_b <= 5, label='total widgets')
'total widgets'

Convert it to a binary quadratic model and solve it using dimod.ExactSolver.

>>> bqm, invert = dimod.cqm_to_bqm(cqm)
>>> sampleset = dimod.ExactSolver().sample(bqm)

Interpret the answer in the original variable classes

>>> invert(sampleset.first.sample)
{'num_widget_a': 2, 'num_widget_b': 3}

Note that the inverter is also serializable.

>>> import json
>>> newinvert = dimod.constrained.CQMToBQMInverter.from_dict(
...     json.loads(json.dumps(invert.to_dict())))
>>> newinvert(sampleset.first.sample)
{'num_widget_a': 2, 'num_widget_b': 3}