Example #1
0
    def __init__(self, raw_results, answer, problem, all_vars):
        # Store our arguments.
        self.raw_results = raw_results
        self.answer = answer
        self.problem = problem

        # Unembed the solutions.  Fix rather than discard invalid solutions.
        if self.problem.embedding == {}:
            fixed_answer = self.answer.copy()
        else:
            fixed_answer = unembed_sampleset(self.answer, self.problem.embedding,
                                             self.problem.logical.bqm,
                                             chain_break_method=chain_breaks.majority_vote)

        # Construct one Solution object per solution.
        self.solutions = []
        energies = fixed_answer.record.energy
        tallies = fixed_answer.record.num_occurrences
        fixed_solns = fixed_answer.record.sample
        raw_solns = self.answer.record.sample
        sym2col, num2col = self._map_to_column(fixed_answer,
                                               self.problem.embedding,
                                               self.problem.qmasm.sym_map)
        for i in range(len(fixed_solns)):
            sset = self.answer.slice(i, i + 1)
            self.solutions.append(Solution(self.problem, sym2col, num2col, sset,
                                           fixed_solns[i], tallies[i], energies[i],
                                           all_vars))

        # Store the frequency of chain breaks across the entire SampleSet.
        self.chain_breaks = chain_break_frequency(self.answer, self.problem.embedding)
Example #2
0
def postprocess(X, embedded_solution_set, embedding, model):
    ''' Find centroids and assignments from binary solution of embedded model
    
    Args:
        X: input data
        embedded_solution: embedded solution set produced by annealing
        embedding: embedding used to convert from logical to embedded model
        model: logical BQM model

    Returns:
        centroids: Array containing each centnroid as a row vector in a k x d matrix
        assignments: cluster assignments of each point as list
    '''
    sample_set = unembed_sampleset(embedded_solution_set, embedding, model)
    solution = sample_set.first.sample
    N = np.shape(X)[0]
    d = np.shape(X)[1]
    k = len(solution) // N
    assignments = np.array([0] * N)
    M = np.zeros((k, d))
    cluster_sizes = np.zeros(k)
    for i in range(N):
        for j in range(k):
            if solution[i + j * N] == 1:
                M[j] += X[i]
                cluster_sizes[j] += 1.0
                assignments[i] = j
                break
    for i in range(k):
        M[i] /= cluster_sizes[i]
    return M, assignments
Example #3
0
File: 3.py Project: Ocete/TFG
def solve_qubo_dwave(Q, num_reads=1000):
    # Create the solver (connecting to D-Wave) and the Sampler
    config_file = '../dwave.conf'
    client = Client.from_config(config_file, profile='ocete')
    solver = client.get_solver(
    )  # Available QPUs: DW_2000Q_2_1 (2038 qubits), DW_2000Q_5 (2030 qubits)
    dwsampler = DWaveSampler(config_file=config_file)

    # We need to embed Q into a valid graph for the D-Wave architecture
    edgelist = solver.edges
    adjdict = edgelist_to_adjacency(edgelist)
    embed = minorminer.find_embedding(Q, edgelist)
    Q_embeded = embed_qubo(Q, embed, adjdict)

    # Obtain the response from the solver. This is the actual D-Wave execution!
    start = time.time()
    response_qpt = dwsampler.sample_qubo(Q_embeded, num_reads=num_reads)
    qpu_time = time.time() - start
    client.close()

    # Transform the response from the embeded graph to our original architecture
    bqm = dimod.BinaryQuadraticModel.from_qubo(Q)
    unembedded = unembed_sampleset(response_qpt,
                                   embed,
                                   bqm,
                                   chain_break_method=majority_vote)

    # Order the solutions by lower energy
    return unembedded, qpu_time
Example #4
0
 def broken_chains(self):
     "Return True if the solution contains broken chains."
     unbroken = unembed_sampleset(self.raw_ss,
                                  self.problem.embedding,
                                  self.problem.logical.bqm,
                                  chain_break_method=chain_breaks.discard)
     return len(unbroken) == 0
