コード例 #1
0
    def sample(self, bqm, num_reads=10):
        """Gives random samples.

        Args:
            todo

        Returns:
            :obj:`.Response`: The vartype will match the given binary quadratic model.

        Notes:
            For each variable in each sample, the value is chosen by a coin flip.

        """
        values = np.asarray(list(bqm.vartype.value), dtype='int8')
        samples = np.random.choice(values, (num_reads, len(bqm)))
        variable_labels = list(bqm.linear)
        label_to_idx = {v: idx for idx, v in enumerate(variable_labels)}

        energies = [
            bqm.energy(SampleView(idx, samples, label_to_idx))
            for idx in range(num_reads)
        ]

        return Response.from_matrix(samples, {'energy': energies},
                                    vartype=bqm.vartype,
                                    variable_labels=variable_labels)
コード例 #2
0
ファイル: exact_solver.py プロジェクト: aselzler3/dimod
    def sample(self, bqm):
        M = bqm.binary.to_numpy_matrix()

        sample = np.zeros((len(bqm),), dtype=bool)

        # now we iterate, flipping one bit at a time until we have
        # traversed all samples. This is a Gray code.
        # https://en.wikipedia.org/wiki/Gray_code
        def iter_samples():
            sample = np.zeros((len(bqm)), dtype=bool)
            energy = 0.0

            yield sample.copy(), energy

            for i in range(1, 1 << len(bqm)):
                v = _ffs(i)

                # flip the bit in the sample
                sample[v] = not sample[v]

                # for now just calculate the energy, but there is a more clever way by calculating
                # the energy delta for the single bit flip, don't have time, pull requests
                # appreciated!
                energy = sample.dot(M).dot(sample.transpose())

                yield sample.copy(), float(energy) + bqm.offset

        samples, energies = zip(*iter_samples())

        response = Response.from_matrix(np.asarray(samples), {'energy': energies})

        # finally make sure the response matches the given vartype, in-place.
        response.change_vartype(bqm.vartype)

        return response
コード例 #3
0
    def sample(self, bqm):
        """Sample from a binary quadratic model.

        Args:
            bqm (:obj:`~dimod.BinaryQuadraticModel`):
                Binary quadratic model to be sampled from.

        Returns:
            :obj:`~dimod.Response`: A `dimod` :obj:`.~dimod.Response` object.


        Examples:
            This example provides samples for a two-variable Ising model.

            >>> import dimod
            >>> sampler = dimod.ExactSolver()
            >>> bqm = dimod.BinaryQuadraticModel({0: 0.0, 1: 1.0}, {(0, 1): 0.5}, -0.5, dimod.SPIN)
            >>> response = sampler.sample(bqm)
            >>> response.data_vectors['energy']
            array([-1., -2.,  1.,  0.])

        """
        M = bqm.binary.to_numpy_matrix()
        off = bqm.binary.offset

        if M.shape == (0, 0):
            return Response.empty(bqm.vartype)

        sample = np.zeros((len(bqm), ), dtype=bool)

        # now we iterate, flipping one bit at a time until we have
        # traversed all samples. This is a Gray code.
        # https://en.wikipedia.org/wiki/Gray_code
        def iter_samples():
            sample = np.zeros((len(bqm)), dtype=bool)
            energy = 0.0

            yield sample.copy(), energy + off

            for i in range(1, 1 << len(bqm)):
                v = _ffs(i)

                # flip the bit in the sample
                sample[v] = not sample[v]

                # for now just calculate the energy, but there is a more clever way by calculating
                # the energy delta for the single bit flip, don't have time, pull requests
                # appreciated!
                energy = sample.dot(M).dot(sample.transpose())

                yield sample.copy(), float(energy) + off

        samples, energies = zip(*iter_samples())

        response = Response.from_matrix(np.matrix(samples, dtype='int8'),
                                        {'energy': energies},
                                        vartype=Vartype.BINARY)

        # make sure the response matches the given vartype, in-place.
        response.change_vartype(bqm.vartype, inplace=True)

        return response