Esempio n. 1
0
    def test_bqm_calc_energy(self):
        # Test to calculate energy

        # Test Ising energy
        bqm = oj.BinaryQuadraticModel(h=self.h, J=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(Q=self.Q, var_type='BINARY')
        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(Q=self.Q, var_type='BINARY')
        # 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))
Esempio n. 2
0
    def test_chimera(self):
        h = {}
        J = {(0, 4): -1.0, (6, 2): -3.0}
        bqm = oj.BinaryQuadraticModel(h=h, J=J)
        self.assertTrue(bqm.validate_chimera(unit_num_L=3))

        J = {(0, 1): -1}
        bqm = oj.BinaryQuadraticModel(h=h, J=J)
        self.assertFalse(bqm.validate_chimera(unit_num_L=3))
Esempio n. 3
0
    def test_interaction_matrix(self):
        bqm = oj.BinaryQuadraticModel(h=self.h, J=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)
Esempio n. 4
0
    def test_bqm_constructor(self):
        # Test BinaryQuadraticModel constructor
        bqm = oj.BinaryQuadraticModel(h=self.h, J=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(Q=self.Q, var_type='BINARY')
        self.assertEqual(bqm_qubo.var_type, oj.BINARY)
Esempio n. 5
0
    def test_openjij_cxxjij_compare(self):
        seed_for_mc = 1
        Q = {
            (0, 0): 1,
            (1, 1): -1,
            (2, 2): 2,
            (0, 1): 1,
            (1, 2): -1,
            (2, 0): -1
        }
        # solution is [0, 1, 0]

        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(Q=Q, var_type='BINARY')
        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))
Esempio n. 6
0
    def test_benchmark(self):
        h = {0: 1}
        J = {(0, 1): -1.0, (1, 2): -1.0}

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

        # logger setting
        logger = getLogger('openjij')
        stream_handler = StreamHandler()
        stream_handler.setLevel(INFO)
        logger.addHandler(stream_handler)

        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.benchmark([ground_state],
                              ground_energy,
                              solver,
                              time_param_list=step_num_list)
        self.assertTrue(
            set(bm_res) >=
            {'time', 'error', 'e_res', 'tts', 'tts_threshold_prob'})

        self.assertEqual(len(bm_res), len(step_num_list))
Esempio n. 7
0
    def test_transfer_to_cxxjij(self):
        bqm = oj.BinaryQuadraticModel(self.h, self.J)
        # to Dense
        ising_graph = bqm.get_cxxjij_ising_graph(sparse=False)
        self.assertEqual(ising_graph.size(), len(bqm.indices))
        for i in range(len(bqm.indices)):
            for j in range(len(bqm.indices)):
                if i != j:
                    self.assertAlmostEqual(
                        bqm.interaction_matrix()[i, j],
                        ising_graph.get_interactions()[i, j])
                else:
                    # i == j
                    self.assertAlmostEqual(
                        bqm.interaction_matrix()[i, j],
                        ising_graph.get_interactions()[i, len(bqm.indices)])
                    self.assertAlmostEqual(
                        bqm.interaction_matrix()[i, j],
                        ising_graph.get_interactions()[len(bqm.indices), i])
                    self.assertEqual(ising_graph.get_interactions()[i, i], 0)

        self.assertEqual(
            ising_graph.get_interactions()[len(bqm.indices),
                                           len(bqm.indices)], 1)

        # to Sparse
        ising_graph = bqm.get_cxxjij_ising_graph(sparse=True)
        self.assertEqual(ising_graph.size(), len(bqm.indices))
        for i in range(ising_graph.size()):
            for j in ising_graph.adj_nodes(i):
                self.assertEqual(bqm.interaction_matrix()[i, j],
                                 ising_graph[i, j])
