Utilities

Decorators

bqm_index_labels(f) Decorator to convert a BQM to index-labels and relabel the sample set output.
bqm_index_labelled_input(…) Returns a decorator that ensures BQM variable labeling and specified sample_like inputs are index labeled and consistent.
bqm_structured(f) Decorator to raise an error if the given BQM does not match the sampler’s structure.
graph_argument(*arg_names, **options) Decorator to coerce given graph arguments into a consistent form.
nonblocking_sample_method(f) Decorator to create non-blocking sample methods.
vartype_argument(*arg_names) Ensures the wrapped function receives valid vartype argument(s).

Energy Calculations

ising_energy(sample, h, J[, offset]) Calculate the energy for the specified sample of an Ising model.
qubo_energy(sample, Q[, offset]) Calculate the energy for the specified sample of a QUBO model.

Graph-like

child_structure_dfs(sampler[, seen]) Return the structure of a composed sampler using a depth-first search on its children.

Serialization

COOrdinate

A simple text encoding of dimod BQMs.

The COOrdinate list is a sparse matrix representation which can be used to store binary quadratic models. This format is best used when readability is important.

Note that this format only works for BQMs that are labelled with positive integers.

Examples

>>> from dimod.serialization import coo

Serialize a QUBO.

>>> Q = {(0, 0): -1, (0, 1): 1, (1, 2): -4.5}
>>> bqm = dimod.BinaryQuadraticModel.from_qubo(Q)
>>> print(coo.dumps(bqm))
0 0 -1.000000
0 1 1.000000
1 2 -4.500000

We can also include the vartype as a header.

>>> Q = {(0, 0): -1, (0, 1): 1, (1, 2): -4.5}
>>> bqm = dimod.BinaryQuadraticModel.from_qubo(Q)
>>> print(coo.dumps(bqm, vartype_header=True))
# vartype=BINARY
0 0 -1.000000
0 1 1.000000
1 2 -4.500000

Loading from a COO string. Note that you must specify a vartype.

>>> coo_string = '''
... 0 0 -1
... 0 1 1
... 1 2 -4.5
... '''
>>> coo.loads(coo_string, vartype=dimod.BINARY)
BinaryQuadraticModel({0: -1.0, 1: 0.0, 2: 0.0}, {(0, 1): 1.0, (1, 2): -4.5}, 0.0, 'BINARY')

Or provide the vartype as a header.

>>> coo_string = '''
... # vartype=BINARY
... 0 0 -1
... 0 1 1
... 1 2 -4.5
... '''
>>> coo.loads(coo_string)
BinaryQuadraticModel({0: -1.0, 1: 0.0, 2: 0.0}, {(0, 1): 1.0, (1, 2): -4.5}, 0.0, 'BINARY')
dump(bqm, fp[, vartype_header]) Dump a binary quadratic model to a file in COOrdinate format.
dumps(bqm[, vartype_header]) Dump a binary quadratic model to a string in COOrdinate format.
load(fp[, cls, vartype]) Load a COOrdinate formatted binary quadratic model from a file.
loads(s[, cls, vartype]) Load a COOrdinate formatted binary quadratic model from a string.

FileView

A format for saving large binary quadratic models.

This format is inspired by the NPY format

Extension Convention

Binary quadratic models are typically saved using the .bqm extension.

Format Version 1.0

Format specification:

The first 8 bytes are a magic string: exactly “DIMODBQM”.

The next 1 byte is an unsigned byte: the major version of the file format.

The next 1 byte is an unsigned byte: the minor version of the file format.

The next 4 bytes form a little-endian unsigned int, the length of the header data HEADER_LEN.

The next HEADER_LEN bytes form the header data. This is a json-serialized dictionary. The dictionary is exactly:

dict(shape=bqm.shape,
     dtype=bqm.dtype.name,
     itype=bqm.itype.name,
     ntype=bqm.ntype.name,
     vartype=bqm.vartype.name,
     type=type(bqm).__name__,
     variables=list(bqm.variables),
     )

it is terminated by a newline character and padded with spaces to make the entire length of the entire header divisible by 16.

The binary quadratic model data comes after the header. The number of bytes can be determined by the data types and the number of variables and number of interactions (described in the shape).

