コード例 #1
0
ファイル: qbs_mnwe.py プロジェクト: Teedious/gcn_qrbm
def show_if_works(sampler):
    qubo = {(0, 0): -1, (0, 1): 2, (1, 1): -1}
    embedding = {0: [0], 1: [1]}
    composite = StructureComposite(sampler, [0, 1], [(0, 1)])
    fixed = FixedEmbeddingComposite(composite, embedding)

    print("\n\n")
    #test standard -> should deliver 100 samples
    print(fixed.sample_qubo(qubo, num_reads=100))

    #test special case qbsolv -> should deliver 100 samples also for qbsolv
    print(fixed.sample_qubo(qubo, num_reads=100, num_repeats=99))
コード例 #2
0
    def test_keyer(self):
        C4 = dnx.chimera_graph(4)
        nodelist = sorted(C4.nodes)
        edgelist = sorted(sorted(edge) for edge in C4.edges)

        child = dimod.StructureComposite(dimod.NullSampler(), nodelist, edgelist)

        embedding = {0: [49, 53], 1: [52], 2: [50]}

        sampler = FixedEmbeddingComposite(child, embedding)

        with self.assertRaises(dwave.embedding.exceptions.MissingChainError):
            sampler.sample_qubo({(1, 4): 1})

        sampler.sample_qubo({(1, 2): 1}).record  # sample and resolve future
        sampler.sample_qubo({(1, 1): 1}).record  # sample and resolve future
コード例 #3
0
    def test_keyerror(self):
        C16 = dnx.chimera_graph(16)
        child_sampler = dimod.RandomSampler()
        nodelist = sorted(C16.nodes)
        edgelist = sorted(sorted(edge) for edge in C16.edges)
        struc_sampler = dimod.StructureComposite(child_sampler, nodelist,
                                                 edgelist)

        embedding = {0: [391, 386], 1: [390], 2: [385]}

        sampler = FixedEmbeddingComposite(struc_sampler, embedding)

        with self.assertRaises(ValueError):
            sampler.sample_qubo({(1, 4): 1})

        sampler.sample_qubo({(1, 2): 1}).record  # sample and resolve future
        sampler.sample_qubo({(1, 1): 1}).record  # sample and resolve future
コード例 #4
0
ファイル: sampler.py プロジェクト: mercari/CFQIRBM
class Sampler(object):
    """
    This module defines a sampler.
    :param num_samps: number of samples
    :type num_samps: int
    """
    def __init__(self, num_copies=1):
        self.endpoint = 'YOUR URL'
        self.token = 'YOUR TOKEN'
        self.solver = 'YOUR SOLVER'
        self.gamma = 1400
        self.chainstrength = 4700
        self.num_copies = num_copies
        self.child = DWaveSampler(endpoint=self.endpoint,
                                  token=self.token,
                                  solver=self.solver)

    def sample_qubo(self, Q, num_samps=100):
        """
        Sample from the QUBO problem
        :param qubo: QUBO problem
        :type qubo: numpy dictionary
        :return: samples, energy, num_occurrences
        """
        self.num_samps = num_samps

        if not hasattr(self, 'sampler'):

            bqm = BinaryQuadraticModel.from_qubo(Q)

            # apply the embedding to the given problem to map it to the child sampler
            __, target_edgelist, target_adjacency = self.child.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
            embedding = minorminer.find_embedding(source_edgelist,
                                                  target_edgelist)

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

            self.sampler = FixedEmbeddingComposite(self.child, embedding)

        response = self.sampler.sample_qubo(Q,
                                            chain_strength=self.chainstrength,
                                            num_reads=self.num_samps)

        return np.array(response.__dict__['_samples_matrix'].tolist()), response.__dict__['_data_vectors']["energy"], \
               response.__dict__['_data_vectors']["num_occurrences"]
