Esempio n. 1
0
    def sample_qubo(self, Q, **parameters):
        """Samples from a QUBO using an implemented sample method.

        Examples:
            This example implements a placeholder Ising sampler and samples using
            the mixin QUBO sampler.

            >>> import dimod
            >>> class ImplementIsingSampler(dimod.Sampler):
            ...     def sample_ising(self, h, J):
            ...         return dimod.Response.from_dicts([{1: -1, 2: +1}], {'energy': [-1.0]}) # Placeholder
            ...     @property
            ...     def properties(self):
            ...         return self._properties
            ...     @property
            ...     def parameters(self):
            ...         return dict()
            ...
            >>> sampler = ImplementIsingSampler()
            >>> Q = {(0, 0): -0.5, (0, 1): 1, (1, 1): -0.75}
            >>> res = sampler.sample_qubo(Q)
            >>> print(res)
            [[0 1]]


        """
        bqm = BinaryQuadraticModel.from_qubo(Q)
        response = self.sample(bqm, **parameters)
        return response
Esempio n. 2
0
    def sample_qubo(self, Q, **parameters):
        """Sample from a QUBO using the implemented sample method.

        This method is inherited from the :class:`.Sampler` base class.

        Converts the QUBO into a :obj:`.BinaryQuadraticModel` and then
        calls :meth:`.sample`.

        Args:
            Q (dict):
                Coefficients of a quadratic unconstrained binary optimization
                (QUBO) problem. Should be a dict of the form `{(u, v): bias, ...}`
                where `u`, `v`, are binary-valued variables and `bias` is their
                associated coefficient.

            **kwargs:
                See the implemented sampling for additional keyword definitions.

        Returns:
            :obj:`.SampleSet`

        See also:
            :meth:`.sample`, :meth:`.sample_ising`

        """
        bqm = BinaryQuadraticModel.from_qubo(Q)
        return self.sample(bqm, **parameters)
Esempio n. 3
0
    def sample_qubo(self, Q, num_samps=100):
        """
        Sample from the QUBO problem
        :param qubo: QUBO problem
        :type qubo: numpy dictionary
        :return: samples, energy, num_occurrences
        """
        self.num_samps = num_samps

        if not hasattr(self, 'sampler'):

            bqm = BinaryQuadraticModel.from_qubo(Q)

            # apply the embedding to the given problem to map it to the child sampler
            __, target_edgelist, target_adjacency = self.child.structure

            # add self-loops to edgelist to handle singleton variables
            source_edgelist = list(bqm.quadratic) + [(v, v)
                                                     for v in bqm.linear]

            # get the embedding
            embedding = minorminer.find_embedding(source_edgelist,
                                                  target_edgelist)

            if bqm and not embedding:
                raise ValueError("no embedding found")

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

        response = self.sampler.sample_qubo(Q,
                                            chain_strength=self.chainstrength,
                                            num_reads=self.num_samps)

        return np.array(response.__dict__['_samples_matrix'].tolist()), response.__dict__['_data_vectors']["energy"], \
               response.__dict__['_data_vectors']["num_occurrences"]
Esempio n. 4
0
    def sample_qubo(self, Q, num_samps=100):
        """
        Sample from the QUBO problem
        :param qubo: QUBO problem
        :type qubo: numpy dictionary
        :return: samples, energy, num_occurrences
        """
        #print(Q)
        self.num_samps = num_samps

        if not hasattr(self, 'sampler'):

            bqm = BinaryQuadraticModel.from_qubo(Q)

            # apply the embedding to the given problem to map it to the child sampler
            __, target_edgelist, target_adjacency = self.child.structure

            # add self-loops to edgelist to handle singleton variables
            source_edgelist = list(bqm.quadratic) + [(v, v)
                                                     for v in bqm.linear]

            # get the embedding
            embedding = minorminer.find_embedding(source_edgelist,
                                                  target_edgelist)

            if bqm and not embedding:
                raise ValueError("no embedding found")

            self.sampler = FixedEmbeddingComposite(self.child, embedding)
        response = EmbeddingComposite(
            DWaveSampler(token="DEV-db4d47e5313cf3c52cac31dace7c5080a5ffc46d")
        ).sample_qubo(Q, num_reads=1000)
        #response = self.sampler.sample_qubo(Q, chain_strength=self.chainstrength, num_reads=self.num_samps)
        #for sample, energy, num_occurrences, chain_break_fraction in list(response.data()):
        #    print(sample, "Energy: ", energy, "Occurrences: ", num_occurrences)
        #print(response.samples()[0,[range(0,71)]])
        #print(response._asdict()['vectors']['energy'])
        #print(response._asdict()['vectors']['num_occurrences'])
        saempeul = np.empty((0, 72))
        for sample, in response.data(fields=['sample']):
            saempeul = np.append(saempeul, sample)
        #print(saempeul)
        return saempeul, response._asdict()['vectors']['energy']['data'], \
               response._asdict()['vectors']['num_occurrences']['data']