Esempio n. 8
0
    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.num_sweeps = time_param
            return sa_samp.sample_ising(h, J, num_reads=10)

        # logger setting
        ground_state = [-1, -1, -1]
        ground_energy = oj.BinaryQuadraticModel(h, J).calc_energy(ground_state)
        step_num_list = np.linspace(1, 9, 9, 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'})
Esempio n. 9
0
    def test_bqm_calc_energy(self):
        # Test to calculate energy

        # Test Ising energy
        bqm = oj.BinaryQuadraticModel(self.h, self.J, 'SPIN')
        ising_energy_bqm = bqm.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.energy(self.binaries)
        true_qubo_e = calculate_qubo_energy(self.Q, self.binaries)
        self.assertEqual(qubo_energy_bqm, true_qubo_e)

        # QUBO == Ising
        spins = {0: 1, 1: 1, 2: -1, 3: 1}
        binary = {0: 1, 1: 1, 2: 0, 3: 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.energy(binary)
        qubo_bqm.change_vartype('SPIN')

        self.assertEqual(qubo_energy, qubo_bqm.energy(spins))
Esempio n. 10
0
    def sample_ising(self, h, J,
                     beta=None, gamma=None,
                     num_sweeps=None, schedule=None, trotter=None,
                     num_reads=1,
                     initial_state=None, updater='single spin flip',
                     sparse=False,
                     reinitialize_state=True, seed=None, structure=None):
        """Sampling from the Ising model

        Args:
            h (dict): Linear term of the target Ising model. 
            J (dict): Quadratic term of the target Ising model. 
            beta (float, optional): inverse tempareture.
            gamma (float, optional): strangth of transverse field. Defaults to None.
            num_sweeps (int, optional): number of sweeps. Defaults to None.
            schedule (list[list[float, int]], optional): List of annealing parameter. Defaults to None.
            trotter (int): Trotter number.
            num_reads (int, optional): number of sampling. Defaults to 1.
            initial_state (list[int], optional): Initial state. Defaults to None.
            updater (str, optional): update method. Defaults to 'single spin flip'.
            reinitialize_state (bool, optional): Re-initilization at each sampling. Defaults to True.
            seed (int, optional): Sampling seed. Defaults to None.
            structure (dict): specify the structure. 
            This argument is necessary if the model has a specific structure (e.g. Chimera graph) and the updater algorithm is structure-dependent.
            structure must have two types of keys, namely "size" which shows the total size of spins and "dict" which is the map from model index (elements in model.indices) to the number.

        Raises:
            ValueError: 

        Returns:
            :class:`openjij.sampler.response.Response`: results

        Examples:
            
            for Ising case::

                >>> h = {0: -1, 1: -1, 2: 1, 3: 1}
                >>> J = {(0, 1): -1, (3, 4): -1}
                >>> sampler = oj.SQASampler()
                >>> res = sampler.sample_ising(h, J)

            for QUBO case::

                >>> Q = {(0, 0): -1, (1, 1): -1, (2, 2): 1, (3, 3): 1, (4, 4): 1, (0, 1): -1, (3, 4): 1}
                >>> sampler = oj.SQASampler()
                >>> res = sampler.sample_qubo(Q)
        """

        bqm = openjij.BinaryQuadraticModel(
            linear=h, quadratic=J, var_type='SPIN'
        )
        return self._sampling(bqm, beta=beta, gamma=gamma,
                     num_sweeps=num_sweeps, schedule=schedule, trotter=trotter,
                     num_reads=num_reads,
                     initial_state=initial_state, updater=updater,
                     sparse=sparse,
                     reinitialize_state=reinitialize_state, seed=seed, structure=structure)
Esempio n. 11
0
 def _dict_to_model(self, var_type, h=None, J=None, Q=None, **kwargs):
     if var_type == openjij.SPIN:
         bqm = openjij.BinaryQuadraticModel(h, J, 0.0, var_type)
     elif var_type == openjij.BINARY:
         bqm = openjij.BinaryQuadraticModel.from_qubo(Q)
     else:
         raise ValueError(
             'var_type should be openjij.SPIN or openjij.BINARY')
     return bqm
Esempio n. 12
0
 def test_energy_consistency(self):
     bqm = oj.BinaryQuadraticModel(self.h,
                                   self.J,
                                   vartype='SPIN',
                                   sparse=False)
     dense_ising_graph, offset = bqm.get_cxxjij_ising_graph()
     bqm = oj.BinaryQuadraticModel(self.h,
                                   self.J,
                                   vartype='SPIN',
                                   sparse=True)
     sparse_ising_graph, offset = bqm.get_cxxjij_ising_graph()
     spins = {0: -1, 1: -1, 2: -1, 3: -1}
     self.assertAlmostEqual(
         dense_ising_graph.calc_energy(
             [spins[i] for i in range(len(spins))]), bqm.energy(spins))
     self.assertAlmostEqual(
         sparse_ising_graph.calc_energy(
             [spins[i] for i in range(len(spins))]), bqm.energy(spins))
Esempio n. 13
0
    def sample_ising(self,
                     h,
                     J,
                     initial_state=None,
                     updater='single spin flip',
                     reinitilize_state=True,
                     seed=None,
                     **kwargs):
        """Sample from the specified Ising model.

        Args:
            h (dict):
                Linear biases of the Ising model.

            J (dict):
                Quadratic biases of the Ising model.

            initial_state (list):
                The initial state of simulated annealing

            updater (str):
                Monte Carlo update algorithm : 'single spin flip' or 'swendsenwang'

            reinitilize_state (bool):
                Reinitialize the initial state for every anneal-readout cycle.

            seed (:obj:`int`, optional):
                seed for Monte Carlo step

            **kwargs:
                Optional keyword arguments for the sampling method.

        Returns:
            :obj:: `openjij.sampler.response.Response` object.

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

            >>> import openjij as oj
            >>> sampler = oj.SASampler()
            >>> 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
        model = openjij.BinaryQuadraticModel(h=h, J=J, var_type=var_type)
        return self.sampling(model,
                             initial_state=initial_state,
                             updater=updater,
                             reinitilize_state=reinitilize_state,
                             seed=seed,
                             **kwargs)
Esempio n. 14
0
    def sample_ising(
        self,
        h,
        J,
        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,
    ):
        """sample Ising model.

        Args:
            h (dict): linear biases
            J (dict): quadratic biases
            beta_min (float): minimal value of inverse temperature
            beta_max (float): maximum value of inverse temperature
            num_sweeps (int): number of sweeps
            num_reads (int): number of reads
            schedule (list): list of inverse temperature
            initial_state (dict): initial state
            updater(str): updater algorithm
            reinitialize_state (bool): if true reinitialize state for each run
            seed (int): seed for Monte Carlo algorithm
        Returns:
            :class:`openjij.sampler.response.Response`: results
            
        Examples:
            
            for Ising case::

                >>> h = {0: -1, 1: -1, 2: 1, 3: 1}
                >>> J = {(0, 1): -1, (3, 4): -1}
                >>> sampler = oj.SASampler()
                >>> res = sampler.sample_ising(h, J)

            for QUBO case::

                >>> Q = {(0, 0): -1, (1, 1): -1, (2, 2): 1, (3, 3): 1, (4, 4): 1, (0, 1): -1, (3, 4): 1}
                >>> sampler = oj.SASampler()
                >>> res = sampler.sample_qubo(Q)
            
        """

        model = openjij.BinaryQuadraticModel(linear=h,
                                             quadratic=J,
                                             var_type='SPIN')
        return self._sampling(model, beta_min, beta_max, num_sweeps, num_reads,
                              schedule, initial_state, updater,
                              reinitialize_state, seed)
Esempio n. 15
0
    def test_bqm(self):
        h = {}
        J = {(0, 1): -1.0, (1, 2): -3.0}
        bqm = oj.BinaryQuadraticModel(h, J, 'SPIN')

        self.assertEqual(J, bqm.get_quadratic())

        self.assertEqual(type(bqm.interaction_matrix()), np.ndarray)
        correct_mat = np.array([[0, -1, 0, 0], [0, 0, -3, 0], [0, 0, 0, 0],
                                [0, 0, 0, 1]])
        np.testing.assert_array_equal(bqm.interaction_matrix(),
                                      correct_mat.astype(float))
Esempio n. 16
0
    def sample_qubo(self,
                    Q,
                    initial_state=None,
                    updater='single spin flip',
                    reinitilize_state=True,
                    seed=None,
                    **kwargs):
        """Sample from the specified QUBO.

        Args:
            Q (dict):
                Coefficients of a quadratic unconstrained binary optimization (QUBO) model.

            initial_state (list):
                The initial state of simulated annealing

            updater (str):
                Monte Carlo update algorithm : 'single spin flip' or 'swendsenwang'

            reinitilize_state (bool):
                Reinitialize the initial state for every anneal-readout cycle.

            seed (:obj:`int`, optional):
                seed for Monte Carlo step

            **kwargs:
                Optional keyword arguments for the sampling method.

        Returns:
            :obj:: `openjij.sampler.response.Response` object.

        Examples:
            This example submits a two-variable QUBO model.

            >>> import openjij as oj
            >>> sampler = oj.SASampler()
            >>> Q = {(0, 0): -1, (4, 4): -1, (0, 4): 2}
            >>> response = sampler.sample_qubo(Q)
            >>> for sample in response.samples():    # doctest: +SKIP
            ...    print(sample)
            ...
            {0: 0, 4: 1}

        """

        var_type = openjij.BINARY
        model = openjij.BinaryQuadraticModel(Q=Q, var_type=var_type)
        return self.sampling(model,
                             initial_state=initial_state,
                             updater=updater,
                             reinitilize_state=reinitilize_state,
                             seed=seed,
                             **kwargs)
Esempio n. 17
0
    def test_bqm_constructor(self):
        # Test BinaryQuadraticModel constructor
        bqm = oj.BinaryQuadraticModel(self.h, self.J, 'SPIN', sparse=False)
        self.assertEqual(type(bqm.interaction_matrix()), np.ndarray)

        self.assertEqual(bqm.vartype, oj.SPIN)

        dense_graph, offset = bqm.get_cxxjij_ising_graph()
        self.assertTrue(isinstance(dense_graph, cj.graph.Dense))
        self.assertEqual(offset, 0)

        bqm_qubo = oj.BinaryQuadraticModel.from_qubo(Q=self.Q)
        self.assertEqual(bqm_qubo.vartype, oj.BINARY)
Esempio n. 18
0
    def test_bqm(self):
        h = {}
        J = {(0, 1): -1.0, (1, 2): -3.0}
        bqm = oj.BinaryQuadraticModel(h=h, J=J)

        self.assertEqual(type(bqm.ising_interactions()), np.ndarray)
        correct_mat = np.array([[
            0,
            -1,
            0,
        ], [-1, 0, -3], [0, -3, 0]])
        np.testing.assert_array_equal(bqm.ising_interactions(),
                                      correct_mat.astype(np.float))
Esempio n. 19
0
    def sample_ising(self,
                     h,
                     J,
                     beta=None,
                     gamma=None,
                     num_sweeps=None,
                     schedule=None,
                     num_reads=1,
                     initial_state=None,
                     updater='single spin flip',
                     reinitialize_state=True,
                     seed=None,
                     **kwargs):
        """Sampling from the Ising model

        Args:
            h (dict): Linear term of the target Ising model. 
            J (dict): Quadratic term of the target Ising model. 
            beta (float, optional): inverse tempareture.
            gamma (float, optional): strangth of transverse field. Defaults to None.
            num_sweeps (int, optional): number of sweeps. Defaults to None.
            schedule (list[list[float, int]], optional): List of annealing parameter. Defaults to None.
            num_reads (int, optional): number of sampling. Defaults to 1.
            initial_state (list[int], optional): Initial state. Defaults to None.
            updater (str, optional): update method. Defaults to 'single spin flip'.
            reinitialize_state (bool, optional): Re-initilization at each sampling. Defaults to True.
            seed (int, optional): Sampling seed. Defaults to None.

        Raises:
            ValueError: [description]

        Returns:
            [type]: [description]
        """

        bqm = openjij.BinaryQuadraticModel(linear=h,
                                           quadratic=J,
                                           var_type='SPIN')
        return self._sampling(bqm,
                              beta=beta,
                              gamma=gamma,
                              num_sweeps=num_sweeps,
                              schedule=schedule,
                              num_reads=num_reads,
                              initial_state=initial_state,
                              updater=updater,
                              reinitialize_state=reinitialize_state,
                              seed=seed,
                              **kwargs)
Esempio n. 20
0
    def test_transfer_to_cxxjij(self):
        bqm = oj.BinaryQuadraticModel(self.h, self.J, 'SPIN', sparse=False)
        # to Dense
        ising_graph, offset = bqm.get_cxxjij_ising_graph()
        self.assertEqual(ising_graph.size(), len(bqm.variables))
        for i in range(len(bqm.variables) + 1):
            for j in range(i + 1, len(bqm.variables) + 1):
                self.assertAlmostEqual(bqm.interaction_matrix()[i, j],
                                       ising_graph.get_interactions()[i, j])
                self.assertAlmostEqual(ising_graph.get_interactions()[i, j],
                                       ising_graph.get_interactions()[j, i])

        #with offset
        bqm_qubo = oj.BinaryQuadraticModel.from_qubo(Q=self.Q)
        ising_graph, offset = bqm_qubo.get_cxxjij_ising_graph()
        bqm = bqm_qubo.change_vartype('SPIN', inplace=False)
        self.assertEqual(ising_graph.size(), len(bqm.variables))
        for i in range(len(bqm.variables) + 1):
            for j in range(i + 1, len(bqm.variables) + 1):
                self.assertAlmostEqual(bqm.interaction_matrix()[i, j],
                                       ising_graph.get_interactions()[i, j])
                self.assertAlmostEqual(ising_graph.get_interactions()[i, j],
                                       ising_graph.get_interactions()[j, i])

        self.assertAlmostEqual(offset, bqm.offset)

        # to Sparse
        bqm = oj.BinaryQuadraticModel(self.h, self.J, 'SPIN', sparse=True)
        ising_graph, offset = bqm.get_cxxjij_ising_graph()
        self.assertEqual(ising_graph.size(), len(bqm.variables))
        for i in range(ising_graph.size()):
            for j in ising_graph.adj_nodes(i):
                self.assertEqual(
                    ising_graph[i, j],
                    bqm.interaction_matrix()[min(i, j), max(i, j)] if i != j
                    else bqm.interaction_matrix()[i, len(bqm.variables)])
Esempio n. 21
0
def reverse_annealing():
    initial_state = [0, 0, 0]
    qubo = make_qubo()
    reverse_schedule = [[10, 3], (1, 3), (0.5, 3), (1, 3), (10, 5)]
    sqa = oj.SASampler(schedule=reverse_schedule, iteration=20)
    res = sqa.sample_qubo(qubo, initial_state=initial_state)
    print(res.min_samples)
    model = oj.BinaryQuadraticModel(Q=qubo, vartype='BINARY')
    print(model.calc_energy(res.min_samples['min_states'][0]))

    print('RQA')
    reverse_schedule = [[1, 1], [0.3, 3], [0.1, 5], [0.3, 3], [1, 3]]
    rqa_sampler = oj.SQASampler(schedule=reverse_schedule,
                                iteration=10,
                                beta=10)
    rqa_sampler = SQASampler(schedule=reverse_schedule, iteration=10)
    res = rqa_sampler.sample_qubo(qubo, initial_state=initial_state, seed=1)
    print(res.min_samples)
Esempio n. 22
0
    def sample_ising(self,
                     h,
                     J,
                     initial_state=None,
                     updater='single spin flip',
                     reinitilize_state=True,
                     seed=None,
                     **kwargs):
        """Sample from the specified Ising model.

        Args:
            h (dict):
                Linear biases of the Ising model.

            J (dict):
                Quadratic biases of the Ising model.

            **kwargs:
                Optional keyword arguments for the sampling method.

        Returns:
            :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}

        """

        vartype = openjij.SPIN
        bqm = openjij.BinaryQuadraticModel(h=h, J=J, vartype=vartype)
        return self.sampling(bqm,
                             initial_state=initial_state,
                             updater=updater,
                             reinitilize_state=reinitilize_state,
                             seed=seed,
                             **kwargs)
Esempio n. 23
0
    def sample_ising(self,
                     h,
                     J,
                     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=h,
                                             quadratic=J,
                                             var_type='SPIN')
        return self._sampling(model, beta_min, beta_max, num_sweeps, num_reads,
                              schedule, initial_state, updater,
                              reinitialize_state, seed, **kwargs)
Esempio n. 24
0
    def sample_qubo(self,
                    Q,
                    initial_state=None,
                    updater='single spin flip',
                    reinitilize_state=True,
                    seed=None,
                    **kwargs):
        """Sample from the specified QUBO.

        Args:
            Q (dict):
                Coefficients of a quadratic unconstrained binary optimization (QUBO) model.

            **kwargs:
                Optional keyword arguments for the sampling method.

        Returns:
            :obj:: `openjij.sampler.response.Response` object.

        Examples:
            This example submits a two-variable QUBO model.

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

        """

        vartype = openjij.BINARY
        bqm = openjij.BinaryQuadraticModel(Q=Q, vartype=vartype)
        return self.sampling(bqm,
                             initial_state=initial_state,
                             updater=updater,
                             reinitilize_state=reinitilize_state,
                             seed=seed,
                             **kwargs)
Esempio n. 25
0
File: test.py Progetto: y-yu/OpenJij
    def test_benchmark(self):
        h = {0: 1}
        J = {(0, 1): -1.0, (1, 2): -1.0}

        sa_samp = oj.SASampler()

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

        ground_state = [-1, -1, -1]
        ground_energy = oj.BinaryQuadraticModel(h, J).calc_energy(ground_state)
        step_num_list = np.linspace(10, 50, 5, dtype=np.int)
        bm_res = oj.benchmark([ground_state],
                              ground_energy,
                              solver,
                              time_param_list=step_num_list)
        self.assertTrue(
            set(bm_res) >=
            {'time', 'error', 'e_res', 'tts', 'tts_threshold_prob'})

        self.assertEqual(len(bm_res), len(step_num_list))
Esempio n. 26
0
    # make target instance
    N = 50
    h = {0: 1, 1: 1}
    J = {}
    for i in range(N - 1):
        for j in range(i + 1, N):
            J[(i, j)] = -1.0

    N = 30
    h = {0: -10}
    J = {(i, i + 1): 1 for i in range(N - 1)}

    ground_state = correct_state = [(-1)**i for i in range(N)]  # [-1]*N
    sa_samp = oj.SASampler()

    ground_energy = oj.BinaryQuadraticModel(h, J).calc_energy(ground_state)

    # make benchmark target solver
    def solver(time_param):
        return sa_samp.sample_ising(h, J, num_reads=100, num_sweeps=time_param)

    # benchmarking
    time_list = list(range(10, 101, 10))
    b_res = oj.solver_benchmark(solver,
                                time_list=time_list,
                                solutions=[ground_state])
    plt.xlabel('annealing time')
    plt.ylabel('TTS')
    plt.plot(b_res['time'], np.array(b_res['tts']), '.')
    plt.show()
Esempio n. 27
0
    def sample_ising(self,
                     h,
                     J,
                     beta=None,
                     gamma=None,
                     num_sweeps=None,
                     schedule=None,
                     num_reads=1,
                     initial_state=None,
                     updater='swendsenwang',
                     reinitialize_state=True,
                     seed=None,
                     **kwargs):

        bqm = openjij.BinaryQuadraticModel(linear=h,
                                           quadratic=J,
                                           var_type='SPIN')

        ising_graph = bqm.get_cxxjij_ising_graph()

        self._setting_overwrite(beta=beta,
                                gamma=gamma,
                                num_sweeps=num_sweeps,
                                num_reads=num_reads)
        self._annealing_schedule_setting(bqm, beta, gamma, num_sweeps,
                                         schedule)

        # make init state generator --------------------------------
        if initial_state is None:

            def init_generator():
                n = len(bqm.indices)
                init_num_cut = 10
                c_spins = ising_graph.gen_spin()
                _cut = np.random.uniform(0, 1, (n, init_num_cut))
                spin_config = [[(t, s**(_ti + 1))
                                for _ti, t in enumerate(np.sort(_cut[i]))]
                               for i, s in enumerate(c_spins)]
                return spin_config
        else:

            def init_generator():
                return initial_state

        # -------------------------------- make init state generator

        # choose updater -------------------------------------------
        sqa_system = cxxjij.system.ContinuousTimeIsing_Dense(
            init_generator(), ising_graph, self.gamma)
        _updater_name = updater.lower().replace('_', '').replace(' ', '')
        if _updater_name == 'swendsenwang':
            algorithm = cxxjij.algorithm.Algorithm_ContinuousTimeSwendsenWang_run
        else:
            raise ValueError('updater is one of "swendsen wang"')
        # ------------------------------------------- choose updater

        response = self._cxxjij_sampling(bqm, init_generator, algorithm,
                                         sqa_system, reinitialize_state, seed,
                                         **kwargs)

        response.info['schedule'] = self.schedule_info

        return response
Esempio n. 28
0
    def sample(self, bqm,
                     beta=None, gamma=None,
                     num_sweeps=None, schedule=None, trotter=None,
                     num_reads=1,
                     initial_state=None, updater='single spin flip',
                     sparse=False,
                     reinitialize_state=True, seed=None):
        """Sampling from the Ising model

        Args:
            bqm (oj.BinaryQuadraticModel) binary quadratic model
            beta (float, optional): inverse tempareture.
            gamma (float, optional): strangth of transverse field. Defaults to None.
            num_sweeps (int, optional): number of sweeps. Defaults to None.
            schedule (list[list[float, int]], optional): List of annealing parameter. Defaults to None.
            trotter (int): Trotter number.
            num_reads (int, optional): number of sampling. Defaults to 1.
            initial_state (list[int], optional): Initial state. Defaults to None.
            updater (str, optional): update method. Defaults to 'single spin flip'.
            reinitialize_state (bool, optional): Re-initilization at each sampling. Defaults to True.
            seed (int, optional): Sampling seed. Defaults to None.

        Raises:
            ValueError: 

        Returns:
            :class:`openjij.sampler.response.Response`: results

        Examples:
            
            for Ising case::

                >>> h = {0: -1, 1: -1, 2: 1, 3: 1}
                >>> J = {(0, 1): -1, (3, 4): -1}
                >>> sampler = oj.SQASampler()
                >>> res = sampler.sample_ising(h, J)

            for QUBO case::

                >>> Q = {(0, 0): -1, (1, 1): -1, (2, 2): 1, (3, 3): 1, (4, 4): 1, (0, 1): -1, (3, 4): 1}
                >>> sampler = oj.SQASampler()
                >>> res = sampler.sample_qubo(Q)
        """

        if type(bqm) == dimod.BinaryQuadraticModel:
            bqm = openjij.BinaryQuadraticModel(dict(bqm.linear), dict(bqm.quadratic), bqm.offset, bqm.vartype)

        ising_graph, offset = bqm.get_cxxjij_ising_graph()

        self._setting_overwrite(
            beta=beta, gamma=gamma,
            num_sweeps=num_sweeps, num_reads=num_reads,
            trotter=trotter
        )

        # set annealing schedule -------------------------------
        self._annealing_schedule_setting(
            bqm, beta, gamma, num_sweeps, schedule)
        # ------------------------------- set annealing schedule

        # make init state generator --------------------------------
        if initial_state is None:
            def init_generator(): return [ising_graph.gen_spin(seed) if seed != None else ising_graph.gen_spin()
                                          for _ in range(self.trotter)]
        else:
            if isinstance(initial_state, dict):
                initial_state = [initial_state[k] for k in bqm.variables]
            _init_state = np.array(initial_state)

            # 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()))

            trotter_init_state = [_init_state
                                  for _ in range(self.trotter)]

            def init_generator(): return trotter_init_state
        # -------------------------------- make init state generator

        # choose updater -------------------------------------------
        _updater_name = updater.lower().replace('_', '').replace(' ', '')
        if _updater_name not in self._algorithm:
            raise ValueError('updater is one of "single spin flip"')
        algorithm = self._algorithm[_updater_name] 
        sqa_system = self._make_system[_updater_name](
            init_generator(), ising_graph, self.gamma
        )
        # ------------------------------------------- choose updater

        response = self._cxxjij_sampling(
            bqm, init_generator,
            algorithm, sqa_system,
            reinitialize_state, seed
        )

        response.info['schedule'] = self.schedule_info

        return response
Esempio n. 29
0
 def test_interaction_matrix(self):
     bqm = oj.BinaryQuadraticModel(self.h, self.J, 'SPIN')
     ising_matrix = np.array([[0, -1, 0, 0, 1], [0, 0, -3, 0, -2],
                              [0, 0, 0, 0.5, 0], [0, 0, 0, 0, 0],
                              [0, 0, 0, 0, 1]])
     np.testing.assert_array_equal(bqm.interaction_matrix(), ising_matrix)
Esempio n. 30
0
 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)