Exemplo n.º 1
0
    def setUp(self):
        # mock client
        self.client = Client(endpoint='e',
                             token='t',
                             solver=dict(name__contains='test'))
        self.client._fetch_solvers = lambda **kw: self.solvers
        self.client._submit = lambda *pa, **kw: None
        self.client.upload_problem_encoded = lambda *pa, **kw: Present(
            result=mock_problem_id)

        # mock solvers
        self.structured_solver = StructuredSolver(
            client=self.client,
            data={
                "properties": {
                    "supported_problem_types": ["qubo", "ising"],
                    "qubits": [0, 1, 2],
                    "couplers": [[0, 1], [0, 2], [1, 2]],
                    "num_qubits": 3,
                    "num_reads_range": [0, 100],
                    "parameters": {
                        "num_reads": "Number of samples to return.",
                        "postprocess": "either 'sampling' or 'optimization'"
                    },
                    "topology": {
                        "type": "chimera",
                        "shape": [16, 16, 4]
                    },
                    "category": "qpu",
                    "tags": ["lower_noise"]
                },
                "id": "test-qpu-solver",
                "description": "A test solver 1",
                "status": "online"
            })
        self.unstructured_solver = UnstructuredSolver(
            client=self.client,
            data={
                "properties": {
                    "supported_problem_types": ["bqm"],
                    "parameters": {
                        "num_reads": "Number of samples to return."
                    },
                    "category": "hybrid",
                },
                "id": "test-unstructured-solver",
                "description": "A test unstructured solver"
            })
        self.solvers = [self.structured_solver]
        # we can't use unstructured solvers without dimod installed,
        # so don't even try testing it
        if dimod:
            self.solvers.append(self.unstructured_solver)

        # reset all event handlers
        from dwave.cloud.events import _client_event_hooks_registry as reg
        reg.update({k: [] for k in reg})
Exemplo n.º 2
0
    def _sample(self, type_, linear, quadratic, offset, params,
                label=None, undirected_biases=False):
        """Internal method for `sample_ising`, `sample_qubo` and `sample_bqm`.

        Args:
            linear (list/dict):
                Linear terms of the model.

            quadratic (dict[(int, int), float]):
                Quadratic terms of the model.

            offset (number):
                Constant offset applied to the model.

            params (dict):
                Parameters for the sampling method, solver-specific.

            label (str, optional):
                Problem label.

            undirected_biases (boolean, default=False):
                Are (quadratic) biases specified on undirected edges? For
                triangular or symmetric matrix of quadratic biases set it to
                ``True``.

        Returns:
            :class:`~dwave.cloud.computation.Future`
        """

        # Check the problem
        if not self.check_problem(linear, quadratic):
            raise ProblemStructureError(
                f"Problem graph incompatible with {self.id} solver")

        # Mix the new parameters with the default parameters
        combined_params = dict(self._params)
        combined_params.update(params)

        # Check the parameters before submitting
        for key in combined_params:
            if key not in self.parameters and not key.startswith('x_'):
                raise KeyError("{} is not a parameter of this solver.".format(key))

        # transform some of the parameters in-place
        self._format_params(type_, combined_params)

        body_dict = {
            'solver': self.id,
            'data': encode_problem_as_qp(self, linear, quadratic, offset,
                                         undirected_biases=undirected_biases),
            'type': type_,
            'params': combined_params
        }
        if label is not None:
            body_dict['label'] = label
        body_data = json.dumps(body_dict)
        logger.trace("Encoded sample request: %s", body_data)

        body = Present(result=body_data)
        computation = Future(solver=self, id_=None, return_matrix=self.return_matrix)

        # XXX: offset is carried on Future until implemented in SAPI
        computation._offset = offset

        logger.debug("Submitting new problem to: %s", self.id)
        self.client._submit(body, computation)

        return computation
 def mock_upload(self, bqm):
     return Present(result=mock_problem_id)
 def mock_upload(self, bqm):
     return Present(exception=mock_upload_exc)
Exemplo n.º 5
0
    def _sample(self,
                type_,
                linear,
                quadratic,
                params,
                undirected_biases=False):
        """Internal method for `sample_ising`, `sample_qubo` and `sample_bqm`.

        Args:
            linear (list/dict):
                Linear terms of the model.

            quadratic (dict[(int, int), float]):
                Quadratic terms of the model.

            params (dict):
                Parameters for the sampling method, solver-specific.

            undirected_biases (boolean, default=False):
                Are (quadratic) biases specified on undirected edges? For
                triangular or symmetric matrix of quadratic biases set it to
                ``True``.

        Returns:
            :class:`Future`
        """

        args = dict(type_=type_,
                    linear=linear,
                    quadratic=quadratic,
                    params=params)
        dispatch_event('before_sample', obj=self, args=args)

        # Check the problem
        if not self.check_problem(linear, quadratic):
            raise InvalidProblemError(
                "Problem graph incompatible with solver.")

        # Mix the new parameters with the default parameters
        combined_params = dict(self._params)
        combined_params.update(params)

        # Check the parameters before submitting
        for key in combined_params:
            if key not in self.parameters and not key.startswith('x_'):
                raise KeyError(
                    "{} is not a parameter of this solver.".format(key))

        # transform some of the parameters in-place
        self._format_params(type_, combined_params)

        body_data = json.dumps({
            'solver':
            self.id,
            'data':
            encode_problem_as_qp(self,
                                 linear,
                                 quadratic,
                                 undirected_biases=undirected_biases),
            'type':
            type_,
            'params':
            combined_params
        })
        logger.trace("Encoded sample request: %s", body_data)

        body = Present(result=body_data)
        computation = Future(solver=self,
                             id_=None,
                             return_matrix=self.return_matrix)

        logger.debug("Submitting new problem to: %s", self.id)
        self.client._submit(body, computation)

        dispatch_event('after_sample',
                       obj=self,
                       args=args,
                       return_value=computation)

        return computation