Example #5
0
        def async_unembed(response):
            # unembed the sampleset aysnchronously.

            warninghandler.chain_break(response, embedding)

            sampleset = unembed_sampleset(
                response,
                embedding,
                source_bqm=bqm,
                chain_break_method=chain_break_method,
                chain_break_fraction=chain_break_fraction,
                return_embedding=return_embedding)

            if return_embedding:
                sampleset.info['embedding_context'].update(
                    embedding_parameters=embedding_parameters,
                    chain_strength=embedding.chain_strength)

            if chain_break_fraction and len(sampleset):
                warninghandler.issue(
                    "All samples have broken chains",
                    func=lambda:
                    (sampleset.record.chain_break_fraction.all(), None))

            if warninghandler.action is WarningAction.SAVE:
                # we're done with the warning handler so we can just pass the list
                # off, if later we want to pass in a handler or similar we should
                # do a copy
                sampleset.info.setdefault('warnings',
                                          []).extend(warninghandler.saved)

            return sampleset
Example #6
0
    def load_samplesets(self, bqm, target, embedding, tags=[], unembed_args=None):
        bqm_id = self.id_bqm(bqm)
        target_id = self.id_target(target)
        embedding_id = self.id_embedding(embedding)

        dir_path = [self.samplesets_path,bqm_id,target_id,embedding_id]
        samplesets_path = os.path.join(*dir_path)

        samplesets = []
        for root, dirs, files in os.walk(samplesets_path):
            root_dirs = os.path.normpath(root).split(os.path.sep)
            if all(tag in root_dirs for tag in tags):
                for file in files:
                    sampleset_path = os.path.join(root,file)
                    with open(sampleset_path,'r') as fp:
                        sampleset = _load(fp,cls=DimodDecoder)
                    samplesets.append(sampleset)

        if embedding is "":
            return samplesets
        elif not isinstance(embedding,(Embedding,dict)):
            raise ValueError("Embedding alias or id cannot be used to unembed")

        if unembed_args is None:
            return samplesets
        else:
            return [unembed_sampleset(s,embedding,bqm,**unembed_args) for s in samplesets]
Example #7
0
def solve_ising_dwave(hii, Jij):
    config_file = '/media/sf_QWorld/QWorld/QA_DeNovoAsb/dwcloud.conf'
    client = Client.from_config(config_file, profile='aritra')
    solver = client.get_solver(
    )  # Available QPUs: DW_2000Q_2_1 (2038 qubits), DW_2000Q_5 (2030 qubits)
    dwsampler = DWaveSampler(config_file=config_file)

    edgelist = solver.edges
    adjdict = edgelist_to_adjacency(edgelist)
    embed = minorminer.find_embedding(Jij.keys(), edgelist)
    [h_qpu, j_qpu] = embed_ising(hii, Jij, embed, adjdict)

    response_qpt = dwsampler.sample_ising(h_qpu,
                                          j_qpu,
                                          num_reads=solver.max_num_reads())
    client.close()

    bqm = dimod.BinaryQuadraticModel.from_ising(hii, Jij)
    unembedded = unembed_sampleset(response_qpt,
                                   embed,
                                   bqm,
                                   chain_break_method=majority_vote)
    print("Maximum Sampled Configurations from D-Wave\t===>")
    solnsMaxSample = sorted(unembedded.record, key=lambda x: -x[2])
    for i in range(0, 10):
        print(solnsMaxSample[i])
    print("Minimum Energy Configurations from D-Wave\t===>")
    solnsMinEnergy = sorted(unembedded.record, key=lambda x: +x[1])
    for i in range(0, 10):
        print(solnsMinEnergy[i])
