dimod.generators.binary_encoding#

binary_encoding(v: Hashable, upper_bound: int) BinaryQuadraticModel[source]#

Generate a binary quadratic model encoding an integer.

Parameters:
  • v – Integer variable label.

  • upper_bound – Upper bound on the integer value (inclusive). You can set a lower bound by setting the model’s offset.

Returns:

A binary quadratic model. Variables in the BQM are labelled with tuples with the following two or three values: first, the specified variable label, v; second, the coefficient in the integer encoding; third (only in the tuple representing the most significant bit), a string, 'msb'.

Example

>>> bqm = dimod.generators.binary_encoding('i', 6)
>>> bqm
BinaryQuadraticModel({('i', 1): 1.0, ('i', 2): 2.0, ('i', 3, 'msb'): 3.0}, {}, 0.0, 'BINARY')

You can use a sample to restore the original integer value.

>>> sample = {('i', 1): 1, ('i', 2): 0, ('i', 3, 'msb'): 1}
>>> bqm.energy(sample)
4.0
>>> sum(v[1]*val for v, val in sample.items()) + bqm.offset
4.0

If you wish to encode integers with a lower bound, you can use the binary quadratic model’s offset attribute.

>>> i = dimod.generators.binary_encoding('i', 10) + 5  # integer in [5, 15]

References

[1]: Sahar Karimi, Pooya Ronagh (2017), Practical Integer-to-Binary Mapping for Quantum Annealers. arxiv.org:1706.01945.