コード例 #5
0
    def execute(self, buffer, program):
        from dwave.system.samplers import DWaveSampler
        from dwave.system.composites import EmbeddingComposite, FixedEmbeddingComposite
        from collections import Counter
        import dimod

        h = {}
        J={}
        Q={}
        for inst in program.getInstructions():
            Q[(inst.bits()[0], inst.bits()[1])] = inst.getParameter(0)
            if inst.bits()[0] == inst.bits()[1]:
                h[inst.bits()[0]] = inst.getParameter(0)
            else:
                J[(inst.bits()[0], inst.bits()[1])] = inst.getParameter(0)

        buffer.setSize(max(h.keys())+1)

        if buffer.hasExtraInfoKey('embedding'):
            sampler = FixedEmbeddingComposite(DWaveSampler(token=self.token, solver=self.backend), buffer['embedding'])
        else:
            sampler = EmbeddingComposite(DWaveSampler(token=self.token, solver=self.backend))

        if program.getTag() == "ising":
            response = sampler.sample_ising(h, J, num_reads=self.shots, return_embedding=True)
        else:
            response = sampler.sample_qubo(Q, chain_strength=self.chain_strength, num_reads=self.shots, return_embedding=True)

        if not buffer.hasExtraInfoKey('embedding'):
            # we used embeddingcomposite, get the computed
            # embedding
            emb = response.info['embedding_context']['embedding']
            buffer.addExtraInfo('embedding', emb)

        counts_list = []
        e_map = {}
        for r in response.record:
            sample, energy, nocc, _ = r
            bitstring = ''.join([str(s if s == 1 else 0) for s in sample])
            for i in range(nocc):
                counts_list.append(bitstring)
            e_map[bitstring] = energy

        counts = Counter(counts_list)
        buffer.setMeasurements(counts)
        buffer.addExtraInfo('energies', e_map)
コード例 #6
0
Q_not = {('x', 'x'): -1, ('x', 'z'): 2, ('z', 'x'): 0, ('z', 'z'): -1}

#Minor embedding maps the two problem variables x and z to indexed qubits