Example #8
0
def solve_qubo_dwave(Q,
                     n_genome_reads,
                     num_reads=100,
                     label='',
                     annealing_time=20):
    # Create the solver (connecting to D-Wave) and the Sampler
    config_file = '../dwave_adv.conf'
    client = Client.from_config(config_file, profile='ocete')
    solver = client.get_solver('Advantage_system1.1')
    dwsampler = DWaveSampler(
        solver={
            'qpu': True,
            'topology__type': 'pegasus',
            'annealing_time': annealing_time
        },  # Watch out, Leap doesn seem to take into account
        # this parameter, you have to give it as  a paramater in the dwsampler.sample() call
        token=token,
        endpoint=endpoint)

    # We need to embed Q into a valid graph for the D-Wave architecture
    adjdict = edgelist_to_adjacency(solver.edges)
    embed = minorminer.find_embedding(Q, solver.edges)
    Q_embeded = embed_qubo(Q, embed, adjdict)

    # Obtain the response from the solver. This is the actual D-Wave execution!
    start = time.time()
    response_qpt = dwsampler.sample_qubo(Q_embeded,
                                         num_reads=num_reads,
                                         label=label,
                                         annealing_time=annealing_time)
    qpu_time = time.time() - start
    client.close()

    # Transform the response from the embeded graph to our original architecture
    bqm = dimod.BinaryQuadraticModel.from_qubo(Q)
    unembedded = unembed_sampleset(response_qpt,
                                   embed,
                                   bqm,
                                   chain_break_method=majority_vote)

    # Sort the solutions from lowest energy and format them to quboDict format
    unformated_solutions_list = sorted(unembedded.record, key=lambda x: +x[1])
    solutions_list = []
    for sol, energy, num_appereances in unformated_solutions_list:
        solutions_list.append([
            rebuild_quboDict_from_vector(sol, n_genome_reads), energy,
            num_appereances
        ])

    return solutions_list, qpu_time, get_max_chain_length(embed)
Example #9
0
## Embedding logical qubits to physical ones
embedding = embeddings[sampler.solver.id]

## Set connections betweeen physical qubits
bqm_embedded = embed_bqm(bqm, embedding, target_adjacency, 4.0)
#print(bqm_embedded)

# Return num_reads solutions (responses are in the D-Wave's graph of indexed qubits)
kwargs = {}
if 'num_reads' in sampler.parameters:
    kwargs['num_reads'] = 50
if 'answer_mode' in sampler.parameters:
    kwargs['answer_mode'] = 'histogram'
response = sampler.sample(bqm_embedded, **kwargs)
print("A solution indexed by qubits: \n",
      next(response.data(fields=['sample'])))

# Map back to the BQM's graph (nodes labeled "a0", "b0" etc,)
response = unembed_sampleset(response, embedding, source_bqm=bqm)
print("\nThe solution in problem variables: \n",
      next(response.data(fields=['sample'])))

from helpers.convert import to_base_ten
# Select just the first sample.
sample = next(response.samples(n=1))
dict(sample)
a, b = to_base_ten(sample)

print("Given integer P={}, found factors a={} and b={}".format(P, a, b))
adjacency = {key: 1.0 for key in qubo.keys() if key[0] != key[1]}

# Run QUBO on DW_2000Q_5
sampler = DWaveSampler(solver='DW_2000Q_5')
embedding = find_embedding(adjacency, sampler.edgelist)
qubo_emb = embed_qubo(qubo, embedding, sampler.adjacency)
response = sampler.sample_qubo(qubo_emb,
                               num_reads=1000,
                               postprocess='optimization')

# Unembed samples by specifying chain_break_method argument of unembed_sampleset
bqm = dimod.BinaryQuadraticModel.from_qubo(qubo)
# majority_vote (default)
sample_majority_vote = unembed_sampleset(response,
                                         embedding,
                                         bqm,
                                         chain_break_method=majority_vote)
# discard
sample_discard = unembed_sampleset(response,
                                   embedding,
                                   bqm,
                                   chain_break_method=discard)
# weighted_random
sample_weighted_random = unembed_sampleset(response,
                                           embedding,
                                           bqm,
                                           chain_break_method=weighted_random)
