Beispiel #1
0
    def sample_ising(self, h, J, **parameters):
        """Samples from an Ising model using an implemented sample method.

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

            >>> import dimod
            >>> class ImplementQuboSampler(dimod.Sampler):
            ...     def sample_qubo(self, Q):
            ...         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 = ImplementQuboSampler()
            >>> h = {1: 0.5, 2: -1, 3: -0.75}
            >>> J = {}
            >>> res = sampler.sample_ising(h, J)
            >>> print(res)
            [[-1  1]]

        """
        bqm = BinaryQuadraticModel.from_ising(h, J)
        response = self.sample(bqm, **parameters)
        return response
Beispiel #2
0
    def sample_ising(self, h, J, **parameters):
        """Sample from an Ising model using the implemented sample method.

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

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

        Args:
            h (dict/list):
                Linear biases of the Ising problem. If a dict, should be of the
                form `{v: bias, ...}` where 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.

            J (dict[(variable, variable), bias]):
                Quadratic biases of the Ising problem.

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

        Returns:
            :obj:`.SampleSet`

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

        """
        bqm = BinaryQuadraticModel.from_ising(h, J)
        return self.sample(bqm, **parameters)
    def sample_ising(self, h, J, offset=0, penalty_strength=1.0,
                     keep_penalty_variables=False,
                     discard_unsatisfied=False, **parameters):
        """ Sample from the problem provided by h, J, offset.

        Takes in linear variables in h and quadratic and higher order
        terms in J. Introducing penalties, reduces the higher-order problem
        into a quadratic problem and send it to its child sampler.

        Args:
            h (dict): linear biases corresponding to the HUBO form

            J (dict): higher order biases corresponding to the HUBO form

            offset (float, optional): constant energy offset

            penalty_strength (float, optional): Strength of the reduction constraint.
                Insufficient strength can result in the binary quadratic model
                not having the same minimization as the polynomial.

            keep_penalty_variables (bool, optional): default is True. if False
                will remove the variables used for penalty from the samples

            discard_unsatisfied (bool, optional): default is False. If True
                will discard samples that do not satisfy the penalty conditions.

            **parameters: Parameters for the sampling method, specified by
            the child sampler.

        Returns:
            :obj:`dimod.SampleSet`
        """

        # solve the problem on the child system

        bqm = BinaryQuadraticModel.from_ising(h, {})
        bqm = make_quadratic(J, penalty_strength, bqm=bqm)
        response = self.child.sample(bqm, **parameters)

        return polymorph_response(response, h, J, bqm,
                                  offset=offset,
                                  penalty_strength=penalty_strength,
                                  keep_penalty_variables=keep_penalty_variables,
                                  discard_unsatisfied=discard_unsatisfied)
Beispiel #4
0
    def sample_ising(self,
                     h,
                     J,
                     offset=0,
                     scalar=None,
                     bias_range=1,
                     quadratic_range=None,
                     ignored_variables=None,
                     ignored_interactions=None,
                     ignore_offset=False,
                     **parameters):
        """ Scale and sample from the problem provided by h, J, offset

        if scalar is not given, problem is scaled based on bias and quadratic
        ranges.

        Args:
            h (dict): linear biases

            J (dict): quadratic or higher order biases

            offset (float, optional): constant energy offset

            scalar (number):
                Value by which to scale the energy range of the binary quadratic model.

            bias_range (number/pair):
                Value/range by which to normalize the all the biases, or if
                `quadratic_range` is provided, just the linear biases.

            quadratic_range (number/pair):
                Value/range by which to normalize the quadratic biases.

            ignored_variables (iterable, optional):
                Biases associated with these variables are not scaled.

            ignored_interactions (iterable[tuple], optional):
                As an iterable of 2-tuples. Biases associated with these interactions are not scaled.

            ignore_offset (bool, default=False):
                If True, the offset is not scaled.

            **parameters:
                Parameters for the sampling method, specified by the child sampler.

        Returns:
            :obj:`dimod.SampleSet`

        """

        # if quadratic, create a bqm and send to sample

        if max(map(len, J.keys())) == 2:
            bqm = BinaryQuadraticModel.from_ising(h, J, offset=offset)
            return self.sample(bqm,
                               scalar=scalar,
                               bias_range=bias_range,
                               quadratic_range=quadratic_range,
                               ignored_variables=ignored_variables,
                               ignored_interactions=ignored_interactions,
                               ignore_offset=ignore_offset,
                               **parameters)

        # handle HUBO

        ignored_variables, ignored_interactions = _check_params(
            ignored_variables, ignored_interactions)

        child = self.child
        h_sc, J_sc, offset_sc = _scaled_hubo(h, J, offset, scalar, bias_range,
                                             quadratic_range,
                                             ignored_variables,
                                             ignored_interactions,
                                             ignore_offset)
        response = child.sample_ising(h_sc,
                                      J_sc,
                                      offset=offset_sc,
                                      **parameters)

        poly = _relabeled_poly(h, J, response.variables.index)
        response.record.energy = np.add(
            poly_energies(response.record.sample, poly), offset)
        return response
