Пример #1
0
    def sample(self, bqm, num_reads=10, flux_biases=[], **kwargs):
        # we are altering the bqm if flux_biases given

        info = dict(problem_id=str(uuid4()))
        label = kwargs.get('label')
        if label is not None:
            info.update(problem_label=label)

        if not flux_biases:
            ss = SimulatedAnnealingSampler().sample(bqm, num_reads=num_reads)
            ss.info.update(info)
            return ss

        new_bqm = bqm.copy()

        for v, fbo in enumerate(flux_biases):
            self.flux_biases_flag = True
            new_bqm.add_variable(v, 1000. * fbo)  # add the bias

        response = SimulatedAnnealingSampler().sample(new_bqm, num_reads=num_reads)

        # recalculate the energies with the old bqm
        return dimod.SampleSet.from_samples_bqm([{v: sample[v] for v in bqm.variables}
                                                 for sample in response.samples()],
                                                bqm, info=info)
Пример #2
0
    def test_maze_heuristic_response(self):
        """Small and simple maze to verify that it is possible get a solution.
        """
        # Create maze
        n_rows = 3
        n_cols = 3
        start = '0,0n'
        end = '3,2n'
        walls = ['1,0n', '2,1n', '2,2n']
        maze = Maze(n_rows, n_cols, start, end, walls)
        bqm = maze.get_bqm()

        # Sample and test that a response is given
        sampler = SimulatedAnnealingSampler()
        response = sampler.sample(bqm, num_reads=1000)
        response_sample = next(response.samples())
        self.assertGreaterEqual(len(response), 1)

        # Test heuristic response
        expected_solution = {
            '0,1w': 1,
            '1,1n': 1,
            '1,1w': 1,
            '2,0n': 1,
            '2,1w': 1,
            '2,2w': 1
        }
        fill_with_zeros(expected_solution, n_rows, n_cols, [start, end])
        self.compare(response_sample, expected_solution)
Пример #3
0
 def __init__(self,
              num_reads=None,
              initial_states_generator='random',
              **runopts):
     super(SteepestDescentProblemSampler, self).__init__(**runopts)
     self.num_reads = num_reads
     self.initial_states_generator = initial_states_generator
     self.sampler = SimulatedAnnealingSampler()
Пример #4
0
 def __init__(self, num_reads=None, num_sweeps=1000,
              beta_range=None, beta_schedule_type='geometric',
              initial_states_generator='random', **runopts):
     super(SimulatedAnnealingProblemSampler, self).__init__(**runopts)
     self.num_reads = num_reads
     self.num_sweeps = num_sweeps
     self.beta_range = beta_range
     self.beta_schedule_type = beta_schedule_type
     self.initial_states_generator = initial_states_generator
     self.sampler = SimulatedAnnealingSampler()
     self._stop_event = threading.Event()
Пример #5
0
    def __init__(self, hidlen, vislen, sampler="Test"):
        self.sep = 0
        if sampler == "LeapHybridSampler":
            self.sampler = LeapHybridSampler()  #accessing dwave
            self.sep = 1
        if sampler == "DWaveSampler":
            self.sampler = AutoEmbeddingComposite(DWaveSampler())
        if sampler == "Test":
            self.sampler = SimulatedAnnealingSampler()
        self.t_step = 1000
        self.stepsize = 0.1
        self.path = ""
        self.mute = True

        self.hidlen = hidlen  #handling indexes
        self.vislen = vislen
        self.outlen = 10
        self.hind = ['h' + str(i) for i in range(self.hidlen)]
        self.vind = ['v' + str(i) for i in range(self.vislen)]
        self.ind = self.hind + self.vind

        self.cmap = []
        self.coef = np.zeros(
            (self.vislen + self.hidlen, self.vislen + self.hidlen),
            dtype=np.float_)
        #self.Q = {(i, j): self.coef[i][j] for i in self.ind for j in self.ind}
        self.bqm = dimod.BinaryQuadraticModel(self.coef, 'SPIN')

        self.response = 0  #response and data from it
        self.answerlen = 0
        self.answer = []
        self.index = []
        for i in range(self.hidlen + self.vislen):
            self.index += [i]
        self.answer_occ = []
        self.answern = 0
        self.prob = []
        self.top = [0] * 3
        self.expected = 0

        self.images = []  #images from dataset
        self.label = 0
        self.labels = []
        self.chosen_images = []
        self.prob = []
        self.chosen_prob = []

        self.single_unfixed = []
        self.double_unfixed = []
        self.single_fixed = []
        self.double_fixed = []
        self.delta = []
        self.mean_single = []