# MinimizeEnergy
cbm = MinimizeEnergy(bqm, embedding)
sample_MinimizeEnergy = unembed_sampleset(response,
                                          embedding,
Example #11
0
    def sample(self,
               bqm,
               chain_strength=1.0,
               chain_break_fraction=True,
               **parameters):
        """Sample from the provided binary quadratic model.

        Also set parameters for handling a chain, the set of vertices in a target graph that
        represents a source-graph vertex; when a D-Wave system is the sampler, it is a set
        of qubits that together represent a variable of the binary quadratic model being
        minor-embedded.

        Args:
            bqm (:obj:`dimod.BinaryQuadraticModel`):
                Binary quadratic model to be sampled from.

            chain_strength (float, optional, default=1.0):
                Magnitude of the quadratic bias (in SPIN-space) applied between variables to create
                chains. The energy penalty of chain breaks is 2 * `chain_strength`.

            chain_break_fraction (bool, optional, default=True):
                If True, the unembedded response contains a ‘chain_break_fraction’ field
                that reports the fraction of chains broken before unembedding.

            **parameters:
                Parameters for the sampling method, specified by the child sampler.

        Returns:
            :class:`dimod.SampleSet`: A `dimod` :obj:`~dimod.SampleSet` object.

        Examples:
            This example submits an triangle-structured problem to a D-Wave solver, selected
            by the user's default
            :std:doc:`D-Wave Cloud Client configuration file <cloud-client:intro>`,
            using a specified minor-embedding of the problem’s variables to physical qubits.

            >>> from dwave.system.samplers import DWaveSampler
            >>> from dwave.system.composites import FixedEmbeddingComposite
            >>> import dimod
            ...
            >>> sampler = FixedEmbeddingComposite(DWaveSampler(), {'a': [0, 4], 'b': [1, 5], 'c': [2, 6]})
            >>> response = sampler.sample_ising({}, {'ab': 0.5, 'bc': 0.5, 'ca': 0.5}, chain_strength=2)
            >>> response.first    # doctest: +SKIP
            Sample(sample={'a': 1, 'b': -1, 'c': 1}, energy=-0.5, num_occurrences=1, chain_break_fraction=0.0)

        See `Ocean Glossary <https://docs.ocean.dwavesys.com/en/latest/glossary.html>`_
        for explanations of technical terms in descriptions of Ocean tools.

        """

        # solve the problem on the child system
        child = self.child

        # apply the embedding to the given problem to map it to the child sampler
        __, __, target_adjacency = child.structure

        # get the embedding
        embedding = self.embedding

        bqm_embedded = embed_bqm(bqm,
                                 embedding,
                                 target_adjacency,
                                 chain_strength=chain_strength,
                                 smear_vartype=dimod.SPIN)

        if 'initial_state' in parameters:
            parameters['initial_state'] = _embed_state(
                embedding, parameters['initial_state'])

        response = child.sample(bqm_embedded, **parameters)

        return unembed_sampleset(response,
                                 embedding,
                                 source_bqm=bqm,
                                 chain_break_fraction=chain_break_fraction)
# or, load it from file (if provided)
if len(sys.argv) > 1:
    path = sys.argv[1]
    with open(path) as fp:
        bqm = dimod.BinaryQuadraticModel.from_coo(fp).spin

# get solver
print("solver init")
client = Client.from_config()
solver = client.get_solver(qpu=True)

# embed
print("embedding")
source_edgelist = list(bqm.quadratic) + [(v, v) for v in bqm.linear]
target_edgelist = solver.edges
embedding = find_embedding(source_edgelist, target_edgelist)
target_adjacency = edgelist_to_adjacency(target_edgelist)
bqm_embedded = embed_bqm(bqm, embedding, target_adjacency)

# sample
print("sampling")
response = solver.sample_ising(bqm_embedded.linear,
                               bqm_embedded.quadratic,
                               num_reads=100)
sampleset_embedded = response.sampleset
sampleset = unembed_sampleset(sampleset_embedded, embedding, bqm)

# inspect
print("inspecting")
dwave.inspector.show(bqm, dict(embedding=embedding), response)
Example #13
0
    def sample(self,
               bqm,
               chain_strength=1.0,
               chain_break_method=None,
               chain_break_fraction=True,
               embedding_parameters=None,
               return_embedding=None,
               warnings=None,
               **parameters):
        """Sample from the provided binary quadratic model.

        Args:
            bqm (:obj:`dimod.BinaryQuadraticModel`):
                Binary quadratic model to be sampled from.

            chain_strength (float, optional, default=1.0):
                Magnitude of the quadratic bias (in SPIN-space) applied between
                variables to create chains. The energy penalty of chain breaks
                is 2 * `chain_strength`.

            chain_break_method (function, optional):
                Method used to resolve chain breaks during sample unembedding.
                See :func:`~dwave.embedding.unembed_sampleset`.

            chain_break_fraction (bool, optional, default=True):
                Add a `chain_break_fraction` field to the unembedded response with
                the fraction of chains broken before unembedding.

            embedding_parameters (dict, optional):
                If provided, parameters are passed to the embedding method as
                keyword arguments. Overrides any `embedding_parameters` passed
                to the constructor.

            return_embedding (bool, optional):
                If True, the embedding, chain strength, chain break method and
                embedding parameters are added to :attr:`dimod.SampleSet.info`
                of the returned sample set. The default behaviour is defined
                by :attr:`return_embedding_default`, which itself defaults to
                False.

            warnings (:class:`~dwave.system.warnings.WarningAction`, optional):
                Defines what warning action to take, if any. See
                :mod:`~dwave.system.warnings`. The default behaviour is defined
                by :attr:`warnings_default`, which itself defaults to
                :class:`~dwave.system.warnings.IGNORE`

            **parameters:
                Parameters for the sampling method, specified by the child
                sampler.

        Returns:
            :obj:`dimod.SampleSet`

        Examples:
            See the example in :class:`EmbeddingComposite`.

        """
        if return_embedding is None:
            return_embedding = self.return_embedding_default

        # solve the problem on the child system
        child = self.child

        # apply the embedding to the given problem to map it to the child sampler
        __, target_edgelist, target_adjacency = self.target_structure

        # add self-loops to edgelist to handle singleton variables
        source_edgelist = list(bqm.quadratic) + [(v, v) for v in bqm.linear]

        # get the embedding
        if embedding_parameters is None:
            embedding_parameters = self.embedding_parameters
        else:
            # we want the parameters provided to the constructor, updated with
            # the ones provided to the sample method. To avoid the extra copy
            # we do an update, avoiding the keys that would overwrite the
            # sample-level embedding parameters
            embedding_parameters.update(
                (key, val) for key, val in self.embedding_parameters
                if key not in embedding_parameters)

        embedding = self.find_embedding(source_edgelist, target_edgelist,
                                        **embedding_parameters)

        if warnings is None:
            warnings = self.warnings_default
        elif 'warnings' in child.parameters:
            parameters.update(warnings=warnings)

        warninghandler = WarningHandler(warnings)

        warninghandler.chain_strength(bqm, chain_strength)
        warninghandler.chain_length(embedding)

        if bqm and not embedding:
            raise ValueError("no embedding found")

        bqm_embedded = embed_bqm(bqm,
                                 embedding,
                                 target_adjacency,
                                 chain_strength=chain_strength,
                                 smear_vartype=dimod.SPIN)

        if 'initial_state' in parameters:
            # if initial_state was provided in terms of the source BQM, we want
            # to modify it to now provide the initial state for the target BQM.
            # we do this by spreading the initial state values over the
            # chains
            state = parameters['initial_state']
            parameters['initial_state'] = {
                u: state[v]
                for v, chain in embedding.items() for u in chain
            }

        if self.scale_aware and 'ignored_interactions' in child.parameters:

            ignored = []
            for chain in embedding.values():
                # just use 0 as a null value because we don't actually need
                # the biases, just the interactions
                ignored.extend(chain_to_quadratic(chain, target_adjacency, 0))

            parameters['ignored_interactions'] = ignored

        response = child.sample(bqm_embedded, **parameters)

        warninghandler.chain_break(response, embedding)

        sampleset = unembed_sampleset(
            response,
            embedding,
            source_bqm=bqm,
            chain_break_method=chain_break_method,
            chain_break_fraction=chain_break_fraction,
            return_embedding=return_embedding)

        if return_embedding:
            sampleset.info['embedding_context'].update(
                embedding_parameters=embedding_parameters,
                chain_strength=chain_strength)

        if chain_break_fraction and len(sampleset):
            warninghandler.issue(
                "all samples had broken chains",
                func=lambda:
                (sampleset.record.chain_break_fraction.all(), None))

        if warninghandler.action is WarningAction.SAVE:
            # we're done with the warning handler so we can just pass the list
            # off, if later we want to pass in a handler or similar we should
            # do a copy
            sampleset.info.setdefault('warnings',
                                      []).extend(warninghandler.saved)

        return sampleset
A = dwave_sampler.edgelist
Adj = dwave_sampler.adjacency
embedding = find_embedding(Q, A)
print(embedding)

bqm = BinaryQuadraticModel.from_qubo(Q)

# Cannot use a Composite to get the broken chains, so do the embedding
# directly
bqm_embedded = embed_bqm(bqm, embedding, Adj, chain_strength=chainstrength)
response = DWaveSampler().sample(bqm_embedded, num_reads=numruns)

# We need to get the chains directly, as a list
chains = [embedding[v] for v in list(bqm)]

# Obtain the broken chains
broken = broken_chains(response, chains)

# Interpret the results in terms of the embedding. Be sure to
# tell the method to compute the chain_break_frequency.
print(
    unembed_sampleset(response,
                      embedding,
                      source_bqm=bqm,
                      chain_break_fraction=True), broken)

# Use NumPy method to obtain the indices of the broken chains
w = np.where(broken == True)
indices = list(zip(*w))
print(indices)
Example #15
0
# https://docs.ocean.dwavesys.com/projects/system/en/latest/reference/generated/dwave.embedding.unembed_sampleset.html

import dimod
from dwave.embedding import unembed_sampleset

# Triangular binary quadratic model and an embedding
J = {('a', 'b'): -1, ('b', 'c'): -1, ('a', 'c'): -1}
bqm = dimod.BinaryQuadraticModel.from_ising({}, J)
embedding = {'a': [0, 1], 'b': [2], 'c': [3]}
# Samples from the embedded binary quadratic model
samples = [
    {
        0: -1,
        1: -1,
        2: -1,
        3: -1
    },  # [0, 1] is unbroken
    {
        0: -1,
        1: +1,
        2: +1,
        3: +1
    }
]  # [0, 1] is broken
energies = [-3, 1]
embedded = dimod.SampleSet.from_samples(samples, dimod.SPIN, energies)
# Unembed
samples = unembed_sampleset(embedded, embedding, bqm)

print(samples.record.sample)  # doctest: +SKIP
Example #16
0
#Create a complete Ising model on a QPU 
target_h, target_J = embed_ising(h, J, embedding, target_adjacency)
# print('__________________')
# print('Linear coeff on QPU:', target_h)
# print('Quadratic coeff on QPU:', target_J)
# print('__________________')

# Set parameters for calculations. num_reas is a number of experiments
runs = 4
response = sampler.sample_ising(target_h,
							target_J, 
							num_reads=runs, 
							answer_mode='histogram',
							annealing_time = 1000)
#Get a SampleSet with spins and energies (WARNING: results are for the task, embedded on QPU)
# print('Resulting spins on QPU:')
# print(response)
# print('__________________')

#Return to the original spins:
unembedding = unembed_sampleset(response, embedding, dimod.BinaryQuadraticModel.from_ising({}, J))
# print('Resulting spins in terms of original task:')
# print(unembedding)
# print('__________________')
# plt.hist(unembedding.record.energy,rwidth=1,align='left')
# plt.show()
print(unembedding)
print("QPU time used:", unembedding.info['timing']['qpu_access_time'], "microseconds.")


Example #17
0
        ### Energy offset
        ### エネルギー オフセット
        e_offset = lagrange_hard_shift * days * workforce(1)**2
        e_offset += lagrange_soft_nurse * nurses * duty_days**2

        ### BQM
        bqm = BinaryQuadraticModel.from_qubo(embeddedQ, offset=e_offset)
        sbqm = BinaryQuadraticModel.from_qubo(Q, offset=e_offset)

        # Sample solution
        # 解をサンプリングします
        print("Connected to {}. N = {}, D = {}".format(sampler.solver.id,
                                                       nurses, days))
        results = sampler.sample(bqm, num_reads=numSampling)
        samples = unembed_sampleset(results,
                                    embedding,
                                    sbqm,
                                    chain_break_fraction=True)

        ### Save data with pickle for analysis and reverse annealing
        ### 結果分析と逆アニーリングのため pickle を用いてデータを保存します
        fout = "results_%s_N%d_D%d_s%d.p" % (topology, nurses, days,
                                             numSampling)
        saveDict = {
            'results': results,
            'embedding': embedding,
            'bqm': sbqm,
            'samples': samples
        }
        pickle.dump(saveDict, open(fout, "wb"))
Example #18
0
    def sample(self,
               bqm,
               chain_strength=1.0,
               chain_break_method=None,
               chain_break_fraction=True,
               embedding_parameters=None,
               return_embedding=False,
               **parameters):
        """Sample from the provided binary quadratic model.

        Args:
            bqm (:obj:`dimod.BinaryQuadraticModel`):
                Binary quadratic model to be sampled from.

            chain_strength (float, optional, default=1.0):
                Magnitude of the quadratic bias (in SPIN-space) applied between
                variables to create chains. The energy penalty of chain breaks
                is 2 * `chain_strength`.

            chain_break_method (function, optional):
                Method used to resolve chain breaks during sample unembedding.
                See :func:`~dwave.embedding.unembed_sampleset`.

            chain_break_fraction (bool, optional, default=True):
                Add a `chain_break_fraction` field to the unembedded response with
                the fraction of chains broken before unembedding.

            embedding_parameters (dict, optional):
                If provided, parameters are passed to the embedding method as
                keyword arguments. Overrides any `embedding_parameters` passed
                to the constructor.

            return_embedding (bool, optional, default=False):
                If True, the embedding is added to :attr:`dimod.SampleSet.info`
                of the returned sample set.

            **parameters:
                Parameters for the sampling method, specified by the child
                sampler.

        Returns:
            :obj:`dimod.SampleSet`

        Examples:
            See the example in :class:`EmbeddingComposite`.

        """

        # solve the problem on the child system
        child = self.child

        # apply the embedding to the given problem to map it to the child sampler
        __, target_edgelist, target_adjacency = self.target_structure

        # add self-loops to edgelist to handle singleton variables
        source_edgelist = list(bqm.quadratic) + [(v, v) for v in bqm.linear]

        # get the embedding
        if embedding_parameters is None:
            embedding_parameters = self.embedding_parameters
        else:
            # we want the parameters provided to the constructor, updated with
            # the ones provided to the sample method. To avoid the extra copy
            # we do an update, avoiding the keys that would overwrite the
            # sample-level embedding parameters
            embedding_parameters.update(
                (key, val) for key, val in self.embedding_parameters
                if key not in embedding_parameters)

        embedding = self.find_embedding(source_edgelist, target_edgelist,
                                        **embedding_parameters)

        if bqm and not embedding:
            raise ValueError("no embedding found")

        bqm_embedded = embed_bqm(bqm,
                                 embedding,
                                 target_adjacency,
                                 chain_strength=chain_strength,
                                 smear_vartype=dimod.SPIN)

        if 'initial_state' in parameters:
            # if initial_state was provided in terms of the source BQM, we want
            # to modify it to now provide the initial state for the target BQM.
            # we do this by spreading the initial state values over the
            # chains
            state = parameters['initial_state']
            parameters['initial_state'] = {
                u: state[v]
                for v, chain in embedding.items() for u in chain
            }

        if self.scale_aware and 'ignored_interactions' in child.parameters:

            ignored = []
            for chain in embedding.values():
                # just use 0 as a null value because we don't actually need
                # the biases, just the interactions
                ignored.extend(chain_to_quadratic(chain, target_adjacency, 0))

            parameters['ignored_interactions'] = ignored

        response = child.sample(bqm_embedded, **parameters)

        return unembed_sampleset(response,
                                 embedding,
                                 source_bqm=bqm,
                                 chain_break_method=chain_break_method,
                                 chain_break_fraction=chain_break_fraction,
                                 return_embedding=return_embedding)
Example #19
0

if manual_embed:
	# Pick the method for fixing broken chains.
	from dwave.embedding.chain_breaks import majority_vote # weighted_random
	method = majority_vote
	# Submit the job via an embedded BinaryQuadraticModel.
	from dimod import BinaryQuadraticModel as BQM
	from dwave.embedding import embed_bqm, unembed_sampleset
	# Generate a BQM from the QUBO.
	q = BQM.from_qubo(qubo)
	# Embed the BQM onto the target structure.
	embedded_q = embed_bqm(q, embedding, adjacency) # chain_strength=chain_strength, smear_vartype=dimod.SPIN
	# Collect the sample output.
	response = unembed_sampleset(
	   sampler.sample(embedded_q, num_reads=num_samples),
	   embedding, q, chain_break_method=method,
	   chain_break_fraction=True)
else:
	# Use a FixedEmbeddingComposite if we don't care about chains.
	from dwave.system.composites import FixedEmbeddingComposite
	system_composite = FixedEmbeddingComposite(sampler, embedding)
	response = system_composite.sample_qubo(qubo, num_reads=num_samples)


constant = 0

# Cycle through the results and yield them to the caller.
for out in response.data():
	# Get the output from the data.
	bits = (out.sample[b] for b in sorted(out.sample))
	occurrence = out.num_occurrences