Beispiel #5
0
def embed_ising(souce_h, source_J, embedding, target_adjacency, chain_strength=1.0):
    """Embed an Ising problem onto a target graph.

    Args:
        source_h (dict[variable, bias]/list[bias]):
            Linear biases of the Ising problem. If a list, the list's indices are used as
            variable labels.

        source_J (dict[(variable, variable), bias]):
            Quadratic biases of the Ising problem.

        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:
        tuple: A 2-tuple:

            dict[variable, bias]: Linear biases of the target Ising problem.

            dict[(variable, variable), bias]: Quadratic biases of the target Ising problem.

    Examples:
        This example embeds a fully connected :math:`K_3` graph onto a square target graph.
        Embedding is accomplished by an edge contraction operation on the target graph: target-nodes
        2 and 3 are chained to represent source-node c.

        >>> import dimod
        >>> import networkx as nx
        >>> # Ising problem for a triangular source graph
        >>> h = {}
        >>> J = {('a', 'b'): 1, ('b', 'c'): 1, ('a', 'c'): 1}
        >>> # Target graph is a square graph
        >>> target = nx.cycle_graph(4)
        >>> # Embedding from source to target graph
        >>> embedding = {'a': {0}, 'b': {1}, 'c': {2, 3}}
        >>> # Embed the Ising problem
        >>> target_h, target_J = dimod.embed_ising(h, J, embedding, target)
        >>> target_J[(0, 1)] == J[('a', 'b')]
        True
        >>> target_J        # doctest: +SKIP
        {(0, 1): 1.0, (0, 3): 1.0, (1, 2): 1.0, (2, 3): -1.0}

        This example embeds a fully connected :math:`K_3` graph onto the target graph
        of a dimod reference structured sampler, `StructureComposite`, using the dimod reference
        `ExactSolver` sampler with a square graph specified. Target-nodes 2 and 3 are chained to
        represent source-node c.

        >>> import dimod
        >>> # Ising problem for a triangular source graph
        >>> h = {}
        >>> J = {('a', 'b'): 1, ('b', 'c'): 1, ('a', 'c'): 1}
        >>> # Structured dimod sampler with a structure defined by a square graph
        >>> sampler = dimod.StructureComposite(dimod.ExactSolver(), [0, 1, 2, 3], [(0, 1), (1, 2), (2, 3), (0, 3)])
        >>> # Embedding from source to target graph
        >>> embedding = {'a': {0}, 'b': {1}, 'c': {2, 3}}
        >>> # Embed the Ising problem
        >>> target_h, target_J = dimod.embed_ising(h, J, embedding, sampler.adjacency)
        >>> # Sample
        >>> response = sampler.sample_ising(target_h, target_J)
        >>> for sample in response.samples(n=3, sorted_by='energy'):   # doctest: +SKIP
        ...     print(sample)
        ...
        {0: 1, 1: -1, 2: -1, 3: -1}
        {0: 1, 1: 1, 2: -1, 3: -1}
        {0: -1, 1: 1, 2: -1, 3: -1}

    """
    source_bqm = BinaryQuadraticModel.from_ising(souce_h, source_J)
    target_bqm = embed_bqm(source_bqm, embedding, target_adjacency, chain_strength=chain_strength)
    target_h, target_J, __ = target_bqm.to_ising()
    return target_h, target_J
