How to use the openjij.SPIN 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_model.py View on Github external
def test_variable_type(self):
        spin = oj.cast_var_type('SPIN')
        self.assertEqual(spin, oj.SPIN)

        binary = oj.cast_var_type('BINARY')
        self.assertEqual(binary, oj.BINARY)
github OpenJij / OpenJij / tests / test_sampler.py View on Github external
def test_sqa(self):
        response = oj.SQASampler().sample_ising(self.h, self.J)
        self.assertEqual(len(response.states), 1)
        self.assertEqual(response.var_type, oj.SPIN)
        self.assertListEqual(response.states[0], [-1, -1, -1])
        self.assertEqual(response.energies[0], -18)

        response = oj.SQASampler().sample_qubo(self.Q)
        self.assertEqual(len(response.states), 1)
        self.assertListEqual(response.states[0], [0, 0, 0])

        schedule = [(s, 10) for s in np.arange(0, 1, 5)] + [(0.99, 100)]
        response = oj.SQASampler(schedule=schedule).sample_qubo(self.Q, seed=1)
        self.assertListEqual(response.states[0], [0, 0, 0])

        vaild_sche = [(s, 10) for s in np.linspace(0, 1.1, 5)]
        with self.assertRaises(ValueError):
            sampler = oj.SQASampler()
            _ = sampler.sample_ising({}, {}, schedule=vaild_sche)
github OpenJij / OpenJij / examples / python / sample_model.py View on Github external
:obj:: `openjij.sampler.response.Response` object.

        Examples:
            This example submits a two-variable Ising problem.

            >>> import openjij as oj
            >>> sampler = oj.SQASampler()
            >>> response = sampler.sample_ising({0: -1, 1: 1}, {})
            >>> for sample in response.samples():    # doctest: +SKIP
            ...    print(sample)
            ...
            {0: 1, 1: -1}

        """

        var_type = openjij.SPIN
        bqm = openjij.BinaryQuadraticModel(h=h, J=J, var_type=var_type)
        return self.sampling(bqm,
                             initial_state=initial_state, updater=updater,
                             reinitilize_state=reinitilize_state,
                             seed=seed,
                             **kwargs
                             )
github OpenJij / OpenJij / openjij / sampler / sqa_sampler.py View on Github external
def sampling(self, model,
                 initial_state=None, updater='single spin flip',
                 reinitialize_state=True, seed=None,
                 **kwargs):

        ising_graph = model.get_cxxjij_ising_graph()

        if initial_state is None:
            def init_generator(): return [ising_graph.gen_spin()
                                          for _ in range(self.trotter)]
        else:
            if model.var_type == openjij.SPIN:
                trotter_init_state = [np.array(initial_state)
                                      for _ in range(self.trotter)]
            else:  # BINARY
                trotter_init_state = [
                    (2*np.array(initial_state)-1).astype(int)
                    for _ in range(self.trotter)]

            def init_generator(): return trotter_init_state

        sqa_system = cxxjij.system.make_transverse_ising_Eigen(
            init_generator(), ising_graph, self.gamma
        )

        # choose updater
        _updater_name = updater.lower().replace('_', '').replace(' ', '')
        if _updater_name == 'singlespinflip':
github OpenJij / OpenJij / openjij / model / king_graph.py View on Github external
self.prange = [-3, 3]
        elif self.machine_type == "FPGA":
            self.xrange = [0, 79+1]
            self.yrange = [0, 79+1]
            self.prange = [-127, 127]
        else:
            raise ValueError('machine type should be ASIC or FPGA')

        # convert format h, J, Q and initilize BQM
        if king_graph is not None:
            linear, quadratic = self._convert_to_BQM_format(
                king_graph, var_type)
        super().__init__(linear, quadratic, offset=offset, var_type=var_type)

        # reformat to ising king graph (which is Web API format)
        if king_graph is not None and var_type == openjij.SPIN:
            self._ising_king_graph = king_graph
        elif var_type == openjij.SPIN:
            self._ising_king_graph = []
            for index, h in self.linear.items():
                if h != 0:
                    x, y = self._convert_to_xy(index)
                    self._ising_king_graph.append([x, y, x, y, h])
            for (i, j), J in self.quadratic.items():
                if J != 0:
                    x1, y1 = self._convert_to_xy(i)
                    x2, y2 = self._convert_to_xy(j)
                    self._ising_king_graph.append([x1, y1, x2, y2, J])
        else:
            ising_int = self.ising_interactions()
            sys_size = len(ising_int)
            self._ising_king_graph = []
github OpenJij / OpenJij / openjij / sampler / sqa_sampler.py View on Github external
:obj:: `openjij.sampler.response.Response` object.

        Examples:
            This example submits a two-variable Ising problem.

            >>> import openjij as oj
            >>> sampler = oj.SQASampler()
            >>> response = sampler.sample_ising({0: -1, 1: 1}, {})
            >>> for sample in response.samples():    # doctest: +SKIP
            ...    print(sample)
            ...
            {0: 1, 1: -1}

        """

        model = self._dict_to_model(var_type=openjij.SPIN, h=h, J=J, **kwargs)
        return self.sampling(model,
                             initial_state=initial_state, updater=updater,
                             reinitilize_state=reinitilize_state,
                             seed=seed,
                             **kwargs
                             )
github OpenJij / OpenJij / openjij / sampler / sa_sampler.py View on Github external
# ------------------------------- set annealing schedule

        # make init state generator
        if initial_state is None:
            # if not reinitialize_state:
            #     raise ValueError(
            #         'You need initial_state if reinitilize_state is False.')

            def _generate_init_state(): return ising_graph.gen_spin()
        else:
            # validate initial_state size
            if len(initial_state) != ising_graph.size():
                raise ValueError(
                    "the size of the initial state should be {}"
                    .format(ising_graph.size()))
            if model.var_type == openjij.SPIN:
                _init_state = np.array(initial_state)
            else:  # BINARY
                _init_state = (2*np.array(initial_state)-1).astype(np.int)

            def _generate_init_state(): return np.array(_init_state)

        # choose updater
        _updater_name = updater.lower().replace('_', '').replace(' ', '')
        if _updater_name == 'singlespinflip':
            algorithm = cxxjij.algorithm.Algorithm_SingleSpinFlip_run
            sa_system = cxxjij.system.make_classical_ising_Eigen(
                _generate_init_state(), ising_graph)
        elif _updater_name == 'swendsenwang':
            # swendsen-wang is not support Eigen system
            algorithm = cxxjij.algorithm.Algorithm_SwendsenWang_run
            sa_system = cxxjij.system.make_classical_ising(