How to use the dimod.BINARY 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_bqm.py View on Github external
def test_to_ising_binary_to_ising(self, name, BQM):
        linear = {0: 7.1, 1: 103}
        quadratic = {(0, 1): .97}
        offset = 0.3
        vartype = dimod.BINARY

        model = BQM(linear, quadratic, offset, vartype)

        h, J, off = model.to_ising()

        for spins in itertools.product((-1, 1), repeat=len(model)):
            spin_sample = dict(zip(range(len(spins)), spins))
            bin_sample = {v: (s + 1) // 2 for v, s in spin_sample.items()}

            # calculate the qubo's energy
            energy = off
            for (u, v), bias in J.items():
                energy += spin_sample[u] * spin_sample[v] * bias
            for v, bias in h.items():
                energy += spin_sample[v] * bias
github dwavesystems / dimod / dimod / testing / sampler.py View on Github external
def test_sample_qubo(self, sampler, Q):
    sampleset = sampler.sample_qubo(Q)

    self.assertEqual(set(sampleset.variables), set().union(*Q))
    self.assertIs(sampleset.vartype, dimod.BINARY)

    for sample, en in sampleset.data(['sample', 'energy']):
        self.assertAlmostEqual(dimod.qubo_energy(sample, Q), en)
github dwavesystems / dimod / tests / test_bqm.py View on Github external
def test_bias_new_variable(self, name, BQM):
        if not BQM.shapeable():
            raise unittest.SkipTest

        bqm = BQM(dimod.BINARY)
        bqm.add_variable(bias=5)

        self.assertEqual(bqm.linear, {0: 5})

        bqm.add_variable('a', -6)
        self.assertEqual(bqm.linear, {0: 5, 'a': -6})
github dwavesystems / dwave-neal / tests / test_sampler.py View on Github external
('g_0,2', 'g_0,0'): 4.0,
                     ('g_0,2', 'g_0,1'): 4.0,
                     ('o_0,0', 'o_1,1'): 2,
                     ('o_0,1', 'o_0,0'): 4.0,
                     ('o_0,1', 'o_1,1'): 2,
                     ('o_0,1', 'o_1,2'): 2,
                     ('o_0,2', 'o_0,0'): 4.0,
                     ('o_0,2', 'o_0,1'): 4.0,
                     ('o_0,2', 'o_1,1'): 2,
                     ('o_1,2', 'o_0,2'): 2,
                     ('o_1,2', 'o_1,1'): 4.0,
                     ('o_1,3', 'o_0,2'): 2,
                     ('o_1,3', 'o_1,1'): 4.0,
                     ('o_1,3', 'o_1,2'): 4.0}

        jss_bqm = dimod.BinaryQuadraticModel(linear, quadratic, 9.0, dimod.BINARY)

        # Optimal energy
        optimal_solution = {'b_0,0': 1, 'b_0,1': 0, 'b_0,2': 0, 'b_0,3': 0,
                            'b_1,0': 0, 'b_1,1': 1, 'b_1,2': 0,
                            'g_0,0': 0, 'g_0,1': 1, 'g_0,2': 0,
                            'o_0,0': 1, 'o_0,1': 0, 'o_0,2': 0,
                            'o_1,0': 0, 'o_1,1': 0, 'o_1,2': 1, 'o_1,3': 0}
        optimal_energy = jss_bqm.energy(optimal_solution) # Evaluates to 0.5

        # Get heuristic solution
        sampler = Neal()
        response = sampler.sample(jss_bqm, beta_schedule_type="linear", num_reads=10)
        _, response_energy, _ = next(response.data())

        # Compare energies
        threshold = 0.1	 # Arbitrary threshold
github dwavesystems / dimod / tests / test_serialization_format.py View on Github external
def test_additional_fields_summation(self):
        arr = np.ones((2, 5))
        variables = list(range(5))

        samples = dimod.SampleSet.from_samples((arr, variables),
                                               dimod.BINARY, energy=1,
                                               other=[5, 6],
                                               anotherother=[234029348023948234, 3])
        s = Formatter(width=30, depth=None).format(samples)

        target = '\n'.join(["   0 ...  4 energy num_oc. ...",
                            "0  1 ...  1      1       1 ...",
                            "1  1 ...  1      1       1 ...",
                            "['BINARY',",
                            " 2 rows,",
                            " 2 samples,",
                            " 5 variables]"])

        self.assertEqual(target, s)
github dwavesystems / dimod / tests / test_sampleset.py View on Github external
def test_non_blocking(self):

        future = concurrent.futures.Future()

        sampleset = dimod.SampleSet.from_future(future)

        # shouldn't block or raise
        new = sampleset.change_vartype(dimod.BINARY)

        future.set_result(dimod.SampleSet.from_samples({'a': -1},
                                                       dimod.SPIN,
                                                       energy=1))

        np.testing.assert_array_equal(new.record.sample, [[0]])
github dwavesystems / dwave-hybrid / hybrid / utils.py View on Github external
list: Energy changes in descending order, in the format of tuples
            (energy_gain, variable), for flipping the given sample value
            for each variable.

    Examples:
        This example returns the variable with maximum contribution to energy
        for the given sample.

        >>> import dimod
        >>> bqm = dimod.BQM({}, {'ab': 0, 'bc': 1, 'cd': 2}, 0, 'SPIN')
        >>> flip_energy_gains(bqm, {'a': -1, 'b': 1, 'c': 1, 'd': -1})[0][1]
        'd'

    """

    if bqm.vartype is dimod.BINARY:
        # val 0 flips to 1 => delta +1
        # val 1 flips to 0 => delta -1
        delta = lambda val: 1 - 2 * val
    elif bqm.vartype is dimod.SPIN:
        # val -1 flips to +1 => delta +2
        # val +1 flips to -1 => delta -2
        delta = lambda val: -2 * val
    else:
        raise ValueError("vartype not supported")

    sample = sample_as_dict(sample)

    if variables is None:
        variables = iter(sample)

    if min_gain is None:
github dwavesystems / dwavebinarycsp / dwavebinarycsp / factories / constraint / gates.py View on Github external
def or_gate(variables, vartype=dimod.BINARY, name='OR'):
    """OR gate.

    Args:
        variables (list): Variable labels for the and gate as `[in1, in2, out]`,
            where `in1, in2` are inputs and `out` the gate's output.
        vartype (Vartype, optional, default='BINARY'): Variable type. Accepted
            input values:

            * Vartype.SPIN, 'SPIN', {-1, 1}
            * Vartype.BINARY, 'BINARY', {0, 1}
        name (str, optional, default='OR'): Name for the constraint.

    Returns:
        Constraint(:obj:`.Constraint`): Constraint that is satisfied when its variables are
        assigned values that match the valid states of an OR gate.