def _sample(self, bqm, **kwargs):
        """Sample from the given BQM."""
        # get a FileView-compatibile BQM
        bqm = dimod.as_bqm(
            bqm, cls=[dimod.AdjArrayBQM, dimod.AdjMapBQM, dimod.AdjVectorBQM])

        with FileView(bqm, version=2) as fv:
            sapi_problem_id = self.solver.upload_bqm(fv).result()

        return self.solver.sample_bqm(sapi_problem_id, **kwargs).sampleset
Exemple #2
0
def genModel(X, k, alpha=None, beta=None):
    ''' Generate QUBO model

    Args: 
        X: input data as Numpy array
        k: number of clusters

    Returns:
        Binary quadratic model of logical QUBO problem
    '''
    N = np.shape(X)[0]
    return dimod.as_bqm(genA(X, k, alpha=None, beta=None), dimod.BINARY)
    def _sample_large(self, bqm, **kwargs):
        """Sample from the unlabelled version of the BQM, then apply the
        labels to the returned sampleset.
        """
        # get a FileView-compatibile BQM
        # it is also important that the BQM be ordered
        bqm = dimod.as_bqm(
            bqm, cls=[dimod.AdjArrayBQM, dimod.AdjMapBQM, dimod.AdjVectorBQM])

        with FileView(bqm, version=2, ignore_labels=True) as fv:
            sapi_problem_id = self.solver.upload_bqm(fv).result()

        sampleset = self.solver.sample_bqm(sapi_problem_id, **kwargs).sampleset

        # relabel, as of dimod 0.9.5+ this is not blocking
        mapping = dict(enumerate(bqm.iter_variables()))
        return sampleset.relabel_variables(mapping)
Exemple #4
0
def test_quantum3():
    ''' Example using D-Wave's quantum annealing and Pras' embedding '''
    X = np.array([[1, 2], [1, 4], [9, 5], [9, 6]])  # input data
    N = 4
    k = 2
    A = genA(X, k)
    sampler = set_sampler()  # sets the D-Wave sampler
    embedding_dict, embeddings, qubitfootprint = embedder.embedQubo(
        A, np.zeros(N * k))
    embedded_model = dimod.as_bqm(embedding_dict, dimod.BINARY)
    print("Number of qubits used: " + str(qubitfootprint))
    embedded_solution_set = run_quantum(
        sampler, embedded_model)  # run on the D-Wave hardware
    print(embedder.postProcessing(embedded_solution_set, embeddings, A)[1][0])
    M, assignments = postprocess2(X,
                                  embedder.postProcessing(
                                      embedded_solution_set, embeddings,
                                      A)[1][0])  # postprocess the solution
    print("Centroids: ")
    print(M)
    print("Assignments: " + str(assignments))
Exemple #5
0
    def test_from_AdjMapBQM_sampleset(self):
        # cast dict bqm to AdjMapBQM
        bqm = dimod.as_bqm(self.bqm, cls=[dimod.AdjMapBQM])

        self._test_from_bqm_sampleset(bqm)
Exemple #6
0
    def test_from_AdjMapBQM_response(self):
        # cast dict bqm to AdjMapBQM
        bqm = dimod.as_bqm(self.bqm, cls=[dimod.AdjMapBQM])

        self._test_from_bqm_response(bqm)
    def sample(self, bqm, time_limit=None, **kwargs):
        """Sample from the specified binary quadratic model.

        Args:
            bqm (:obj:`dimod.BinaryQuadraticModel`):
                The binary quadratic model.

            time_limit (int):
                Maximum run time, in seconds, to allow the solver to work on the problem.
                Must be at least the minimum required for the number of problem variables,
                which is calculated and set by default.
                The minimum time for a hybrid solver is specified as a piecewise-linear
                curve defined by a set of floating-point pairs, the `minimum_time_limit`
                field under :attr:`.LeapHybridSampler.properties`. The first element in each
                pair is the number of problem variables; the second is the minimum
                required time. The minimum time for any particular number of variables
                is a linear interpolation calculated on two pairs that represent the
                relevant range for the given number of variables.
                For example, if `LeapHybridSampler().properties["minimum_time_limit"]`
                returns `[[1, 0.1], [100, 10.0], [1000, 20.0]]`, then the minimum time
                for a 50-variable problem is 5 seconds, the linear interpolation of the
                first two pairs that represent problems with between 1 to 100 variables.

            **kwargs:
                Optional keyword arguments for the solver, specified in
                :attr:`.LeapHybridSampler.parameters`.

        Returns:
            :class:`dimod.SampleSet`: A `dimod` :obj:`~dimod.SampleSet` object.

        Examples:
            This example builds a random sparse graph and uses a hybrid solver to find a
            maximum independent set.

            >>> import dimod
            >>> import networkx as nx
            >>> import dwave_networkx as dnx
            >>> import numpy as np
            ...
            >>> # Create a maximum-independent set problem from a random graph
            >>> problem_node_count = 300
            >>> G = nx.random_geometric_graph(problem_node_count, radius=0.0005*problem_node_count)
            >>> qubo = dnx.algorithms.independent_set.maximum_weighted_independent_set_qubo(G)
            >>> bqm = dimod.BQM.from_qubo(qubo)
            ...
            >>> # Find a good solution
            >>> sampler = LeapHybridSampler()    # doctest: +SKIP
            >>> sampleset = sampler.sample(bqm)           # doctest: +SKIP

        """

        bqm = dimod.as_bqm(
            bqm, cls=[dimod.AdjArrayBQM, dimod.AdjMapBQM, dimod.AdjVectorBQM])

        num_vars = len(bqm.variables)
        xx, yy = zip(*self.properties["minimum_time_limit"])
        min_time_limit = np.interp([num_vars], xx, yy)[0]

        if time_limit is None:
            time_limit = min_time_limit
        if not isinstance(time_limit, Number):
            raise TypeError("time limit must be a number")
        if time_limit < min_time_limit:
            msg = (
                "time limit for problem size {} must be at least {}").format(
                    num_vars, min_time_limit)
            raise ValueError(msg)

        with FileView(bqm) as fv:
            sapi_problem_id = self.solver.upload_bqm(fv).result()
        return self.solver.sample_bqm(sapi_problem_id,
                                      time_limit=time_limit).sampleset