Пример #6
0
class SimulatedAnnealingSubproblemSampler(Runnable, traits.SubproblemSampler):
    """A simulated annealing sampler for a subproblem.

    Args:
        num_reads (int, optional, default=1):
            Number of states (output solutions) to read from the sampler.
        sweeps (int, optional, default=1000):
            Number of sweeps or steps.

    Examples:
        See examples on https://docs.ocean.dwavesys.com/projects/hybrid/en/latest/reference/samplers.html#examples.
    """
    def __init__(self, num_reads=1, sweeps=1000):
        super(SimulatedAnnealingSubproblemSampler, self).__init__()
        self.num_reads = num_reads
        self.sweeps = sweeps
        self.sampler = SimulatedAnnealingSampler()
        self._stop_event = threading.Event()

    def __repr__(self):
        return ("{self}(num_reads={self.num_reads!r}, "
                "sweeps={self.sweeps!r})").format(self=self)

    def next(self, state):
        subbqm = state.subproblem
        response = self.sampler.sample(
            subbqm,
            num_reads=self.num_reads,
            sweeps=self.sweeps,
            interrupt_function=lambda: self._stop_event.is_set())
        return state.updated(subsamples=response)

    def stop(self):
        self._stop_event.set()
Пример #7
0
    def _get_sampler(self, profile, solver):
        "Return a dimod.Sampler object."
        # Handle built-in software samplers as special cases.
        info = {}
        if solver != None:
            info["solver_name"] = solver
        if solver == "exact":
            return ExactSolver(), info
        elif solver == "neal":
            return SimulatedAnnealingSampler(), info
        elif solver == "tabu":
            return TabuSampler(), info

        # In the common case, read the configuration file, either the
        # default or the one named by the DWAVE_CONFIG_FILE environment
        # variable.
        if profile != None:
            info["profile"] = profile
        try:
            with Client.from_config(profile=profile) as client:
                if solver == None:
                    solver = client.default_solver
                else:
                    solver = {"name": solver}
                sampler = DWaveSampler(profile=profile, solver=solver)
                info = {
                    "solver_name": sampler.solver.name,
                    "endpoint": client.endpoint
                }
                return sampler, info
        except Exception as err:
            self.qmasm.abend("Failed to construct a sampler (%s)" % str(err))
Пример #8
0
class SteepestDescentProblemSampler(traits.ProblemSampler, traits.SISO,
                                    Runnable):
    """A steepest descent solver for a complete problem.

    Args:
        num_reads (int, optional, default=len(state.samples) or 1):
            Number of states (output solutions) to read from the sampler.

        initial_states_generator (str, 'none'/'tile'/'random', optional, default='random'):
            Defines the expansion of input state samples into `initial_states`
            for the steepest descent, if fewer than `num_reads` samples are
            present. See :meth:`greedy.sampler.SteepestDescentSolver.sample`.

    """
    def __init__(self,
                 num_reads=None,
                 initial_states_generator='random',
                 **runopts):
        super(SteepestDescentProblemSampler, self).__init__(**runopts)
        self.num_reads = num_reads
        self.initial_states_generator = initial_states_generator
        self.sampler = SimulatedAnnealingSampler()

    def __repr__(self):
        return ("{self}(num_reads={self.num_reads!r}, "
                "initial_states_generator={self.initial_states_generator!r})"
                ).format(self=self)

    def next(self, state, **runopts):
        samples = self.sampler.sample(
            state.problem,
            num_reads=self.num_reads,
            initial_states=state.samples,
            initial_states_generator=self.initial_states_generator)
        return state.updated(samples=samples)
