Esempio n. 1
0
    def test_two_var_functional_labelled(self):
        dqm = dimod.DQM()
        dqm.add_variable(5)
        dqm.add_variable(7, 'b')

        dqm.set_linear_case(0, 3, 1.5)
        dqm.set_quadratic(0, 'b', {(0, 1): 1.5, (3, 4): 1})

        vectors = dqm.to_numpy_vectors()

        new = dimod.DQM.from_numpy_vectors(*vectors)

        new_vectors = new.to_numpy_vectors()
        np.testing.assert_array_equal(vectors[0], new_vectors[0])
        np.testing.assert_array_equal(vectors[1], new_vectors[1])
        np.testing.assert_array_equal(vectors[2][0], new_vectors[2][0])
        np.testing.assert_array_equal(vectors[2][1], new_vectors[2][1])
        np.testing.assert_array_equal(vectors[2][2], new_vectors[2][2])

        self.assertEqual(new.num_variables(), dqm.num_variables())
        self.assertEqual(new.num_cases(), dqm.num_cases())
        self.assertEqual(new.variables, dqm.variables)
        for v in dqm.variables:
            self.assertEqual(new.num_cases(v), dqm.num_cases(v))
            np.testing.assert_array_equal(new.get_linear(v),
                                          dqm.get_linear(v))
        self.assertEqual(new.adj, dqm.adj)
        self.assertEqual(new._cydqm.adj,
                         dqm._cydqm.adj)  # implementation detail
        for u in dqm.adj:
            for v in dqm.adj[u]:
                self.assertEqual(dqm.get_quadratic(u, v),
                                 new.get_quadratic(u, v))
