示例#1
0
    def solve(self, matrix, initial=()):
        '''
            returns: a solution
                    solution is a tuple (dict, float) representing sample and energy.
        '''
        if bool(initial):
            initial_sample = list(initial[0].values())
            print("initial sample: ",initial_sample)
        print("solver starts the process...")
        mtx = matrix.copy()
        print("converting to upper triangular...")
        mtx = mt.to_upper_triangular(mtx)
        print("matrix has %d zeros out of %d" % (np.count_nonzero(mtx==0), mtx.shape[0]*mtx.shape[1]))

        np.savetxt("mtx.txt", mtx, fmt='%d')

        Q = {}
        size = mtx.shape[0]
        for i,j in itertools.product(range(size),range(size)):
            if i==j:
                if mtx[i][i]:
                    Q[(i,i)] = mtx[i][i]
            elif i<j:
                if mtx[i][j]:
                    Q[(i,j)] = mtx[i][j]
            else:
                pass
        
        print("Solver engages Dwave quantum hardware!")
        sampler = dimod.ScaleComposite(EmbeddingComposite(DWaveSampler()))

        anneal_schedule = [(0,1),(4,0.5),(14,0.5),(20,1)]
        if bool(initial):
            print(initial)
            initial_state_dict = initial[0]
            response = sampler.sample_qubo(Q,num_reads=50, anneal_schedule=anneal_schedule, initial_state=initial_state_dict)
        else:
            response = sampler.sample_qubo(Q,num_reads=50, annealing_time=20)

        timing_iter = (response.info['timing']['qpu_sampling_time'] / 1000000)
        self.timing += timing_iter
        print(timing_iter)
        print(response.info)
        for datum in response.data(fields=['sample','energy','num_occurrences']):
            print(datum)
            break

        return (response.first.sample, response.first.energy)
示例#2
0
    def test_scale_aware_scale_composite(self):

        nodelist = [0, 1, 2]
        edgelist = [(0, 1), (1, 2), (0, 2)]
        embedding = {'a': [0], 'b': [1, 2]}

        sampler = FixedEmbeddingComposite(dimod.TrackingComposite(
            dimod.ScaleComposite(
                dimod.StructureComposite(dimod.NullSampler(), nodelist,
                                         edgelist))),
                                          embedding=embedding,
                                          scale_aware=True)

        _ = sampler.sample_ising({'a': 100, 'b': -100}, {'ab': 300})

        self.assertIn('ignored_interactions', sampler.child.input)
        ignored = sampler.child.input['ignored_interactions']

        self.assertTrue(ignored == [(1, 2)] or ignored == [(2, 1)])