Пример #9
0
class SimulatedAnnealingProblemSampler(Runnable, traits.ProblemSampler):
    """A simulated annealing sampler for a complete problem.

    Args:
        num_reads (int, optional, default=1):
            Number of states (output solutions) to read from the sampler.

        sweeps (int, optional, default=1000):
            Number of sweeps or steps.

    """
    def __init__(self, num_reads=1, sweeps=1000, **runopts):
        super(SimulatedAnnealingProblemSampler, self).__init__(**runopts)
        self.num_reads = num_reads
        self.sweeps = sweeps
        self.sampler = SimulatedAnnealingSampler()
        self._stop_event = threading.Event()

    def __repr__(self):
        return ("{self}(num_reads={self.num_reads!r}, "
                "sweeps={self.sweeps!r})").format(self=self)

    def next(self, state, **runopts):
        bqm = state.problem
        response = self.sampler.sample(
            bqm,
            num_reads=self.num_reads,
            sweeps=self.sweeps,
            interrupt_function=lambda: self._stop_event.is_set())
        return state.updated(samples=response)

    def halt(self):
        self._stop_event.set()
Пример #10
0
    def _init_sampler(self):
        """Allows for re-init in case a solver goes offline."""

        if self._qpu:
            # select the first available sampler in the `DW_2000Q` class
            self._sampler = EmbeddingComposite(
                DWaveSampler(solver=dict(qpu=True)))
        else:
            self._sampler = SimulatedAnnealingSampler()

        self._sampler_args = {}
        if 'num_reads' in self._sampler.parameters:
            self._sampler_args['num_reads'] = 50
        if 'answer_mode' in self._sampler.parameters:
            self._sampler_args['answer_mode'] = 'histogram'
        if 'chain_strength' in self._sampler.parameters:
            self._sampler_args['chain_strength'] = 2.0
Пример #11
0
    def sample(self, bqm, num_reads=10, flux_biases=[]):
        # we are altering the bqm
        new_bqm = bqm.copy()

        for v, fbo in enumerate(flux_biases):
            self.flux_biases_flag = True
            new_bqm.add_variable(v, 1000. * fbo)  # add the bias

        response = SimulatedAnnealingSampler().sample(new_bqm,
                                                      num_reads=num_reads)

        energies = [
            bqm.energy(sample) for sample in response.samples(sorted_by=None)
        ]

        return dimod.Response.from_samples(response.samples(sorted_by=None),
                                           {'energy': energies}, {},
                                           bqm.vartype)
