示例#1
0
 def test_simple(self):
     qm = QM()
     a = qm.add_variable('SPIN', 'a')
     qm.set_linear(a, 1.5)
     qm.change_vartype('BINARY', a)
     self.assertEqual(qm.energy({a: 1}), 1.5)
     self.assertEqual(qm.energy({a: 0}), -1.5)
     self.assertIs(qm.vartype(a), dimod.BINARY)
示例#2
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)