def test_bq_ref_input_validation(self): problem_id = '123' with self.assertRaises(TypeError): encode_problem_as_bq(problem_id) bqm = dimod.BQM.from_qubo({}) with self.assertRaises(TypeError): encode_problem_as_ref(bqm)
def upload_bqm(self, bqm): """Upload the specified :term:`BQM` to SAPI, returning a Problem ID that can be used to submit the BQM to this solver (i.e. call the `.sample_bqm` method). Args: bqm (:class:`~dimod.BinaryQuadraticModel`/bytes-like/file-like): A binary quadratic model given either as an in-memory :class:`~dimod.BinaryQuadraticModel` object, or as raw data (encoded serialized model) in either a file-like or a bytes-like object. Returns: :class:`concurrent.futures.Future`[str]: Problem ID in a Future. Problem ID can be used to submit problems by reference. Note: To use this method, dimod package has to be installed. """ data = self._bqm_as_fileview(bqm) if data is None: if hasattr(bqm, 'to_serializable'): # soon to be deprecated data = encode_problem_as_bq(bqm, compress=True)['data'] else: # raw data (ready for upload) in `bqm` data = bqm return self.client.upload_problem_encoded(data)
def _encode_any_problem_as_bqm_ref(self, problem, params): """Encode `problem` for submitting in `bqm-ref` format. Upload the problem if it's not already uploaded. Args: problem (:class:`~dimod.BinaryQuadraticModel`/str): A binary quadratic model, or a reference to one (Problem ID). params (dict): Parameters for the sampling method, solver-specific. Returns: str: JSON-encoded problem submit body """ if isinstance(problem, six.string_types): problem_id = problem else: logger.debug("To encode the problem for submit via 'bqm-ref', " "we need to upload it first.") problem_id = self.upload_bqm(problem).result() body = json.dumps({ 'solver': self.id, 'data': encode_problem_as_bq(problem_id), 'type': 'bqm', 'params': params }) logger.trace("Sampling request encoded as: %s", body) return body
def sample_bqm(self, bqm, **params): """Sample from the specified :term:`BQM`. Args: bqm (:class:`~dimod.BinaryQuadraticModel`/str): A binary quadratic model, or a reference to one (Problem ID returned by `.upload_bqm` method). **params: Parameters for the sampling method, solver-specific. Returns: :class:`~dwave.cloud.computation.Future` Note: To use this method, dimod package has to be installed. """ # encode the request body = json.dumps({ 'solver': self.id, 'data': encode_problem_as_bq(bqm), 'type': 'bqm', 'params': params }) logger.trace("Encoded sample request: %s", body) future = Future(solver=self, id_=None, return_matrix=self.return_matrix) logger.debug("Submitting new problem to: %s", self.id) self.client._submit(body, future) return future
def test_bq_encodes_empty_bqm(self): """Empty BQM has to be trivially encoded.""" bqm = dimod.BQM.from_qubo({}) req = encode_problem_as_bq(bqm) self.assertEqual(req.get('format'), 'bq') self.assertEqual(pluck(req, 'data.version.bqm_schema'), '3.0.0') self.assertEqual(pluck(req, 'data.num_variables'), 0) self.assertEqual(pluck(req, 'data.num_interactions'), 0)
def test_bq_encodes_qubo_bqm(self): """Simple Qubo BQM properly encoded.""" bqm = dimod.BQM.from_qubo({(0, 1): 1}) req = encode_problem_as_bq(bqm) self.assertEqual(req.get('format'), 'bq') self.assertEqual(pluck(req, 'data.version.bqm_schema'), '3.0.0') self.assertEqual(pluck(req, 'data.variable_type'), 'BINARY') self.assertEqual(pluck(req, 'data.num_variables'), 2) self.assertEqual(pluck(req, 'data.num_interactions'), 1)
def test_bq_request_encoding_ising_bqm(self): """Simple Ising BQM properly encoded.""" bqm = dimod.BQM.from_ising({0: 1}, {(0, 1): 1}) req = encode_problem_as_bq(bqm) self.assertEqual(req.get('format'), 'bq') self.assertEqual(pluck(req, 'data.version.bqm_schema'), '3.0.0') self.assertEqual(pluck(req, 'data.variable_type'), 'SPIN') self.assertEqual(pluck(req, 'data.num_variables'), 2) self.assertEqual(pluck(req, 'data.num_interactions'), 1)
def test_bq_encodes_bqm_with_named_vars(self): """BQM with named variable properly encoded.""" bqm = dimod.BQM.from_ising({}, {'ab': 1, 'bc': 1, 'ca': 1}) req = encode_problem_as_bq(bqm) self.assertEqual(req.get('format'), 'bq') self.assertEqual(pluck(req, 'data.version.bqm_schema'), '3.0.0') self.assertEqual(pluck(req, 'data.variable_type'), 'SPIN') self.assertEqual(pluck(req, 'data.num_variables'), 3) self.assertEqual(pluck(req, 'data.num_interactions'), 3) self.assertEqual(pluck(req, 'data.variable_labels'), list('abc'))
def upload(config_file, profile, problem_id, format, input_file): """Multipart problem upload with cold restart support.""" try: client = Client.from_config(config_file=config_file, profile=profile) except Exception as e: click.echo("Invalid configuration: {}".format(e)) return 1 if config_file: click.echo("Using configuration file: {}".format(config_file)) if profile: click.echo("Using profile: {}".format(profile)) click.echo("Using endpoint: {}".format(client.endpoint)) click.echo(("Preparing to upload a problem from {!r} " "in {!r} format.").format(input_file.name, format)) if format == 'coo': click.echo("Transcoding 'coo' to 'bq-zlib'.") try: import dimod except ImportError: # pragma: no cover raise RuntimeError("Can't decode 'coo' format without dimod. " "Re-install the library with 'bqm' support.") # note: `BQM.from_coo` doesn't support files opened in binary (yet); # fallback to reopen for now with open(input_file.name, 'rt') as fp: bqm = dimod.BinaryQuadraticModel.from_coo(fp) problem = encode_problem_as_bq(bqm, compress=True)['data'] elif format == 'bq-zlib': problem = input_file click.echo("Uploading...") try: future = client.upload_problem_encoded(problem=problem, problem_id=problem_id) remote_problem_id = future.result() except Exception as e: click.echo(e) return 2 click.echo("Upload done. Problem ID: {!r}".format(remote_problem_id))