Пример #12
0
class SimulatedAnnealingSubproblemSampler(traits.SubproblemSampler, traits.SISO, Runnable):
    """A simulated annealing sampler for a subproblem.

    Args:
        num_reads (int, optional, default=len(state.subsamples) or 1):
            Number of states (output solutions) to read from the sampler.

        num_sweeps (int, optional, default=1000):
            Number of sweeps or steps.

        beta_range (tuple, optional):
            A 2-tuple defining the beginning and end of the beta schedule, where
            beta is the inverse temperature. The schedule is applied linearly in
            beta. Default range is set based on the total bias associated with
            each node.

        beta_schedule_type (string, optional, default='geometric'):
            Beta schedule type, or how the beta values are interpolated between
            the given 'beta_range'. Supported values are: linear and geometric.

        initial_states_generator (str, 'none'/'tile'/'random', optional, default='random'):
            Defines the expansion of input state subsamples into `initial_states`
            for the simulated annealing, if fewer than `num_reads` subsamples are
            present. See :meth:`~neal.SimulatedAnnealingSampler.sample`.

    See :ref:`samplers-examples`.
    """

    def __init__(self, num_reads=None, num_sweeps=1000,
                 beta_range=None, beta_schedule_type='geometric',
                 initial_states_generator='random', **runopts):
        super(SimulatedAnnealingSubproblemSampler, self).__init__(**runopts)
        self.num_reads = num_reads
        self.num_sweeps = num_sweeps
        self.beta_range = beta_range
        self.beta_schedule_type = beta_schedule_type
        self.initial_states_generator = initial_states_generator
        self.sampler = SimulatedAnnealingSampler()
        self._stop_event = threading.Event()

    def __repr__(self):
        return ("{self}(num_reads={self.num_reads!r}, "
                       "num_sweeps={self.num_sweeps!r}, "
                       "initial_states_generator={self.initial_states_generator!r})").format(self=self)

    def next(self, state, **runopts):
        subsamples = self.sampler.sample(
            state.subproblem, num_reads=self.num_reads, num_sweeps=self.num_sweeps,
            beta_range=self.beta_range, beta_schedule_type=self.beta_schedule_type,
            initial_states=state.subsamples,
            initial_states_generator=self.initial_states_generator,
            interrupt_function=lambda: self._stop_event.is_set())
        return state.updated(subsamples=subsamples)

    def halt(self):
        self._stop_event.set()
Пример #13
0
    def sample(self, bqm, num_reads=10, flux_biases=[]):
        # we are altering the bqm

        if not flux_biases:
            return SimulatedAnnealingSampler().sample(bqm, num_reads=num_reads)

        new_bqm = bqm.copy()

        for v, fbo in enumerate(flux_biases):
            self.flux_biases_flag = True
            new_bqm.add_variable(v, 1000. * fbo)  # add the bias

        response = SimulatedAnnealingSampler().sample(new_bqm,
                                                      num_reads=num_reads)

        # recalculate the energies with the old bqm
        return dimod.SampleSet.from_samples_bqm(
            [{v: sample[v]
              for v in bqm} for sample in response.samples()], bqm)
Пример #14
0
 def test_basic_operation(self):
     bqm = dimod.BinaryQuadraticModel({}, {
         'ab': 1,
         'bc': 1,
         'ca': 1
     }, 0, dimod.SPIN)
     sampleset = KerberosSampler().sample(
         bqm,
         qpu_sampler=SimulatedAnnealingSampler(),
         max_subproblem_size=1)
Пример #15
0
def agent_step_1(current_state, Q):
    '''
    Implements a Grid World problem step.
    '''
    sample_dict = list(SimulatedAnnealingSampler().sample_qubo(
        Q, num_reads=1).samples())[0]

    a_list = list()
    for k in sorted_qubit_indexes_tuple:
        a_list.append(sample_dict[k])
    action_index = real_01qbits_to_virtual_qubits_dict[tuple(a_list)]

    if False:
        print(tuple(a_list))
        print(sorted(real_01qbits_to_virtual_qubits_dict.items()))
        exit(0)

    # print(tuple(action_set_to_encoding_tuple_dict.keys()))

    action_index = action_set_to_encoding_tuple_dict[\
            available_actions_per_position_tuple[ current_state[0][0] ][ current_state[0][1] ]\
        ][action_index]

    if action_index == 0:
        new_position = (\
            current_state[0][0] - 1,
            current_state[0][1]
        )
    elif action_index == 1:
        new_position = (\
            current_state[0][0],
            current_state[0][1] + 1,
        )
    elif action_index == 2:
        new_position = (\
            current_state[0][0] + 1,
            current_state[0][1],
        )
    elif action_index == 3:
        new_position = (\
            current_state[0][0],
            current_state[0][1] - 1,
        )
    else:
        new_position = current_state[0]

    return\
        (\
            (\
                new_position,\
                available_state_dict[new_position],\
            ),\
            sample_dict,\
            action_index,\
        )