Beispiel #6
0
 def get_ising_embedding(self, h, J, **parameters):
     """Retrieve or create a minor-embedding from Ising model
     """
     bqm = BinaryQuadraticModel.from_ising(h, J)
     embedding = self.get_embedding(bqm, **parameters)
     return embedding
Beispiel #7
0
 def sample_ising(self, h, J, **parameters):
     """Samples from the given Ising model using the instantiated sample method."""
     bqm = BinaryQuadraticModel.from_ising(h, J)
     response = self.sample(bqm, **parameters)
     return response
Beispiel #8
0
    def sample_ising(self, h, J, offset=0, scalar=None,
                     bias_range=1, quadratic_range=None,
                     ignored_variables=None, ignored_interactions=None,
                     ignore_offset=False, **parameters):
        """ Scale and sample from the problem provided by h, J, offset

        if scalar is not given, problem is scaled based on bias and quadratic
        ranges.

        Args:
            h (dict): linear biases

            J (dict): quadratic or higher order biases

            offset (float, optional): constant energy offset

            scalar (number):
                Value by which to scale the energy range of the binary quadratic model.

            bias_range (number/pair):
                Value/range by which to normalize the all the biases, or if
                `quadratic_range` is provided, just the linear biases.

            quadratic_range (number/pair):
                Value/range by which to normalize the quadratic biases.

            ignored_variables (iterable, optional):
                Biases associated with these variables are not scaled.

            ignored_interactions (iterable[tuple], optional):
                As an iterable of 2-tuples. Biases associated with these interactions are not scaled.

            ignore_offset (bool, default=False):
                If True, the offset is not scaled.

            **parameters:
                Parameters for the sampling method, specified by the child sampler.

        Returns:
            :obj:`dimod.SampleSet`

        """

        if any(len(inter) > 2 for inter in J):
            # handle HUBO
            import warnings
            msg = ("Support for higher order Ising models in ScaleComposite is "
                   "deprecated and will be removed in dimod 0.9.0. Please use "
                   "PolyScaleComposite.sample_hising instead.")
            warnings.warn(msg, DeprecationWarning)

            from dimod.reference.composites.higherordercomposites import PolyScaleComposite
            from dimod.higherorder.polynomial import BinaryPolynomial

            poly = BinaryPolynomial.from_hising(h, J, offset=offset)

            ignored_terms = set()
            if ignored_variables is not None:
                ignored_terms.update(frozenset(v) for v in ignored_variables)
            if ignored_interactions is not None:
                ignored_terms.update(frozenset(inter) for inter in ignored_interactions)
            if ignore_offset:
                ignored_terms.add(frozenset())

            return PolyScaleComposite(self.child).sample_poly(poly, scalar=scalar,
                                                              bias_range=bias_range,
                                                              poly_range=quadratic_range,
                                                              ignored_terms=ignored_terms,
                                                              **parameters)

        bqm = BinaryQuadraticModel.from_ising(h, J, offset=offset)
        return self.sample(bqm, scalar=scalar,
                           bias_range=bias_range,
                           quadratic_range=quadratic_range,
                           ignored_variables=ignored_variables,
                           ignored_interactions=ignored_interactions,
                           ignore_offset=ignore_offset, **parameters)
Beispiel #9
0
 def sample_ising(self, h, J, **parameters):
     """Samples from an Ising model using an implemented sample method.
     """
     bqm = BinaryQuadraticModel.from_ising(h, J)
     return self.sample(bqm, **parameters)