ConstrainedQuadraticModel.to_file(*, spool_size: int = 1000000000, compress: bool = False) tempfile.SpooledTemporaryFile[source]

Serialize to a file-like object.

  • spool_size – Defines the max_size passed to the constructor of tempfile.SpooledTemporaryFile. Determines whether the returned file-like’s contents will be kept on disk or in memory.

  • compress – If True, the data will be compressed with zipfile.ZIP_DEFLATED.

Format Specification (Version 1.3):

This format is inspired by the NPY format

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

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:

     num_quadratic_variables_real=cqm.num_quadratic_variables('REAL', include_objective=True),
     num_linear_biases_real=cqm.num_biases('REAL', linear_only=True),

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

The constraint quadratic model data comes after the header. It is encoded as a zip file. The zip file will contain one file named objective, containing the objective as encoded as a file view. It will also contain a directory called constraints. The constraints directory will contain one subdirectory for each constraint, each containing lhs, rhs and sense encoding the lhs as a fileview, the rhs as a float and the sense as a string. Each directory will also contain a discrete file, encoding whether the constraint represents a discrete variable. Weighted constraints also contain a weight and penalty file, encoding the weight and the penalty type for the constraint.

Format Specification (Version 1.2):

This format is the same as Version 1.3, except that there are no weighted constraints, and thus the weight and penalty files are not present.

Format Specification (Version 1.1):

This format is the same as Version 1.2, except that the data dict does not have num_quadratic_variables_real and num_linear_biases_real.

Format Specification (Version 1.0):

This format is the same as Version 1.1, except that the data dict does not have num_quadratic_variables.


>>> cqm1 = dimod.ConstrainedQuadraticModel()
>>> x, y = dimod.Binaries(["x", "y"])
>>> cqm1.set_objective(2 * x * y - 2 * x)
>>> cqm_file = cqm1.to_file()
>>> cqm2 = dimod.ConstrainedQuadraticModel.from_file(cqm_file)
>>> print(cqm2.objective.to_polystring())
-2*x + 2*x*y