Esempio n. 2
0
    def test_second_unlabelled(self):
        dqm = dimod.DQM()

        u = dqm.add_variable(4, label='a')
        v = dqm.add_variable(3)

        self.assertEqual(dqm.variables, ['a', 1])
    def test_second_unlabelled_conflict(self):
        dqm = dimod.DQM()

        u = dqm.add_variable(4, label=1)
        v = dqm.add_variable(3)
        v = dqm.add_variable(3)

        self.assertEqual(dqm.variables, [1, 0, 2])
    def test_typical(self):
        dqm = dimod.DQM()
        dqm.add_variable(5, 'a')
        dqm.add_variable(3, 'b')

        new = dqm.relabel_variables({'a': 'b', 'b': 'a'}, inplace=False)

        self.assertEqual(new.variables, ['b', 'a'])
    def test_index(self):
        dqm = dimod.DQM()
        dqm.add_variable(5, 'a')
        dqm.add_variable(3, 'b')

        dqm, mapping = dqm.relabel_variables_as_integers()

        self.assertEqual(mapping, {0: 'a', 1: 'b'})
    def test_set_quadratic_offdtype(self, name, dtype):
        dqm = dimod.DQM()
        u = dqm.add_variable(3)
        v = dqm.add_variable(2)

        biases = np.zeros((3, 2), dtype=dtype)

        dqm.set_quadratic(u, v, biases)
    def test_empty(self):
        dqm = dimod.DQM()

        self.assertEqual(dqm.num_variables(), 0)
        self.assertEqual(dqm.variables, [])
        self.assertEqual(dqm.adj, {})
        self.assertEqual(dqm.num_cases(), 0)
        self.assertEqual(dqm.offset, 0)
    def test_two_variable_labelled(self):
        dqm = dimod.DQM()
        u = dqm.add_variable(10)
        v = dqm.add_variable(5, label='v')

        dqm.set_quadratic(u, v, {(0, 1): 1})
        dqm.set_linear_case(u, 0, 1.5)

        self.assertEqual(dqm.energy({u: 0, v: 1}), 2.5)
    def test_self_loop(self):
        dqm = dimod.DQM()
        u = dqm.add_variable(5)
        v = dqm.add_variable(5)

        with self.assertRaises(ValueError):
            dqm.set_quadratic(u, u, {})
        with self.assertRaises(ValueError):
            dqm.set_quadratic_case(u, 0, u, 1, .5)
    def test_smoke(self):
        dqm = dimod.DQM()
        u = dqm.add_variable(2, 'a')
        v = dqm.add_variable(3)
        dqm.set_linear(u, [1, 2])
        dqm.set_quadratic(u, v, {(0, 1): 1, (0, 2): 1})

        sampleset = sampler.sample_dqm(dqm)
        sampleset.resolve()
    def test_one_variable(self):
        dqm = dimod.DQM()
        u = dqm.add_variable(4)

        for s in range(4):
            sample = [s]
            self.assertEqual(dqm.energy(sample), 0.0)

        np.testing.assert_array_equal(dqm.energies([[s] for s in range(4)]),
                                      np.zeros(4))
    def test_778(self):
        # https://github.com/dwavesystems/dimod/issues/778
        dqm = dimod.DQM()

        variables = np.array([0, 1, 2], dtype=np.int64)

        for variable in variables:
            dqm.add_variable(num_cases=5, label=variable)

        self.assertEqual(dqm.num_cases(variables[0]), 5)
    def test_empty_functional(self):
        dqm = dimod.DQM()

        with tempfile.TemporaryFile() as tf:
            with dqm.to_file() as df:
                shutil.copyfileobj(df, tf)
            tf.seek(0)
            new = dimod.DQM.from_file(tf)

        self.assertEqual(new.num_variables(), 0)
    def test_one_labelled(self):
        dqm = dimod.DQM()

        v = dqm.add_variable(10, label='a')

        self.assertEqual(v, 'a')
        self.assertEqual(dqm.num_variables(), 1)
        self.assertEqual(dqm.num_cases(), 10)
        self.assertEqual(dqm.num_cases('a'), 10)
        with self.assertRaises(ValueError):
            dqm.num_cases(0)
    def test_offset(self):
        dqm = dimod.DQM()
        dqm.add_variable(2)
        dqm.set_linear(0, [1,1])
        initial_energy = dqm.energy([0])

        dqm.offset = 10
        self.assertEqual(dqm.offset, 10)
        self.assertEqual(
            dqm.energy([0]), initial_energy + dqm.offset
        )
    def test_one_variable(self):
        dqm = dimod.DQM()

        v = dqm.add_variable(10)

        self.assertEqual(v, 0)
        self.assertEqual(dqm.num_variables(), 1)
        self.assertEqual(dqm.variables, [0])
        self.assertEqual(dqm.adj, {0: set()})
        self.assertEqual(dqm.num_cases(), 10)
        self.assertEqual(dqm.num_cases(0), 10)
    def test_set_quadratic_dense(self):
        dqm = dimod.DQM()
        u = dqm.add_variable(3)
        v = dqm.add_variable(2)

        dqm.set_quadratic(u, v, [[0, 1], [1.5, 6], [2, 0]])

        np.testing.assert_array_equal(dqm.get_quadratic(u, v, array=True),
                                      [[0, 1], [1.5, 6], [2, 0]])

        self.assertEqual(dqm.get_quadratic(u, v),
                         {(0, 1): 1, (1, 0): 1.5, (1, 1): 6, (2, 0): 2})
    def test_problem_labelling(self):
        dqm = dimod.DQM()
        u = dqm.add_variable(2, 'a')
        v = dqm.add_variable(3)
        dqm.set_linear(u, [1, 2])
        dqm.set_quadratic(u, v, {(0, 1): 1, (0, 2): 1})
        label = 'problem label'

        sampleset = sampler.sample_dqm(dqm, label=label)
        self.assertIn('problem_id', sampleset.info)
        self.assertIn('problem_label', sampleset.info)
        self.assertEqual(sampleset.info['problem_label'], label)
    def test_self_loop(self):
        dqm = dimod.DQM()
        u = dqm.add_variable(5)
        v = dqm.add_variable(6)

        terms = [(u, 0, .5), (v, 1, .5), (u, 2, .5)]

        dqm.add_linear_equality_constraint(
            terms, lagrange_multiplier=1, constant=1)

        # because two cases within the same variable are mentioned, we can
        # discard that interaction
        self.assertEqual(dqm.num_case_interactions(), 2)
    def test_set_linear_case(self):
        dqm = dimod.DQM()
        dqm.add_variable(5, 'a')

        np.testing.assert_array_equal(dqm.get_linear('a'), [0, 0, 0, 0, 0])

        dqm.set_linear_case('a', 1, 1.5)
        dqm.set_linear_case('a', 2, 4)

        self.assertEqual(dqm.get_linear_case('a', 0), 0)
        self.assertEqual(dqm.get_linear_case('a', 1), 1.5)
        self.assertEqual(dqm.get_linear_case('a', 2), 4)
        np.testing.assert_array_equal(dqm.get_linear('a'), [0, 1.5, 4, 0, 0])
    def test_two_variable(self):
        dqm = dimod.DQM()
        u = dqm.add_variable(3)
        v = dqm.add_variable(4, label='hello')

        dqm.set_linear_case(v, 3, 1.5)
        dqm.set_quadratic(u, v, {(0, 1): 5, (2, 0): 107})

        samples = list(itertools.product(range(3), range(4)))

        energies = dqm.energies((samples, [0, 'hello']))

        np.testing.assert_array_equal([0.0, 5.0, 0.0, 1.5, 0.0, 0.0, 0.0, 1.5,
                                       107.0, 0.0, 0.0, 1.5], energies)
    def test_inequality_constraint_equality(self):
        dqm = dimod.DQM()

        expr = [('a', 1, 1), ('b', 2, 1),
                ('c', 3, 1)]
        # we want 1 <= sum(expr) <= 1
        for i, j, k in expr:
            if i not in dqm.variables:
                dqm.add_variable(4, i)

        dqm1 = dqm.copy()
        dqm_equal = dqm.copy()

        slack_terms = \
            dqm.add_linear_inequality_constraint(expr,
                                                 constant=0,
                                                 lb=1,
                                                 ub=1,
                                                 lagrange_multiplier=1,
                                                 label="a")
        self.assertEqual(len(slack_terms), 0)

        slack_terms =\
            dqm1.add_linear_inequality_constraint(expr,
                                                  constant=-1,
                                                  lb=0,
                                                  ub=0,
                                                  lagrange_multiplier=1,
                                                  label="a")
        self.assertTrue(len(slack_terms) == 0)

        dqm_equal.add_linear_equality_constraint(expr,
                                                 constant=-1,
                                                 lagrange_multiplier=1)
        for j in [0, 1]:
            check = dqm.to_numpy_vectors()[j] - dqm_equal.to_numpy_vectors()[j]
            check1 = \
                dqm1.to_numpy_vectors()[j] - dqm_equal.to_numpy_vectors()[j]
            for i in range(len(check)):
                self.assertAlmostEqual(check[i], 0)
                self.assertAlmostEqual(check1[i], 0)

        for k in range(3):
            check = dqm.to_numpy_vectors()[2][k] -\
                     dqm_equal.to_numpy_vectors()[2][k]
            check1 = dqm1.to_numpy_vectors()[2][k] -\
                     dqm_equal.to_numpy_vectors()[2][k]
            for i in range(len(check)):
                self.assertAlmostEqual(check[i], 0)
                self.assertAlmostEqual(check1[i], 0)
    def test_sample_dqm_smoke_test(self):
        """Construction of and sampling from an unstructured DQM solver works."""

        try:
            import dimod
            dqm = dimod.DQM()
            dqm.add_variable(5)
            dqm.add_variable(7)
            dqm.set_linear_case(0, 3, 1.5)
            dqm.set_quadratic(0, 1, {(0, 1): 1.5, (3, 4): 1})
        except:
            # dimod or dimod with DQM support not available, so just use a mock
            dqm = mock.Mock()
            dqm.to_file.return_value = io.BytesIO(b'123')

        problem_type = 'dqm'

        # use a global mocked session, so we can modify it on-fly
        session = mock.Mock()

        # upload is now part of submit, so we need to mock it
        mock_problem_id = 'mock-problem-id'

        def mock_upload(self, bqm):
            return Present(result=mock_problem_id)

        # construct a functional solver by mocking client and api response data
        with mock.patch.multiple(Client,
                                 create_session=lambda self: session,
                                 upload_problem_encoded=mock_upload):
            with Client('endpoint', 'token') as client:
                solver = DQMSolver(
                    client,
                    unstructured_solver_data(problem_type=problem_type))

                # use bqm for mock response (for now)
                ss = dimod.ExactSolver().sample(dimod.BQM.empty('SPIN'))
                ss.info.update(problem_id=mock_problem_id)
                session.post = lambda path, _: choose_reply(
                    path, {
                        'problems/':
                        complete_reply(
                            ss, id_=mock_problem_id, type_=problem_type)
                    })

                # verify decoding works
                fut = solver.sample_dqm(dqm)
                numpy.testing.assert_array_equal(fut.sampleset, ss)
                numpy.testing.assert_array_equal(fut.problem_type,
                                                 problem_type)
    def test_set_linear(self):
        dqm = dimod.DQM()
        dqm.add_variable(5, 'a')

        np.testing.assert_array_equal(dqm.get_linear('a'), [0, 0, 0, 0, 0])

        with self.assertRaises(ValueError):
            dqm.set_linear('a', [0])

        dqm.set_linear('a', [0, 1.5, 4, 0, 0])

        self.assertEqual(dqm.get_linear_case('a', 0), 0)
        self.assertEqual(dqm.get_linear_case('a', 1), 1.5)
        self.assertEqual(dqm.get_linear_case('a', 2), 4)
        np.testing.assert_array_equal(dqm.get_linear('a'), [0, 1.5, 4, 0, 0])
    def test_two(self):
        dqm = dimod.DQM()

        u = dqm.add_variable(10)
        v = dqm.add_variable(5)

        self.assertEqual(u, 0)
        self.assertEqual(v, 1)
        self.assertEqual(dqm.num_variables(), 2)
        self.assertEqual(dqm.num_cases(), 15)
        self.assertEqual(dqm.num_cases(u), 10)
        self.assertEqual(dqm.num_cases(v), 5)

        with self.assertRaises(ValueError):
            dqm.num_cases(2)
    def test_readinto(self):
        dqm = dimod.DQM()
        dqm.add_variable(5)
        dqm.add_variable(7)

        dqm.set_linear_case(0, 3, 1.5)
        dqm.set_quadratic(0, 1, {(0, 1): 1.5, (3, 4): 1})

        with dqm.to_file() as f:
            buff = f.read()

        with dqm.to_file() as f:
            buff2 = bytearray(len(buff))
            f.readinto(buff2)

        self.assertEqual(buff, buff2)