Esempio n. 5
0
def embed_qubo(source_Q, embedding, target_adjacency, chain_strength=1.0):
    """Embed a QUBO onto a target graph.

    Args:
        source_Q (dict[(variable, variable), bias]):
            Coefficients of a quadratic unconstrained binary optimization (QUBO) model.

        embedding (dict):
            Mapping from source graph to target graph as a dict of form {s: {t, ...}, ...},
            where s is a source-model variable and t is a target-model variable.

        target_adjacency (dict/:class:`networkx.Graph`):
            Adjacency of the target graph as a dict of form {t: Nt, ...},
            where t is a target-graph variable and Nt is its set of neighbours.

        chain_strength (float, optional):
            Magnitude of the quadratic bias (in SPIN-space) applied between variables to form a chain. Note
            that the energy penalty of chain breaks is 2 * `chain_strength`.

    Returns:
        dict[(variable, variable), bias]: Quadratic biases of the target QUBO.

    Examples:
        This example embeds a square source graph onto fully connected :math:`K_5` graph.
        Embedding is accomplished by an edge deletion operation on the target graph: target-node
        0 is not used.

        >>> import dimod
        >>> import networkx as nx
        >>> # QUBO problem for a square graph
        >>> Q = {(1, 1): -4.0, (1, 2): 4.0, (2, 2): -4.0, (2, 3): 4.0,
        ...      (3, 3): -4.0, (3, 4): 4.0, (4, 1): 4.0, (4, 4): -4.0}
        >>> # Target graph is a fully connected k5 graph
        >>> K_5 = nx.complete_graph(5)
        >>> 0 in K_5
        True
        >>> # Embedding from source to target graph
        >>> embedding = {1: {4}, 2: {3}, 3: {1}, 4: {2}}
        >>> # Embed the QUBO
        >>> target_Q = dimod.embed_qubo(Q, embedding, K_5)
        >>> (0, 0) in target_Q
        False
        >>> target_Q     # doctest: +SKIP
        {(1, 1): -4.0,
         (1, 2): 4.0,
         (2, 2): -4.0,
         (2, 4): 4.0,
         (3, 1): 4.0,
         (3, 3): -4.0,
         (4, 3): 4.0,
         (4, 4): -4.0}

        This example embeds a square graph onto the target graph of a dimod reference structured
        sampler, `StructureComposite`, using the dimod reference `ExactSolver` sampler with a
        fully connected :math:`K_5` graph specified.

        >>> import dimod
        >>> import networkx as nx
        >>> # QUBO problem for a square graph
        >>> Q = {(1, 1): -4.0, (1, 2): 4.0, (2, 2): -4.0, (2, 3): 4.0,
        ...      (3, 3): -4.0, (3, 4): 4.0, (4, 1): 4.0, (4, 4): -4.0}
        >>> # Structured dimod sampler with a structure defined by a K5 graph
        >>> sampler = dimod.StructureComposite(dimod.ExactSolver(), list(K_5.nodes), list(K_5.edges))
        >>> sampler.adjacency      # doctest: +SKIP
        {0: {1, 2, 3, 4},
         1: {0, 2, 3, 4},
         2: {0, 1, 3, 4},
         3: {0, 1, 2, 4},
         4: {0, 1, 2, 3}}
        >>> # Embedding from source to target graph
        >>> embedding = {0: [4], 1: [3], 2: [1], 3: [2], 4: [0]}
        >>> # Embed the QUBO
        >>> target_Q = dimod.embed_qubo(Q, embedding, sampler.adjacency)
        >>> # Sample
        >>> response = sampler.sample_qubo(target_Q)
        >>> for datum in response.data():   # doctest: +SKIP
        ...     print(datum)
        ...
        Sample(sample={1: 0, 2: 1, 3: 1, 4: 0}, energy=-8.0)
        Sample(sample={1: 1, 2: 0, 3: 0, 4: 1}, energy=-8.0)
        Sample(sample={1: 1, 2: 0, 3: 0, 4: 0}, energy=-4.0)
        Sample(sample={1: 1, 2: 1, 3: 0, 4: 0}, energy=-4.0)
        Sample(sample={1: 0, 2: 1, 3: 0, 4: 0}, energy=-4.0)
        Sample(sample={1: 1, 2: 1, 3: 1, 4: 0}, energy=-4.0)
        >>> # Snipped above response for brevity

    """
    source_bqm = BinaryQuadraticModel.from_qubo(source_Q)
    target_bqm = embed_bqm(source_bqm, embedding, target_adjacency, chain_strength=chain_strength)
    target_Q, __ = target_bqm.to_qubo()
    return target_Q
