Exemplo n.º 1
0
    def test_triangle(self):
        qm = QM()
        qm.add_variables_from('SPIN', 'rstu')
        qm.add_variable('BINARY', 'x')
        qm.add_variable('INTEGER', 'i')

        qm.quadratic['sx'] = 5
        qm.quadratic['si'] = -3
        qm.quadratic['xi'] = 23
        qm.quadratic['ti'] = -7
        qm.quadratic['xu'] = 3
        qm.quadratic['rs'] = -12

        qm.offset = 1.5
        qm.linear['r'] = 5
        qm.linear['x'] = -4
        qm.linear['i'] = .25

        new = qm.spin_to_binary(inplace=False)

        rng = np.random.default_rng(42)

        for _ in range(10):
            sample = {}
            for v in qm.variables:
                if qm.vartype(v) == dimod.BINARY:
                    sample[v] = rng.choice((0, 1))
                elif qm.vartype(v) == dimod.SPIN:
                    sample[v] = rng.choice((-1, 1))
                elif qm.vartype(v) == dimod.INTEGER:
                    sample[v] = rng.choice(10)

            energy = qm.energy(sample)

            for v in qm.variables:
                if qm.vartype(v) == dimod.SPIN:
                    sample[v] = (sample[v] + 1) // 2

            self.assertEqual(energy, new.energy(sample))

        self.assertIs(qm.vartype('r'), dimod.SPIN)
        self.assertIs(new.vartype('r'), dimod.BINARY)
Exemplo n.º 2
0
    def test_3var(self, dtype):
        qm = QM()
        qm.add_variable('INTEGER', 'i')
        qm.add_variable('BINARY', 'x')
        qm.add_variable('SPIN', 's')

        qm.set_linear('i', 3)
        qm.set_quadratic('s', 'i', 2)
        qm.set_quadratic('x', 's', -2)
        qm.set_quadratic('i', 'i', 5)
        qm.offset = 7

        with tempfile.TemporaryFile() as tf:
            with qm.to_file() as qmf:
                shutil.copyfileobj(qmf, tf)
            tf.seek(0)
            new = QM.from_file(tf)

        self.assertTrue(qm.is_equal(new))
        self.assertEqual(qm.dtype, new.dtype)
Exemplo n.º 3
0
 def test_setting(self):
     qm = QM()
     qm.offset = 5
     self.assertEqual(qm.offset, 5)
     qm.offset -= 2
     self.assertEqual(qm.offset, 3)