コード例 #1
0
ファイル: decorators.py プロジェクト: alexzucca90/dimod
    def new_f(sampler, bqm, **kwargs):
        try:
            structure = sampler.structure
            adjacency = structure.adjacency
        except AttributeError:
            if isinstance(sampler, Structured):
                raise RuntimeError("something is wrong with the structured sampler")
            else:
                raise TypeError("sampler does not have a structure property")

        if not all(v in adjacency for v in bqm.linear):
            # todo: better error message
            raise BinaryQuadraticModelStructureError("given bqm does not match the sampler's structure")
        if not all(u in adjacency[v] for u, v in bqm.quadratic):
            # todo: better error message
            raise BinaryQuadraticModelStructureError("given bqm does not match the sampler's structure")

        return f(sampler, bqm, **kwargs)
コード例 #2
0
    def sample_ising(self, h, *args, **kwargs):
        # to be consistent with the cloud-client, we ignore the 0 biases
        # on missing nodes for lists
        if isinstance(h, list):
            if len(h) > self.solver.num_qubits:
                msg = "Problem graph incompatible with solver."
                raise BinaryQuadraticModelStructureError(msg)
            nodes = self.solver.nodes
            h = dict((v, b) for v, b in enumerate(h) if b and v in nodes)

        return super().sample_ising(h, *args, **kwargs)
コード例 #3
0
    def sample_qubo(self, Q, **kwargs):
        """Sample from the specified QUBO.

        Args:
            Q (dict):
                Coefficients of a quadratic unconstrained binary optimization (QUBO) model.

            **kwargs:
                Optional keyword arguments for the sampling method, specified per solver in
                :attr:`.DWaveSampler.parameters`. D-Wave System Documentation's
                `solver guide <https://docs.dwavesys.com/docs/latest/doc_solver_ref.html>`_
                describes the parameters and properties supported on the D-Wave system.

        Returns:
            :class:`dimod.SampleSet`: A `dimod` :obj:`~dimod.SampleSet` object.
            In it this sampler also provides timing information in the `info`
            field as described in the D-Wave System Documentation's
            `timing guide <https://docs.dwavesys.com/docs/latest/doc_timing.html>`_.

        Examples:
            This example submits a two-variable QUBO mapped directly to qubits
            0 and 4 on a D-Wave system.

            >>> from dwave.system.samplers import DWaveSampler
            >>> sampler = DWaveSampler()
            >>> Q = {(0, 0): -1, (4, 4): -1, (0, 4): 2}
            >>> sampleset = sampler.sample_qubo(Q)
            >>> for sample in sampleset.samples():    # doctest: +SKIP
            ...    print(sample)
            ...
            {0: 0, 4: 1}

        See `Ocean Glossary <https://docs.ocean.dwavesys.com/en/latest/glossary.html>`_
        for explanations of technical terms in descriptions of Ocean tools.

        """
        variables = set().union(*Q)

        # developer note: in the future we should probably catch exceptions
        # from the cloud client, but for now this is simpler/cleaner. We use
        # the solver's nodes/edges because they are a set, so faster lookup
        nodes = self.solver.nodes
        edges = self.solver.edges
        if not all(
                u in nodes if u == v else ((u, v) in edges or (v, u) in edges)
                for u, v in Q):
            msg = "Problem graph incompatible with solver."
            raise BinaryQuadraticModelStructureError(msg)

        future = self.solver.sample_qubo(Q, **kwargs)

        hook = _result_to_response_hook(variables, dimod.BINARY)
        return dimod.SampleSet.from_future(future, hook)
