How to use the dimod.vartypes.Vartype.SPIN function in dimod

To help you get started, we’ve selected a few dimod examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github dwavesystems / dimod / tests / test_connectedcomponentscomposite.py View on Github external
def test_sample(self):
        bqm = BinaryQuadraticModel({1: -1.3, 4: -0.5},
                                   {(1, 4): -0.6},
                                   0,
                                   vartype=Vartype.SPIN)
        sampler = ConnectedComponentsComposite(ExactSolver())
        response = sampler.sample(bqm)

        self.assertEqual(response.first.sample, {4: 1, 1: 1})
        self.assertAlmostEqual(response.first.energy, -2.4)
github dwavesystems / dimod / tests / test_fixedvariablecomposite.py View on Github external
def test_sample(self):
        bqm = BinaryQuadraticModel({1: -1.3, 4: -0.5},
                                   {(1, 4): -0.6},
                                   0,
                                   vartype=Vartype.SPIN)

        fixed_variables = {1: -1}
        sampler = FixedVariableComposite(ExactSolver())
        response = sampler.sample(bqm, fixed_variables=fixed_variables)

        self.assertEqual(response.first.sample, {4: -1, 1: -1})
        self.assertAlmostEqual(response.first.energy, 1.2)
github dwavesystems / dimod / dimod / higherorder / utils.py View on Github external
"""
    multiplier, multiplicand, product, aux = variables

    return BinaryQuadraticModel({multiplier: -.5,
                                 multiplicand: -.5,
                                 product: -.5,
                                 aux: -1.},
                                {(multiplier, multiplicand): .5,
                                 (multiplier, product): .5,
                                 (multiplier, aux): 1.,
                                 (multiplicand, product): .5,
                                 (multiplicand, aux): 1.,
                                 (product, aux): 1.},
                                2.,
                                Vartype.SPIN)
github dwavesystems / dimod / dimod / core / bqm.py View on Github external
def update(self, other):
        """Update the binary quadratic model, adding biases from another."""

        if self.vartype is Vartype.SPIN:
            bqm = other.spin
        elif self.vartype is Vartype.BINARY:
            bqm = other.binary
        else:
            raise ValueError("unknown vartype")

        self.add_variables_from(bqm.linear)
        self.add_interactions_from(bqm.quadratic)
        self.add_offset(bqm.offset)
github dwavesystems / dimod / dimod / higherorder / polynomial.py View on Github external
def __init__(self, poly, vartype):
        if isinstance(poly, abc.Mapping):
            poly = poly.items()

        # we need to aggregate the repeated terms
        self._terms = terms = {}
        for term, bias in poly:

            fsterm = asfrozenset(term)

            # when SPIN-valued, s^2 == 1, so we need to handle that case
            # in BINARY, x^2 == x
            if len(fsterm) < len(term) and vartype is Vartype.SPIN:
                new = set()
                term = tuple(term)  # make sure it has .count
                for v in fsterm:
                    if term.count(v) % 2:
                        new.add(v)
                fsterm = frozenset(new)

            if fsterm in terms:
                terms[fsterm] += bias
            else:
                terms[fsterm] = bias

        self.vartype = vartype
github dwavesystems / dimod / dimod / sampleset.py View on Github external
if isinstance(samples_like, SampleSet):
        return samples_like.vartype

    samples, _ = as_samples(samples_like)

    ones_mask = (samples == 1)

    if ones_mask.all():
        # either empty or all 1s, in either case ambiguous
        return None

    if (ones_mask ^ (samples == 0)).all():
        return Vartype.BINARY

    if (ones_mask ^ (samples == -1)).all():
        return Vartype.SPIN

    raise ValueError("given samples_like is of an unknown vartype")
github dwavesystems / dimod / dimod / responses / numpy_response.py View on Github external
    def __init__(self, info=None, vartype=Vartype.SPIN):
        NumpyResponse.__init__(self, info=info, vartype=vartype)
github dwavesystems / dimod / dimod / higherorder / utils.py View on Github external
pair, __ = paircounter.most_common(1)[0]
        u, v = pair

        # make a new product variable p == u*v and replace all (u, v) with p
        p = _new_product(variables, u, v)
        terms = [term for term in poly if u in term and v in term]
        for term in terms:
            new = tuple(w for w in term if w != u and w != v) + (p,)
            poly[new] = poly.pop(term)

        # add a constraint enforcing the relationship between p == u*v
        if vartype is Vartype.BINARY:
            constraint = _binary_product([u, v, p])

            bqm.info['reduction'][(u, v)] = {'product': p}
        elif vartype is Vartype.SPIN:
            aux = _new_aux(variables, u, v)  # need an aux in SPIN-space

            constraint = _spin_product([u, v, p, aux])

            bqm.info['reduction'][(u, v)] = {'product': p, 'auxiliary': aux}
        else:
            raise RuntimeError("unknown vartype: {!r}".format(vartype))

        # scale constraint and update the polynomial with it
        constraint.scale(strength)
        for v, bias in constraint.linear.items():
            try:
                poly[v, ] += bias
            except KeyError:
                poly[v, ] = bias
        for uv, bias in constraint.quadratic.items():
github dwavesystems / dimod / dimod / binary_quadratic_model_convert.py View on Github external
as the variable labels.

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

        offset (optional, default=0.0):
            The constant offset applied to the model.

    Returns:
        :class:`.BinaryQuadraticModel`

    """
    if isinstance(h, list):
        h = dict(enumerate(h))

    return BinaryQuadraticModel(h, J, offset, Vartype.SPIN)
github dwavesystems / dimod / dimod / reference / samplers / simulated_annealing.py View on Github external
if not isinstance(num_reads, int):
            raise TypeError("'samples' should be a positive integer")
        if num_reads < 1:
            raise ValueError("'samples' should be a positive integer")

        h, J, offset = bqm.to_ising()

        # run the simulated annealing algorithm
        samples = []
        energies = []
        for __ in range(num_reads):
            sample, energy = ising_simulated_annealing(h, J, beta_range, num_sweeps)
            samples.append(sample)
            energies.append(energy)

        response = SampleSet.from_samples(samples, Vartype.SPIN, energies)
        response.change_vartype(bqm.vartype, offset, inplace=True)
        return response