Пример #16
0
    def test_unstructured_child_sampler(self):
        q = QPUSubproblemAutoEmbeddingSampler(qpu_sampler=SimulatedAnnealingSampler())

        # test sampler stays unstructured
        self.assertFalse(isinstance(q.sampler, dimod.Structured))

        # test sampling works
        bqm = dimod.BinaryQuadraticModel({'a': 1}, {}, 0, 'SPIN')
        init = State.from_subsample({'a': 1}, bqm)
        res = q.run(init).result()
        self.assertEqual(res.subsamples.first.energy, -1)
def solve(hs, js):
    response = SimulatedAnnealingSampler().sample_ising(
        hs,
        js,
        beta_range=BETA_RANGE,
        num_reads=NUM_READS,
        num_sweeps=NUM_SWEEPS,
        beta_schedule_type=BETA_SCHEDULE_TYPE,
        seed=1)

    # NUM_READS個の解の中から、もっとも良い解を返します
    return tuple(response.record.sample[np.argmin(response.record.energy)])
    def __init__(self, qpu):
        maps = dict()
        maps['Global'] = global_signed_social_network()

        # The Syria subregion
        syria_groups = set()
        for v, data in maps['Global'].nodes(data=True):
            if 'map' not in data:
                continue
            if data['map'] in {'Syria', 'Aleppo'}:
                syria_groups.add(v)
        maps['Syria'] = maps['Global'].subgraph(syria_groups)

        # The Iraq subregion
        iraq_groups = set()
        for v, data in maps['Global'].nodes(data=True):
            if 'map' not in data:
                continue
            if data['map'] == 'Iraq':
                iraq_groups.add(v)
        maps['Iraq'] = maps['Global'].subgraph(iraq_groups)

        self._maps = maps

        self._qpu = qpu
        if qpu:
            from dwave.system.composites import EmbeddingComposite
            from dwave.system.samplers import DWaveSampler
            self._sampler = EmbeddingComposite(DWaveSampler())
        else:
            from neal import SimulatedAnnealingSampler
            self._sampler = SimulatedAnnealingSampler()

        self._sampler_args = {}
        if 'num_reads' in self._sampler.parameters:
            self._sampler_args['num_reads'] = 50
        if 'answer_mode' in self._sampler.parameters:
            self._sampler_args['answer_mode'] = 'histogram'
        if 'chain_strength' in self._sampler.parameters:
            self._sampler_args['chain_strength'] = 2.0
Пример #19
0
def solve_neal(Q, seed=None, **kwargs):
    from neal import SimulatedAnnealingSampler
    # generate seed for logging purpose
    if seed is None:
        import random
        seed = random.randint(0, 1 << 31)
    # run neal
    start_time = time.process_time()
    response = SimulatedAnnealingSampler().sample_qubo(Q, seed=seed, **kwargs)
    exec_time = time.process_time() - start_time
    logger.info(
        f'QUBO of size {len(Q)} sampled in {exec_time:.2f}s (NEAL, seed={seed}).'
    )
    return response
Пример #20
0
    def test_external_embedding_sampler(self):
        bqm = dimod.BinaryQuadraticModel.from_ising({'a': 1}, {})
        init = State.from_subproblem(bqm, embedding={'a': [0]})

        sampler = dimod.StructureComposite(
            SimulatedAnnealingSampler(), nodelist=[0], edgelist=[])

        workflow = QPUSubproblemExternalEmbeddingSampler(qpu_sampler=sampler)

        # run mock sampling
        res = workflow.run(init).result()

        # verify mock sampler received custom kwargs
        self.assertEqual(res.subsamples.first.energy, -1)
