How to use the openjij.BinaryQuadraticModel function in openjij

To help you get started, we’ve selected a few openjij 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 OpenJij / OpenJij / tests / test_utils.py View on Github external
def test_benchmark(self):
        h = {0: 1}
        J = {(0, 1):-1.0, (1,2): -1.0}

        def solver(time_param, *args):
            sa_samp = oj.SASampler()
            sa_samp.step_num = time_param 
            sa_samp.iteration = 10
            return sa_samp.sample_ising(h, J)

        # logger setting
        ground_state = [-1, -1, -1]
        ground_energy = oj.BinaryQuadraticModel(h, J).calc_energy(ground_state)
        step_num_list = np.linspace(1, 5, 5, dtype=np.int)
        bm_res = oj.solver_benchmark(
            solver=solver,
            time_list=step_num_list,
            solutions=[ground_state])
        self.assertTrue(set(bm_res) >= {'time', 'success_prob', 'residual_energy', 'tts', 'info'})
        self.assertEqual(len(bm_res) ,len(step_num_list))

        bench = oj.solver_benchmark(
            solver=solver,
            time_list=step_num_list,
            ref_energy=ground_energy, measure_with_energy=True)
        self.assertTrue(set(bench) >= {'time', 'success_prob', 'residual_energy', 'tts', 'info'})
github OpenJij / OpenJij / tests / test_model.py View on Github external
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)
github OpenJij / OpenJij / tests / test_model.py View on Github external
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 = {}, {}
github OpenJij / OpenJij / tests / test_model.py View on Github external
bqm = oj.BinaryQuadraticModel(self.h, self.J)
        ising_matrix = np.array([
            [1, -1,  0,  0],
            [-1, -2, -3, 0],
            [0, -3, 0, 0.5],
            [0, 0, 0.5, 0]
        ])
        np.testing.assert_array_equal(
            bqm.ising_interactions(), ising_matrix
        )

        # check Hij = Jij + Jji
        J = self.J.copy()
        J[0, 1] /= 3
        J[1, 0] = J[0, 1] * 2
        bqm = oj.BinaryQuadraticModel(self.h, J)
        np.testing.assert_array_equal(
            bqm.ising_interactions(), ising_matrix
        )
github OpenJij / OpenJij / openjij / sampler / sqa_sampler.py View on Github external
def _dict_to_model(self, var_type, h=None, J=None, Q=None, **kwargs):
        return openjij.BinaryQuadraticModel(h=h, J=J, Q=Q, var_type=var_type)
github OpenJij / OpenJij / openjij / sampler / sa_sampler.py View on Github external
def sample(self, model, beta_min=None, beta_max=None,
               num_sweeps=None, num_reads=1, schedule=None,
               initial_state=None, updater='single spin flip',
               reinitialize_state=True, seed=None,
               **kwargs):

        model = openjij.BinaryQuadraticModel(
            linear=model.linear, quadratic=model.quadratic,
            offset=model.offset, var_type=model.vartype
        )

        self._setting_overwrite(
            beta_min=beta_min, beta_max=beta_max,
            num_sweeps=num_sweeps, num_reads=num_reads
        )

        ising_graph = model.get_cxxjij_ising_graph()

        self.num_reads = num_reads if num_reads > 1 else self.num_reads

        # set annealing schedule -------------------------------
        if schedule or self.schedule:
            self._schedule = self._convert_validation_schedule(
github OpenJij / OpenJij / examples / python / sample_model.py View on Github external
return response

    def _post_process4state(self, q_state):
        return q_state


if __name__ == '__main__':

    h = {0: 5, 1: 5, 2: 5}
    J = {(0, 1): -1.0, (1, 2): -1.0, (2, 0): -1.0}
    iteration = 10
    trotter = 4
    sampler = SQASampler(iteration=iteration, trotter=trotter)
    response = sampler.sample_ising(h=h, J=J)

    model = oj.BinaryQuadraticModel(h=h, J=J)
    print(model.calc_energy([-1, -1, -1], need_to_convert_from_spin=True))

    print(len(response.states), iteration)
    print(len(response.q_states), iteration)
    print(len(response.q_states[0]), trotter)
    print(type(response.q_states[0][0][0]))
    print(response.energies[0], -18)
    print(isinstance(response.q_states[0][0][0], np.int64))
github OpenJij / OpenJij / examples / python / benchmark.py View on Github external
if __name__ == "__main__":

    # make target instance
    N = 10
    h = {0: 1, 1: 1}
    J = {}
    for i in range(N-1):
        for j in range(i+1, N):
            J[(i, j)] = -1.0
    
    true_ground_state = [-1]*N
    sa_samp = oj.SASampler()
    
    ground_energy = oj.BinaryQuadraticModel(h, J).calc_energy(true_ground_state)

    # make benchmark target solver
    def solver(time_param, iteration):
        sa_samp.step_num = time_param 
        sa_samp.iteration = iteration
        return sa_samp.sample_ising(h, J)

    # benchmarking
    b_res = oj.benchmark([true_ground_state], ground_energy, solver, time_param_list=np.arange(1, 161, 50))

    plt.xlabel('annealing time')
    plt.ylabel('error probability')
    plt.plot(b_res['time'], b_res['error'])
    plt.show()