#Select the first node and print adjacent nodes, coupled qubits
print(sampler.adjacency[sampler.nodelist[0])

#Manually minor-embed the problem with FixedEmbeddingComposite

from dwave.system.composites import FixedEmbeddingComposite
sampler_embedded = FixedEmbeddingComposite(sampler, {'x':[0], 'z':[4]})
print(sampler_embedded.adjacency)

#Ask for 500 samples

response = sampler_embedded.sample_qubo(Q_not, num_reads=5000)
for datum in response.date(['sample', 'energy', 'num_occurences']):
      print(datum.sample, "Energy: ", datum.energy, "Occurrences: ",
            datum.num_occurrences)
---------------------------------------------------------------------
#Minor-Embedding an AND Gate
---------------------------------------------------------------------
      
#3 Qubits cannot be connected in a closed loop, but 4 can be connected in a closed loop
#Manual minor-embedding using FixedEmbeddingComposite()
from dwave.system.composites import FixedEmbeddingComposite
embedding = {'x1': {1}, 'x2': {5}, 'z': {0, 4}}
sampler_embedded = FixedEmbeddingComposite(sampler, embedding)
print(sampler_embedded.adjaceny)

#We ask for 5000 samples
コード例 #7
0
ファイル: doubleor-expl.py プロジェクト: Yunsoo-Ha/QSimOpt

csp.add_constraint(logic_circuit1, ['a', 'b', 'nor1'])
csp.add_constraint(logic_circuit1, ['nor1', 'c', 'z'])

# Convert the binary constraint satisfaction problem to a binary quadratic model
bqm = dwavebinarycsp.stitch(csp)

from dwave.system.samplers import DWaveSampler
from dwave.system.composites import FixedEmbeddingComposite

# I used the QMI (presentation page 48: More complex example: 3-bit Adder)
embedding = {'a': {0}, 'nor1': {4, 12}, 'b': {1, 5}, 'c': {9, 13}, 'z': {8}}

sampler_embedded = FixedEmbeddingComposite(DWaveSampler(), embedding)

#Based on BQM, we can get the QUBO. We can do this automatically but, here I did it manually.
#Q = dimod.BinaryQuadraticModel.to_qubo(bqm)

Q = ({('a', 'b'): 2, ('a', 'nor1'): 4, ('b', 'nor1'): 4, ('nor1', 'c'): 2, ('nor1', 'z'): 4, \
      ('c', 'z'): 4, ('a', 'a'): -2, ('b', 'b'): -2, ('nor1', 'nor1'): -4, ('c', 'c'): -2, \
      ('z', 'z'): -2})

#response = sampler_embedded.sample_qubo(Q)
#for datum in response.data(['sample', 'energy']):
#  print(datum.sample, "Energy: ", datum.energy)

response = sampler_embedded.sample_qubo(Q, num_reads=5000)
for datum in response.data(['sample', 'energy', 'num_occurrences']):
    print(datum.sample, "Energy: ", datum.energy, "Occurrences: ",
          datum.num_occurrences)
コード例 #8
0
ファイル: d_wave_client.py プロジェクト: Teedious/gcn_qrbm
class DClient:

    op_mode_quantum = 1
    op_mode_simulated_annealing = 2
    op_mode_qbsolv = 3

    def __init__(self, mode=2):

        self.api_tokens = [
            "DEV-6a4c8dd1862e3e593ab8ee3e1389184107f52c45",
            "DEV-2fd0bc12a079b0089fb4c8bd4e439694160945ce",
            "DEV-7f56a1d2d5504b12b6bc7df346e2b18d59bea4a3",
            "DEV-e2bc6c527b3b6402000edcd3fa6d9c572a1ee872",
            "DEV-0cbee57b56cbe00d520a1dcd4d57fbde62f56869",
            "DEV-650859a4adf3a4fdee3e958ca4ab4ed45c17e393",
            "DEV-650859a4adf3a4fdee3e958ca4ab4ed45c17e393",
        ]
        self.mode = mode
        self.embedding = None
        self.sampler = None
        self.base_sampler = DWaveSampler(solver={'qpu': True},
                                         token=self.api_tokens[0])

    def find_embedding(self, Q):
        i = 0
        max = 10
        while None == self.embedding and i < max:
            i += 1
            try:
                self.embedding = minorminer.find_embedding(
                    Q, self.base_sampler.edgelist)
            except Exception as a:
                if i == max - 1:
                    raise Exception(
                        "No embedding found after {} tries.".format(max))

    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)

    def sample(self, Q, num_reads=10):
        answer = None
        self.find_embedding(Q)
        while None == answer:
            try:
                self.create_sampler()
                # hier muss was gefixt werden
                #######################################################################################
                #######################################################################################
                #######################################################################################
                #######################################################################################
                #######################################################################################
                #######################################################################################
                #######################################################################################
                #######################################################################################
                #######################################################################################
                #######################################################################################
                #######################################################################################
                #######################################################################################
                # bqm = dimod.BinaryQuadraticModel.from_qubo(Q)
                # __, target_edgelist, target_adjacency = self.sampler.target_structure
                # bqm_embedded = embed_bqm(bqm, self.embedding, target_adjacency,
                #                  smear_vartype=dimod.SPIN)
                # # embed bqm gives a binary View object of the BQM which is not allowed in the TabuSampler
                # print(isinstance(bqm, dimod.BinaryQuadraticModel))
                # print(isinstance(bqm_embedded, dimod.BinaryQuadraticModel))
                if self.mode == self.op_mode_qbsolv:
                    answer = self.sampler.sample_qubo(Q,
                                                      num_repeats=num_reads -
                                                      1)
                else:
                    answer = self.sampler.sample_qubo(Q, num_reads=num_reads)
                #######################################################################################
                #######################################################################################
                #######################################################################################
                #######################################################################################
                #######################################################################################
                #######################################################################################
            except SolverFailureError:
                self.sampler = None
                print("\n\n\n{} is now empty\n\n\n".format(self.api_tokens[0]))
                with open("./empty_api_tokens", mode='a',
                          encoding="utf-8") as file:
                    file.write("{}\n".format(self.api_tokens[0]))
                del self.api_tokens[0]
                self.base_sampler = DWaveSampler(solver={'qpu': True},
                                                 token=self.api_tokens[0])
        ret = list(answer.data(['sample', 'num_occurrences']))
        return ret
