Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.
def test_bqm_constructor(self):
# Test BinaryQuadraticModel constructor
bqm = oj.BinaryQuadraticModel(self.h, self.J)
self.assertEqual(type(bqm.ising_interactions()), np.ndarray)
self.assertEqual(bqm.var_type, oj.SPIN)
dense_graph = bqm.get_cxxjij_ising_graph(sparse=False)
self.assertTrue(isinstance(dense_graph, cj.graph.Dense))
bqm_qubo = oj.BinaryQuadraticModel.from_qubo(self.Q)
self.assertEqual(bqm_qubo.var_type, oj.BINARY)
def test_bqm_calc_energy(self):
# Test to calculate energy
# Test Ising energy
bqm = oj.BinaryQuadraticModel(self.h, self.J)
ising_energy_bqm = bqm.calc_energy(self.spins)
true_ising_e = calculate_ising_energy(self.h, self.J, self.spins)
self.assertEqual(ising_energy_bqm, true_ising_e)
# Test QUBO energy
bqm = oj.BinaryQuadraticModel.from_qubo(Q=self.Q)
qubo_energy_bqm = bqm.calc_energy(self.binaries)
true_qubo_e = calculate_qubo_energy(self.Q, self.binaries)
self.assertEqual(qubo_energy_bqm, true_qubo_e)
# QUBO == Ising
spins = [1, 1, -1, 1]
binary = [1, 1, 0, 1]
qubo_bqm = oj.BinaryQuadraticModel.from_qubo(Q=self.Q)
# ising_mat = qubo_bqm.ising_interactions()
# h, J = {}, {}
# for i in range(len(ising_mat)-1):
# for j in range(i, len(ising_mat)):
# if i == j:
# h[i] = ising_mat[i][i]
# else:
# J[(i, j)] = ising_mat[i][j]
init_binary = [1, 0, 1]
init_spin = [1, -1, 1]
# openjij
sampler = oj.SASampler(
beta_min=0.01, beta_max=10,
step_length=10, step_num=100
)
res = sampler.sample_qubo(
Q=Q, initial_state=init_binary,
seed=seed_for_mc
)
# cxxjij
model = oj.BinaryQuadraticModel.from_qubo(Q=Q)
graph = model.get_cxxjij_ising_graph()
system = cj.system.make_classical_ising_Eigen(init_spin, graph)
sch = cj.utility.make_classical_schedule_list(
beta_min=0.01, beta_max=10,
one_mc_step=10, num_call_updater=100
)
cj.algorithm.Algorithm_SingleSpinFlip_run(
system, seed_for_mc, sch
)
self.assertListEqual(
res.states[0], list((system.spin[:-1]+1)/2)
)
# Test Ising energy
bqm = oj.BinaryQuadraticModel(self.h, self.J)
ising_energy_bqm = bqm.calc_energy(self.spins)
true_ising_e = calculate_ising_energy(self.h, self.J, self.spins)
self.assertEqual(ising_energy_bqm, true_ising_e)
# Test QUBO energy
bqm = oj.BinaryQuadraticModel.from_qubo(Q=self.Q)
qubo_energy_bqm = bqm.calc_energy(self.binaries)
true_qubo_e = calculate_qubo_energy(self.Q, self.binaries)
self.assertEqual(qubo_energy_bqm, true_qubo_e)
# QUBO == Ising
spins = [1, 1, -1, 1]
binary = [1, 1, 0, 1]
qubo_bqm = oj.BinaryQuadraticModel.from_qubo(Q=self.Q)
# ising_mat = qubo_bqm.ising_interactions()
# h, J = {}, {}
# for i in range(len(ising_mat)-1):
# for j in range(i, len(ising_mat)):
# if i == j:
# h[i] = ising_mat[i][i]
# else:
# J[(i, j)] = ising_mat[i][j]
qubo_energy = qubo_bqm.calc_energy(binary)
self.assertEqual(qubo_energy, qubo_bqm.calc_energy(
spins, need_to_convert_from_spin=True))