def main(sampler_type, region, show, inspect):

    if sampler_type is None:
        print("No solver selected, defaulting to hybrid")
        sampler_type = 'hybrid'

    # get the appropriate signed social network
    G = global_signed_social_network(region=region)

    # choose solver and any tuning parameters needed
    if sampler_type == 'cpu':
        params = dict(num_reads=100)
        sampler = SimulatedAnnealingSampler()

    elif sampler_type == 'hybrid':
        params = dict()
        sampler = LeapHybridSampler()

    elif sampler_type == 'qpu':
        params = dict(
            num_reads=100,
            chain_strength=2.0,
        )
        sampler = dimod.TrackingComposite(EmbeddingComposite(DWaveSampler()))

    else:
        raise RuntimeError("unknown solver type")

    # use the chosen sampler (passing in the parameters)
    edges, colors = dnx.structural_imbalance(
        G, sampler, label='Example - Structural Imbalance', **params)

    if inspect and sampler_type == 'qpu':
        dwave.inspector.show(sampler.output)

    print("Found", len(edges), 'violations out of', len(G.edges), 'edges')

    draw_social_network(G, colors)

    if show:
        plt.show()
    else:
        filename = 'structural imbalance {} {}.png'.format(
            sampler_type, region)
        plt.savefig(filename, facecolor='white')
        plt.clf()
Пример #22
0
    def get_sampler(self, profile, solver):
        "Return a dimod.Sampler object and associated solver information."
        # Handle built-in software samplers as special cases.
        info = {}
        if solver != None:
            info["solver_name"] = solver
        if solver == "exact":
            return ExactSolver(), info, {}
        elif solver == "neal":
            return SimulatedAnnealingSampler(), info, {}
        elif solver == "tabu":
            return TabuSampler(), info, {}
        elif solver == "kerberos" or (solver != None
                                      and solver[:9] == "kerberos,"):
            base_sampler = KerberosSampler()
            try:
                sub_sampler_name = solver.split(",")[1]
            except IndexError:
                sub_sampler_name = None
            sub_sampler, sub_info, params = self.get_sampler_from_config(
                profile, sub_sampler_name, "qpu")
            info.update(self._recursive_properties(sub_sampler))
            info["solver_name"] = "kerberos + %s" % sub_info["solver_name"]
            params["qpu_sampler"] = sub_sampler
            return base_sampler, info, params
        elif solver == "qbsolv" or (solver != None
                                    and solver[:7] == "qbsolv,"):
            base_sampler = QBSolv()
            try:
                sub_sampler_name = solver.split(",")[1]
            except IndexError:
                sub_sampler_name = None
            sub_sampler, sub_info, params = self.get_sampler(
                profile, sub_sampler_name)
            if getattr(sub_sampler, "structure", None) != None:
                sub_sampler = EmbeddingComposite(sub_sampler)
            info.update(self._recursive_properties(sub_sampler))
            info["solver_name"] = "QBSolv + %s" % sub_info["solver_name"]
            params["solver"] = sub_sampler
            return base_sampler, info, params

        # In the common case, read the configuration file, either the
        # default or the one named by the DWAVE_CONFIG_FILE environment
        # variable.
        return self.get_sampler_from_config(profile, solver)
Пример #23
0
def main(sampler_type, region, show):

    if sampler_type is None:
        print("No solver selected, defaulting to hybrid")
        sampler_type = 'hybrid'

    if region == 'global' and sampler_type == 'qpu':
        print("Given region is too large for the QPU, please choose another "
              "region or use hybrid.")

    # get the appropriate signed social network
    G = global_signed_social_network(region=region)

    # choose solver and any tuning parameters needed
    if sampler_type == 'cpu':
        params = dict(num_reads=100)
        sampler = SimulatedAnnealingSampler()

    elif sampler_type == 'hybrid':
        params = dict()
        sampler = LeapHybridSampler()

    elif sampler_type == 'qpu':
        params = dict(
            num_reads=100,
            chain_strength=2.0,
        )
        sampler = EmbeddingComposite(DWaveSampler())

    else:
        raise RuntimeError("unknown solver type")

    # use the chosen sampler (passing in the parameters)
    edges, colors = dnx.structural_imbalance(G, sampler, **params)

    print("Found", len(edges), 'violations out of', len(G.edges), 'edges')

    draw_social_network(G, colors)

    if show:
        plt.show()
    else:
        filename = 'stuctural imbalance {} {}.png'.format(sampler_type, region)
        plt.savefig(filename, facecolor='white', dpi=500)
        plt.clf()