コード例 #9
0
sampler = DWaveSampler()
sampler_embedded = FixedEmbeddingComposite(sampler, embedding)
print('\n**********  Part 1: Largest complete graph Kn'
      ' that can be a sub-graph of bipartite graph K4,4 ***********  \n')
print('Assignment : \n', embedding)
print('Neighbourhood check : \n', sampler_embedded.adjacency)

# Part 2: Solving Problem 4 using manual embedding as a QUBO
shots = 100
h0 = -0.2
h1 = -0.2
j01 = 1
j10 = 0
sampler = DWaveSampler()
embedding_1 = {'h0': {5}, 'h1': {13}}
Q_not = {
    ('h0', 'h0'): h0,
    ('h0', 'h1'): j01,
    ('h1', 'h0'): j10,
    ('h1', 'h1'): h1
}
sampler_embedded = FixedEmbeddingComposite(sampler, embedding_1)
response = sampler_embedded.sample_qubo(Q_not, num_reads=shots)
print(
    '\n**********  Part 2: Problem 4 using manual embedding to qubit 5 and 13 (in two different unit cells)\n'
)
for res in response.data(['sample', 'energy', 'num_occurrences']):
    print('|h0 = %s |h1 = %s | Energy = %f | Probability  = %f %% ' %
          (res.sample['h0'], res.sample['h1'], res.energy,
           res.num_occurrences * 100 / shots))
コード例 #10
0
solver = DWaveSampler()

Q1 = [('x1', 'x2'), ('x1', 'z'), ('x2', 'z')]
Q2 = {('x1', 'x2'): 2, ('x1', 'z'): -2, ('x2', 'z'): 3}
Q3 = {('x1', 'x2'): 1, ('x1', 'z'): 5, ('x2', 'z'): 20}

__, target_edgelist, target_adjacency = solver.structure

emb1 = find_embedding(Q1, target_edgelist,
                      verbose=1)  # get the list of variables and nodes
emb2 = find_embedding(Q2, target_edgelist, verbose=1)
emb3 = find_embedding(Q3, target_edgelist, verbose=1)

sampler1 = FixedEmbeddingComposite(
    solver, emb1)  # knows nothing about the origianl QUBO matrix
result1 = sampler1.sample_qubo(
    Q2, num_reads=10)  # uses the original matrix on the phisical embedding

sampler2 = FixedEmbeddingComposite(solver, emb2)
result2 = sampler2.sample_qubo(Q2, num_reads=10)

sampler3 = FixedEmbeddingComposite(solver, emb3)
result3 = sampler3.sample_qubo(Q3, num_reads=10)

print('\nresult1', result1)
print('\nresult2', result2)
print('\nresult3', result3)

print('\nemb1', emb1)
print('\nemb2', emb2)
print('\nemb3', emb3)
コード例 #11
0
	# 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
	chain_break_fraction = out.chain_break_fraction
	energy = out.energy + constant
	print('Bits \t\t\t\t Occurrence \t Chain \t breaks \t Energy')
	print(bits, occurrence, 100 * chain_break_fraction, energy)
コード例 #12
0
ファイル: miner_qpu.py プロジェクト: m3ller/20200318
# See the License for the specific language governing permissions and
# limitations under the License.

from minorminer import find_embedding
from dwave.system.samplers import DWaveSampler
from dwave.system.composites import FixedEmbeddingComposite

# Set up the QUBO. Start with the equations:
# x + y - 2xy -1
# 2yz - y - z
# -2zx + z + x - 1
# QUBO: 2x - 2xy + 2yz - 2zx - 2
Q = {(0, 0): 2, (0, 1): -2, (0, 2): -2, (1, 2): 2}

chainstrength = 2
numruns = 1000

dwave_sampler = DWaveSampler(solver={'qpu': True})
edges = dwave_sampler.edgelist
embedding = find_embedding(Q, edges)
print(embedding)

sampler = FixedEmbeddingComposite(dwave_sampler, embedding)
response = sampler.sample_qubo(Q,
                               chain_strength=chainstrength,
                               num_reads=numruns)

for sample, energy, num, cbf in response.data(
    ['sample', 'energy', 'num_occurrences', 'chain_break_fraction']):
    print(sample, energy, num, cbf)