dimod.cqm_to_bqm

cqm_to_bqm(cqm: dimod.constrained.ConstrainedQuadraticModel, lagrange_multiplier: Optional[Union[int, float, numpy.number]] = None) Tuple[dimod.binary.binary_quadratic_model.BinaryQuadraticModel, dimod.constrained.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 binary quadratic model

A function that converts samples over the binary quadratic model back into samples for the constrained quadratic model.

Return type

A 2-tuple containing

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}