コード例 #4
0
    def sample(self, bqm, warnings=None, **kwargs):
        """Sample from the specified binary quadratic model.

        Args:
            bqm (:class:`~dimod.BinaryQuadraticModel`):
                The binary quadratic model. Must match :attr:`.nodelist` and
                :attr:`.edgelist`.

            warnings (:class:`~dwave.system.warnings.WarningAction`, optional):
                Defines what warning action to take, if any. See
                :ref:`warnings_system`. The default behaviour is to
                ignore warnings.

            **kwargs:
                Optional keyword arguments for the sampling method, specified per solver in
                :attr:`.parameters`. D-Wave System Documentation's
                `solver guide <https://docs.dwavesys.com/docs/latest/doc_solver_ref.html>`_
                describes the parameters and properties supported on the D-Wave system.

        Returns:
            :class:`~dimod.SampleSet`: Sample set constructed from a (non-blocking)
            :class:`~concurrent.futures.Future`-like object.
            In it this sampler also provides timing information in the `info`
            field as described in the D-Wave System Documentation's
            :ref:`sysdocs_gettingstarted:qpu_sapi_qpu_timing`.

        Examples:
            This example submits a two-variable Ising problem mapped directly to two
            adjacent qubits on a D-Wave system. ``qubit_a`` is the first qubit in
            the QPU's indexed list of qubits and ``qubit_b`` is one of the qubits
            coupled to it. Given sufficient reads (here 100), the quantum
            computer should return the best solution, :math:`{1, -1}` on ``qubit_a`` and
            ``qubit_b``, respectively, as its first sample (samples are ordered from
            lowest energy).

            >>> from dwave.system import DWaveSampler
            ...
            >>> sampler = DWaveSampler()
            ...
            >>> qubit_a = sampler.nodelist[0]
            >>> qubit_b = next(iter(sampler.adjacency[qubit_a]))
            >>> sampleset = sampler.sample_ising({qubit_a: -1, qubit_b: 1},
            ...                                  {},
            ...                                  num_reads=100)
            >>> sampleset.first.sample[qubit_a] == 1 and sampleset.first.sample[qubit_b] == -1
            True

        See `Ocean Glossary <https://docs.ocean.dwavesys.com/en/stable/concepts/index.html>`_
        for explanations of technical terms in descriptions of Ocean tools.

        """

        solver = self.solver

        try:
            future = solver.sample_bqm(bqm, **kwargs)
        except ProblemStructureError as exc:
            msg = ("Problem graph incompatible with solver. Please use 'EmbeddingComposite' "
                   "to map the problem graph to the solver.")
            raise BinaryQuadraticModelStructureError(msg) from exc

        if warnings is None:
            warnings = self.warnings_default
        warninghandler = WarningHandler(warnings)
        warninghandler.energy_scale(bqm)

        # need a hook so that we can check the sampleset (lazily) for
        # warnings
        def _hook(computation):
            sampleset = computation.sampleset

            if warninghandler is not None:
                warninghandler.too_few_samples(sampleset)
                if warninghandler.action is WarningAction.SAVE:
                    sampleset.info['warnings'] = warninghandler.saved

            return sampleset

        return dimod.SampleSet.from_future(future, _hook)
コード例 #5
0
    def sample(self, bqm, warnings=None, **kwargs):
        """Sample from the specified Ising model.

        Args:
            bqm (:class:`~dimod.BinaryQuadraticModel`):
                The binary quadratic model. Must match :attr:`.nodelist` and
                :attr:`.edgelist`.

            warnings (:class:`~dwave.system.warnings.WarningAction`, optional):
                Defines what warning action to take, if any. See
                :mod:`~dwave.system.warnings`. The default behaviour is defined
                by :attr:`warnings_default`, which itself defaults to
                :class:`~dwave.system.warnings.IGNORE`

            **kwargs:
                Optional keyword arguments for the sampling method, specified per solver in
                :attr:`.DWaveSampler.parameters`. D-Wave System Documentation's
                `solver guide <https://docs.dwavesys.com/docs/latest/doc_solver_ref.html>`_
                describes the parameters and properties supported on the D-Wave system.

        Returns:
            :class:`dimod.SampleSet`: A `dimod` :obj:`~dimod.SampleSet` object.
            In it this sampler also provides timing information in the `info`
            field as described in the D-Wave System Documentation's
            `timing guide <https://docs.dwavesys.com/docs/latest/doc_timing.html>`_.

        Examples:
            This example submits a two-variable Ising problem mapped directly to qubits
            0 and 1 on a D-Wave system. Given sufficient reads (here 100), the quantum
            computer should return the best solution, :math:`{1, -1}` on qubits 0 and 1,
            respectively, as its first sample (samples are ordered from lowest energy).

            >>> from dwave.system import DWaveSampler
            >>> sampler = DWaveSampler(solver={'qubits__issuperset': {0, 1}})
            >>> sampleset = sampler.sample_ising({0: -1, 1: 1}, {}, num_reads=100)
            >>> sampleset.first.sample[0] == 1 and sampleset.first.sample[1] == -1
            True

        See `Ocean Glossary <https://docs.ocean.dwavesys.com/en/latest/glossary.html>`_
        for explanations of technical terms in descriptions of Ocean tools.

        """

        solver = self.solver

        if not (solver.nodes.issuperset(bqm.linear)
                and solver.edges.issuperset(bqm.quadratic)):
            msg = "Problem graph incompatible with solver."
            raise BinaryQuadraticModelStructureError(msg)

        future = solver.sample_bqm(bqm, **kwargs)

        if warnings is None:
            warnings = self.warnings_default
        warninghandler = WarningHandler(warnings)
        warninghandler.energy_scale(bqm)

        # need a hook so that we can check the sampleset (lazily) for
        # warnings
        def _hook(computation):
            sampleset = computation.sampleset

            if warninghandler is not None:
                warninghandler.too_few_samples(sampleset)
                if warninghandler.action is WarningAction.SAVE:
                    sampleset.info['warnings'] = warninghandler.saved

            return sampleset

        return dimod.SampleSet.from_future(future, _hook)