Esempio n. 6
0
 def get_qubo_embedding(self, Q, **parameters):
     """Retrieve or create a minor-embedding from QUBO
     """
     bqm = BinaryQuadraticModel.from_qubo(Q)
     embedding = self.get_embedding(bqm, **parameters)
     return embedding
Esempio n. 7
0
 def sample_qubo(self, Q, **parameters):
     """Samples from the given QUBO using the instantiated sample method."""
     bqm = BinaryQuadraticModel.from_qubo(Q)
     response = self.sample(bqm, **parameters)
     return response
Esempio n. 8
0
 def sample_qubo(self, Q, **parameters):
     """Samples from a QUBO using an implemented sample method.
     """
     bqm = BinaryQuadraticModel.from_qubo(Q)
     return self.sample(bqm, **parameters)
Esempio n. 9
0
def combinations(n: Union[int, Collection[Variable]],
                 k: int,
                 strength: float = 1,
                 vartype: VartypeLike = BINARY) -> BinaryQuadraticModel:
    r"""Generate a binary quadratic model that is minimized when k of n
    variables are selected.

    More fully, generates a binary quadratic model (BQM) that is minimized for
    each of the k-combinations of its variables.

    The energy for the BQM is given by
    :math:`(\sum_{i} x_i - k)^2`.

    Args:
        n: If ``n`` is an integer, variables are labelled `[0, n)`. If ``n`` is
            a list or set, variables are labelled accordingly.

        k: The generated BQM has ``0`` energy when any ``k`` of its variables
            are ``1``.

        strength: The energy of the first excited state of the binary quadratic
            model.

        vartype: Variable type for the BQM. Accepted input values:

            * :class:`.Vartype.SPIN`, ``'SPIN'``, ``{-1, 1}``
            * :class:`.Vartype.BINARY`, ``'BINARY'``, ``{0, 1}``

    Returns:
        A binary quadratic model.

    Examples:

        >>> bqm = dimod.generators.combinations(['a', 'b', 'c'], 2)
        >>> bqm.energy({'a': 1, 'b': 0, 'c': 1})
        0.0
        >>> bqm.energy({'a': 1, 'b': 1, 'c': 1})
        1.0

        >>> bqm = dimod.generators.combinations(5, 1)
        >>> bqm.energy({0: 0, 1: 0, 2: 1, 3: 0, 4: 0})
        0.0
        >>> bqm.energy({0: 0, 1: 0, 2: 1, 3: 1, 4: 0})
        1.0

        >>> bqm = dimod.generators.combinations(['a', 'b', 'c'], 2, strength=3.0)
        >>> bqm.energy({'a': 1, 'b': 0, 'c': 1})
        0.0
        >>> bqm.energy({'a': 1, 'b': 1, 'c': 1})
        3.0

    """
    if isinstance(n, Collection):
        variables = n
    else:
        try:
            variables = range(n)
        except TypeError:
            raise TypeError('n should be a collection or an integer')

    if k > len(variables) or k < 0:
        raise ValueError("cannot select k={} from {} variables".format(
            k, len(variables)))

    # (\sum_i x_i - k)^2
    #     = \sum_i x_i \sum_j x_j - 2k\sum_i x_i + k^2
    #     = \sum_{i,j} x_ix_j + (1 - 2k)\sum_i x_i + k^2
    lbias = float(strength * (1 - 2 * k))
    qbias = float(2 * strength)

    if not isinstance(n, int):
        num_vars = len(n)
        variables = n
    else:
        num_vars = n
        try:
            variables = range(n)
        except TypeError:
            raise TypeError('n should be a collection or an integer')

    Q = np.triu(np.ones((num_vars, num_vars)) * qbias, k=1)
    np.fill_diagonal(Q, lbias)
    bqm = BinaryQuadraticModel.from_qubo(Q, offset=strength * (k**2))

    if not isinstance(n, int):
        bqm.relabel_variables(dict(zip(range(len(n)), n)))

    return bqm.change_vartype(vartype, inplace=True)