Пример #24
0
    def create_sampler(self):
        if None == self.sampler:
            composite = None
            _inner_sampler = None
            if self.mode == self.op_mode_quantum:
                _inner_sampler = self.base_sampler
            elif self.mode == self.op_mode_simulated_annealing:
                _inner_sampler = SimulatedAnnealingSampler()
            elif self.mode == self.op_mode_qbsolv:
                _inner_sampler = QBSolv()
            else:
                raise ValueError(
                    "op_mode {} is not known. (only 1,2,3)".format(self.mode))

            composite = StructureComposite(_inner_sampler,
                                           self.base_sampler.nodelist,
                                           self.base_sampler.edgelist)

            self.sampler = FixedEmbeddingComposite(composite, self.embedding)
Пример #25
0
def get_sampler(sampler_name, graph):
    from config import REGIST_INFO_PATH

    with open(REGIST_INFO_PATH, 'r') as f:
        regist_info = json.load(f)

    if sampler_name == 'exact':
        if check_graph(graph):
            sampler = ExactSolver()
        else:
            return TOO_MANY_NODES

    elif sampler_name == 'simulated annealing':
        return SimulatedAnnealingSampler()

    elif sampler_name == 'dwave':
        if DWAVE_ALLOWED:
            sampler = EmbeddingComposite(DWaveSampler(**regist_info))
        else:
            return DWAVE_NOT_ALLOWED

    return sampler
Пример #26
0
def env_agent_step(\
  current_state,\
  available_actions_per_position_tuple,\
  available_actions_list,\
  Q_hh,\
  Q_vh,\
  replica_count,\
  average_size,\
  apply_action_function\
 ):
    '''
	It implements an agent step in the context of the Grid World agent.

	current_state
		It is a tuple containing at index 0 the row and column index of the agent. At
		index 1, it contains the qubit representation of that position.

	available_actions_per_position_tuple
		It contains the action index for the Grid World agent.
        0 : ^
        1 : >
        2 : v
        3 : <
        4 : hold

	available_actions_list
		It contains the actions qubit encoding.

	Q_hh
		It is a dictionary where key pairs (i,j) where i < j are assigned hidden-hidden weights.

	Q_vh
		It is a dictionary where key pairs are assigned visible-hidden weights.

	replica_count
		It contains the number of replicas in the Hamiltonian of one dimension higher.

	average_size
		It contains the number of configurations of the Hamiltonian of one dimension higher
		used for extracting the value.


	'''
    max_tuple = None

    if not (0 <= current_state[0][0] < 3 and 0 <= current_state[0][1]):
        print('first debug:', current_state)

    for action_index in filter(
      # lambda e: e != 4,
      lambda e: True,
      available_actions_per_position_tuple[\
      current_state[0][0]][current_state[0][1]]
     ):

        vis_iterable = current_state[1] + available_actions_list[action_index]

        general_Q = create_general_Q_from(Q_hh, Q_vh, vis_iterable)

        samples = list(SimulatedAnnealingSampler().sample_qubo(
            general_Q, num_reads=replica_count * average_size).samples())

        random.shuffle(samples)

        current_F = get_free_energy(
            get_3d_hamiltonian_average_value(samples, general_Q, replica_count,
                                             average_size, 0.5, 2),
            samples,
            replica_count,
            2,
        )

        if max_tuple is None or max_tuple[0] < current_F:
            max_tuple = (current_F, action_index, samples, vis_iterable)

    return\
     (
      apply_action_function(), # new state
      max_tuple[0],        # F value
      max_tuple[2],            # samples
      max_tuple[3],            # used iterable vector
      max_tuple[1],            # action index
      current_state[0],        # old_position
     )