The first dtype.itemsize bytes are the offset. The next num_variables * (ntype.itemsize + dtype.itemsize) bytes are the linear data. The linear data includes the neighborhood starts and the biases. The final `2 * num_interactions * (itype.itemsize + dtype.itemsize) bytes are the quadratic data. Stored as `(outvar, bias) pairs.

Format Version 2.0

In order to make the header a more reasonable length, the variable labels have been moved to the body. The variables field of the header dictionary now has a boolean value, making the dictionary:

dict(shape=bqm.shape,
     dtype=bqm.dtype.name,
     itype=bqm.itype.name,
     ntype=bqm.ntype.name,
     vartype=bqm.vartype.name,
     type=type(bqm).__name__,
     variables=any(v != i for i, v in enumerate(bqm.variables)),
     )

If the BQM is index-labeled, then no additional data is added. Otherwise, a new section is appended after the bias data.

The first 4 bytes are exactly “VARS”.

The next 4 bytes form a little-endian unsigned int, the length of the variables array VARIABLES_LENGTH.

The next VARIABLES_LENGTH bytes are a json-serialized array. As constructed by `json.dumps(list(bqm.variables)). The variables section is padded with spaces to make the entire length of divisible by 16.

Future

If more sections are required in the future, they should be structured like the variables section from Version 2.0, i.e. a 4 byte section identifier and 4 bytes of length.

FileView(bqm[, version, ignore_labels]) A seekable, readable view into a binary quadratic model.
load(fp[, cls]) Load a binary quadratic model from a file.

JSON

JSON-encoding of dimod objects.

Examples

>>> import json
>>> from dimod.serialization.json import DimodEncoder, DimodDecoder
...
>>> bqm = dimod.BinaryQuadraticModel.from_ising({}, {('a', 'b'): -1})
>>> s = json.dumps(bqm, cls=DimodEncoder)
>>> new = json.loads(s, cls=DimodDecoder)
>>> bqm == new
True
>>> import json
>>> from dimod.serialization.json import DimodEncoder, DimodDecoder
...
>>> sampleset = dimod.SampleSet.from_samples({'a': -1, 'b': 1}, dimod.SPIN, energy=5)
>>> s = json.dumps(sampleset, cls=DimodEncoder)
>>> new = json.loads(s, cls=DimodDecoder)
>>> sampleset == new
True
>>> import json
>>> from dimod.serialization.json import DimodEncoder, DimodDecoder
...
>>> # now inside a list
>>> s = json.dumps([sampleset, bqm], cls=DimodEncoder)
>>> new = json.loads(s, cls=DimodDecoder)
>>> new == [sampleset, bqm]
True
DimodEncoder(*[, skipkeys, ensure_ascii, …]) Subclass the JSONEncoder for dimod objects.
DimodDecoder(*args, **kwargs) Subclass the JSONDecoder for dimod objects.
dimod_object_hook(obj) JSON-decoding for dimod objects.

Testing

The testing subpackage contains functions for verifying and testing dimod objects. Testing objects/functions can be imported from the dimod.testing namespace. For example:

>>> from dimod.testing import assert_sampler_api

API Asserts

assert_composite_api(composed_sampler) Assert that an instantiated composed sampler exposes correct composite properties and methods.
assert_sampler_api(sampler) Assert that an instantiated sampler exposes correct properties and methods.
assert_structured_api(sampler) Assert that an instantiated structured sampler exposes correct composite properties and methods.

Correctness Asserts

assert_bqm_almost_equal(actual, desired[, …]) Test if two binary quadratic models have almost equal biases.
assert_response_energies(response, bqm[, …]) Assert that each sample in the given response has the correct energy.
assert_sampleset_energies(sampleset, bqm[, …]) Assert that each sample in the given sample set has the correct energy.

Test Case Loader

load_sampler_bqm_tests(sampler[, …]) Populate the decorated TestCase with sampler tests using small BQMs.

Vartype Conversion

ising_to_qubo(h, J[, offset]) Convert an Ising problem to a QUBO problem.
qubo_to_ising(Q[, offset]) Convert a QUBO problem to an Ising problem.