コード例 #6
0
    def sample_ising(self, h, J, **kwargs):
        """Sample from the specified Ising model.

        Args:
            h (dict/list):
                Linear biases of the Ising model. If a dict, should be of the
                form `{v: bias, ...}` where `v` is a spin-valued variable and
                `bias` is its associated bias. If a list, it is treated as a
                list of biases where the indices are the variable labels,
                except in the case of missing qubits in which case 0 biases are
                ignored while a non-zero bias set on a missing qubit raises an
                error.

            J (dict[(int, int): float]):
                Quadratic biases of the Ising model.

            **kwargs:
                Optional keyword arguments for the sampling method, specified per solver in
                :attr:`.DWaveSampler.parameters`. D-Wave System Documentation's
                `solver guide <https://docs.dwavesys.com/docs/latest/doc_solver_ref.html>`_
                describes the parameters and properties supported on the D-Wave system.

        Returns:
            :class:`dimod.SampleSet`: A `dimod` :obj:`~dimod.SampleSet` object.
            In it this sampler also provides timing information in the `info`
            field as described in the D-Wave System Documentation's
            `timing guide <https://docs.dwavesys.com/docs/latest/doc_timing.html>`_.

        Examples:
            This example submits a two-variable Ising problem mapped directly to qubits
            0 and 1 on a D-Wave system.

            >>> from dwave.system.samplers import DWaveSampler
            >>> sampler = DWaveSampler()
            >>> sampleset = sampler.sample_ising({0: -1, 1: 1}, {})
            >>> for sample in sampleset.samples():    # doctest: +SKIP
            ...    print(sample)
            ...
            {0: 1, 1: -1}

        See `Ocean Glossary <https://docs.ocean.dwavesys.com/en/latest/glossary.html>`_
        for explanations of technical terms in descriptions of Ocean tools.

        """
        nodes = self.solver.nodes  # set rather than .nodelist which is a list

        if isinstance(h, list):
            # to be consistent with the cloud-client, we ignore the 0 biases
            # on missing nodes.
            h = dict((v, b) for v, b in enumerate(h) if b or v in nodes)

        variables = set(h).union(*J)

        # developer note: in the future we should probably catch exceptions
        # from the cloud client, but for now this is simpler/cleaner. We use
        # the solver's nodes/edges because they are a set, so faster lookup
        edges = self.solver.edges
        if not (all(v in nodes for v in h) and
                all((u, v) in edges or (v, u) in edges for u, v in J)):
            msg = "Problem graph incompatible with solver."
            raise BinaryQuadraticModelStructureError(msg)

        future = self.solver.sample_ising(h, J, **kwargs)

        hook = _result_to_response_hook(variables, dimod.SPIN)
        return dimod.SampleSet.from_future(future, hook)