Esempio n. 27
0
    def test_two_var_functional(self):
        dqm = dimod.DQM()
        dqm.add_variable(5)
        dqm.add_variable(7)

        dqm.set_linear_case(0, 3, 1.5)
        dqm.set_quadratic(0, 1, {(0, 1): 1.5, (3, 4): 1})

        new = dimod.DQM.from_numpy_vectors(*dqm.to_numpy_vectors())

        self.assertEqual(new.num_variables(), dqm.num_variables())
        self.assertEqual(new.num_cases(), dqm.num_cases())
        self.assertEqual(new.variables, dqm.variables)
        for v in dqm.variables:
            self.assertEqual(new.num_cases(v), dqm.num_cases(v))
            np.testing.assert_array_equal(new.get_linear(v), dqm.get_linear(v))
        self.assertEqual(new.adj, dqm.adj)
    def test_smoke(self):
        dqm = dimod.DQM()
        u = dqm.add_variable(2, 'a')
        v = dqm.add_variable(3)
        dqm.set_linear(u, [1, 2])
        dqm.set_quadratic(u, v, {(0, 1): 1, (0, 2): 1})

        try:
            # dimod 0.10+
            dqm.offset += 3
        except AttributeError:
            pass

        sampleset = sampler.sample_dqm(dqm)

        np.testing.assert_array_almost_equal(dqm.energies(sampleset),
                                             sampleset.record.energy)
    def test_more_constraint(self):
        dqm = dimod.DQM()
        x = dqm.add_variable(5, label='x')
        y = dqm.add_variable(3, label='y')
        w = dqm.add_variable(4, label='w')

        expression = [(x, 1, 1.0), (y, 2, 2.0), (w, 3, 1.0)]
        constant = -2.0
        dqm.add_linear_equality_constraint(
            expression,
            lagrange_multiplier=1.0, constant=constant)

        expression_dict = {v: (c, b) for v, c, b in expression}
        for cx, cy, cw in itertools.product(range(5), range(3), range(4)):
            s = constant
            state = {'x': cx, 'y': cy, 'w': cw}
            for v, cv, bias in expression:
                if expression_dict[v][0] == state[v]:
                    s += bias
            self.assertAlmostEqual(dqm.energy(state), s ** 2)
    def test_simple_constraint(self):
        dqm = dimod.DQM()
        num_variables = 2
        num_cases = 3
        x = {}
        for i in range(num_variables):
            x[i] = dqm.add_variable(num_cases, label='x_{i}'.format(i=i))

        for c in range(num_cases):
            dqm.add_linear_equality_constraint(
                [(x[i], c, 1.0) for i in range(num_variables)],
                lagrange_multiplier=1.0, constant=-1.0)

        for i in x:
            for case in range(num_cases):
                self.assertEqual(dqm.get_linear_case(x[i], case), -1)
            for j in x:
                if j > i:
                    for case in range(num_cases):
                        self.assertEqual(dqm.get_quadratic_case(x[i], case, x[j], case), 2.0)