Пример #27
0
#!/usr/bin/env python3
# -*- coding: utf-8 -*-

from dimod import BinaryQuadraticModel
from neal import SimulatedAnnealingSampler

sampler = SimulatedAnnealingSampler()

x0, x1, y = ('x0', 'x1', 'y')
a, b, c = 1, 1, 3
Q = {(y, y): c, (x0, y): -2*b, (x1, y): -2*b, (x0, x1): a, (x0, x0): 0}

bqm = BinaryQuadraticModel.from_qubo(Q)
response = sampler.sample(bqm, num_reads=5000)

results = {}
for datum in response.data(['sample', 'energy', 'num_occurrences']):
    key = (tuple(dict(datum.sample).items()), float(datum.energy))
    if key in results:
        results[key] = (datum.sample, results[key][1] + datum.num_occurrences)
    else:
        results[key] = (datum.sample, datum.num_occurrences)

num_runs = sum([results[key][1] for key in results])
for key in results:
    try:
        print(results[key][0], "Energy: ", key[1],
              f"Occurrences: {results[key][1]/num_runs*100:.2f}%")
    except KeyError:
        pass
Пример #28
0
Let's see if we can mix things up a bit.

The constraints technique used in this tutorial was based on Dr. Haiou
Shen's web page on n-queens and SAT solvers:
- https://sites.google.com/site/haioushen/search-algorithm/solvean-queensproblemusingsatsolver

'''

# At the top of this file, set useQpu to True to use a live QPU.
if (useQpu):
    sampler = DWaveSampler()
    # We need an embedding composite sampler because not all qubits are
    # working. A trivial embedding lets us avoid dead qubits.
    sampler = EmbeddingComposite(sampler)
else:
    sampler = SimulatedAnnealingSampler()

# Every time I try to type "print," my fingers type "printf."
# So, I am going to use "p" instead!
p = print

# We will want to ask input now and then; Python 2 and Python 3 handle
# differently.
try:
    input  # We want to use the input() function
except:
    input = raw_input  # Python 2 has a raw_input() function

# The mysterial Q variable will be a lookup for drawing on the screen.
Q = {}
Q[0] = '*'
Пример #29
0
def generateSimulatedSamples(qubo, num_reads=100):

    #https://docs.ocean.dwavesys.com/projects/neal/en/latest/reference/generated/neal.sampler.SimulatedAnnealingSampler.sample.html
    return SimulatedAnnealingSampler().sample_qubo(qubo, num_reads=num_reads)
Пример #30
0
print('Given virtual qubits x1, x2, and z, list possible solutions where:')
print('  z = AND(x1, x2)')
print('')

# At the top of this file, set useQpu to True to use a live QPU.
#
# For this tutorial we need a triangular configution, but the physical
# topology of the QPU does not have triangles. There is a technique
# called "embedding" that allows us to map our virtual problem onto a
# physical platform. The concept of embedding is described more
# thoroughly in the embedding tutorials.
if (useQpu):
    sampler = DWaveSampler()  # live QPU
    sampler_embedded = EmbeddingComposite(sampler)  # we will need to embed
else:
    sampler = SimulatedAnnealingSampler()  # simulated quantum annealer
    sampler_embedded = sampler  # we do not need to embed for a simulation

# The Q variable is called the quadratic. It is a list of qubit biases
# and couplings. This configuration for AND is equivalent to the
# equation:
#
#   energy = ( (x1 * x2 * 1) + (x1 * z * -2) + (x2 * z * -2) + (z * 3) )
#
# In plain language, we want energy to be the lowest possible value
# only when z is the boolean AND of x1 and x2, or when z = x1 * x2.
Q = {('x1', 'x2'): 1, ('x1', 'z'): -2, ('x2', 'z'): -2, ('z', 'z'): 3}

# A sampler returns one or more possible solutions. We are looking for
# solutions that have the lowest possible energy value. The num_reads
# argument means we want to try and solve this 40 times.