示例#3
0
    def sample(self, bqm, chain_strength=None, **kwargs):
        """Sample from the specified binary quadratic model.

        Args:
            bqm (:class:`~dimod.BinaryQuadraticModel`):
                Any binary quadratic model with up to
                :attr:`.largest_clique_size` variables. This BQM is embedded
                using a dense clique embedding.

            chain_strength (float, optional):
                The (relative) chain strength to use in the embedding. By
                default a chain strength of `1.5sqrt(N)` where `N` is the size
                of the largest clique, as returned by
                :attr:`.largest_clique_size`.

            **kwargs:
                Optional keyword arguments for the sampling method, specified
                per solver in :attr:`.DWaveCliqueSampler.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. Note that `auto_scale` is not supported by this
                sampler, because it scales the problem as part of the embedding
                process.

        """

        # some arguments should not be overwritten
        if 'auto_scale' in kwargs:
            raise TypeError("sample() got an unexpected keyword argument "
                            "'auto_scale'")
        if 'bias_range' in kwargs:
            raise TypeError("sample() got an unexpected keyword argument "
                            "'bias_range'")
        if 'quadratic_range' in kwargs:
            raise TypeError("sample() got an unexpected keyword argument "
                            "'quadratic_range'")

        # handle circular import. todo: fix
        from dwave.system.composites.embedding import FixedEmbeddingComposite

        # get the embedding
        embedding = find_clique_embedding(bqm.variables, self.target_graph,
                                          use_cache=True)

        # returns an empty embedding when the BQM is too large
        if not embedding and bqm.num_variables:
            raise ValueError("Cannot embed given BQM (size {}), sampler can "
                             "only handle problems of size {}".format(
                                len(bqm.variables), self.largest_clique_size))

        assert bqm.num_variables == len(embedding)  # sanity check

        if chain_strength is None:
            # chain length determines chain strength
            if embedding and bqm.num_interactions > 0:
                squared_j = (j ** 2 for j in bqm.quadratic.values())
                rms = math.sqrt(sum(squared_j)/bqm.num_interactions)
       
                chain_strength = 1.5 * rms * math.sqrt(bqm.num_variables)
            else:
                chain_strength = 1  # doesn't matter

        # scaling only make sense in Ising space
        original_bqm = bqm

        if bqm.vartype is not dimod.SPIN:
            bqm = bqm.change_vartype(dimod.SPIN, inplace=False)

        sampler = FixedEmbeddingComposite(
            dimod.ScaleComposite(self.child),
            embedding)

        if 'auto_scale' in self.child.parameters:
            kwargs['auto_scale'] = False

        sampleset = sampler.sample(bqm,
                                   bias_range=self.qpu_linear_range,
                                   quadratic_range=self.qpu_quadratic_range,
                                   chain_strength=chain_strength,
                                   **kwargs
                                   )

        # change_vartype is non-blocking
        return sampleset.change_vartype(original_bqm.vartype)
示例#4
0
    def sample(self, bqm, chain_strength=None, **kwargs):
        """Sample from the specified binary quadratic model.

        Args:
            bqm (:class:`~dimod.BinaryQuadraticModel`):
                Any binary quadratic model with up to
                :attr:`.largest_clique_size` variables. This BQM is embedded
                using a clique embedding.

            chain_strength (float/mapping/callable, optional):
                Sets the coupling strength between qubits representing variables 
                that form a :term:`chain`. Mappings should specify the required 
                chain strength for each variable. Callables should accept the BQM 
                and embedding and return a float or mapping. By default, 
                `chain_strength` is calculated with
                :func:`~dwave.embedding.chain_strength.uniform_torque_compensation`.

            **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. Note that `auto_scale` is not supported by this
                sampler, because it scales the problem as part of the embedding
                process.

        """

        # some arguments should not be overwritten
        if 'auto_scale' in kwargs:
            raise TypeError("sample() got an unexpected keyword argument "
                            "'auto_scale'")
        if 'bias_range' in kwargs:
            raise TypeError("sample() got an unexpected keyword argument "
                            "'bias_range'")
        if 'quadratic_range' in kwargs:
            raise TypeError("sample() got an unexpected keyword argument "
                            "'quadratic_range'")

        # handle circular import. todo: fix
        from dwave.system.composites.embedding import FixedEmbeddingComposite

        # get the embedding
        embedding = find_clique_embedding(bqm.variables,
                                          self.target_graph,
                                          use_cache=True)

        # returns an empty embedding when the BQM is too large
        if not embedding and bqm.num_variables:
            raise ValueError("Cannot embed given BQM (size {}), sampler can "
                             "only handle problems of size {}".format(
                                 len(bqm.variables), self.largest_clique_size))

        assert bqm.num_variables == len(embedding)  # sanity check

        # scaling only make sense in Ising space
        original_bqm = bqm

        if bqm.vartype is not dimod.SPIN:
            bqm = bqm.change_vartype(dimod.SPIN, inplace=False)

        sampler = FixedEmbeddingComposite(dimod.ScaleComposite(self.child),
                                          embedding)

        if 'auto_scale' in self.child.parameters:
            kwargs['auto_scale'] = False

        sampleset = sampler.sample(bqm,
                                   bias_range=self.qpu_linear_range,
                                   quadratic_range=self.qpu_quadratic_range,
                                   chain_strength=chain_strength,
                                   **kwargs)

        # change_vartype is non-blocking
        return sampleset.change_vartype(original_bqm.vartype)