def test_minimize_energy_chain_break_method(self): # bug report https://github.com/dwavesystems/dwave-system/issues/206 Q = { (0, 1): 1, (0, 2): 1, (0, 3): 1, (1, 2): 1, (1, 3): 1, (2, 3): 1, (0, 0): 1, (1, 1): 1, (2, 2): 1, (3, 3): 1 } S = {(0, 1): 1, (0, 2): 1, (0, 3): 1, (1, 2): 1, (1, 3): 1, (2, 3): 1} bqm = dimod.BinaryQuadraticModel.from_qubo(Q) G = dnx.chimera_graph(4) sampler = dimod.StructureComposite(dimod.ExactSolver(), G.nodes, G.edges) embedding = {0: [55], 1: [48], 2: [50, 53], 3: [52, 51]} composite = FixedEmbeddingComposite(sampler, embedding) cbm = chain_breaks.MinimizeEnergy(bqm, embedding) composite.sample(bqm, chain_break_method=cbm).resolve()
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"]
def test_sample_bqm_triangle(self): sampler = FixedEmbeddingComposite(MockDWaveSampler(), { 'a': [0, 4], 'b': [1, 5], 'c': [2, 6] }) resp = sampler.sample_ising({'a': 1, 'b': 1, 'c': 0}, {}) self.assertEqual(set(resp.variables), {'a', 'b', 'c'})
def next(self, state, **runopts): num_reads = runopts.get('num_reads', self.num_reads) sampling_params = runopts.get('sampling_params', self.sampling_params) params = sampling_params.copy() params.update(num_reads=num_reads) sampler = FixedEmbeddingComposite(self.sampler, embedding=state.embedding) response = sampler.sample(state.subproblem, **params) return state.updated(subsamples=response)
def test_chain_break_method_customization(self): sampler = FixedEmbeddingComposite(MockDWaveSampler(), {'a': [0]}) with mock.patch('dwave.system.composites.embedding.unembed_sampleset' ) as mock_unembed: sampler.sample_ising({'a': 1}, {}, chain_break_method=chain_breaks.discard) # assert chain_break_method propagated to unembed_sampleset __, kwargs = mock_unembed.call_args self.assertEqual(kwargs['chain_break_method'], chain_breaks.discard)
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))
def test_chain_break_method_customization(self): sampler = FixedEmbeddingComposite(MockDWaveSampler(), {'a': [0]}) def mock_unembed(*args, **kwargs): self.assertIn('chain_break_method', kwargs) self.assertEqual(kwargs['chain_break_method'], chain_breaks.discard) mock_unembed.call_count += 1 return dwave.embedding.unembed_sampleset(*args, **kwargs) mock_unembed.call_count = 0 with mock.patch('dwave.system.composites.embedding.unembed_sampleset', mock_unembed): sampler.sample_ising({'a': 1}, {}, chain_break_method=chain_breaks.discard).resolve() self.assertEqual(mock_unembed.call_count, 1)
def global_sampler(self): fixed_sampler = FixedEmbeddingComposite( DWaveSampler(solver={ 'lower_noise': True, 'qpu': True }), self.embedding) return fixed_sampler
def test_instantiation_triangle(self): sampler = FixedEmbeddingComposite(MockSampler(), {'a': [0, 4], 'b': [1, 5], 'c': [2, 6]}) dtest.assert_sampler_api(sampler) # checks adj consistent with nodelist/edgelist self.assertEqual(sampler.nodelist, ['a', 'b', 'c']) self.assertEqual(sampler.edgelist, [('a', 'b'), ('a', 'c'), ('b', 'c')])
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)
def test_instantiation_empty_embedding(self): sampler = FixedEmbeddingComposite(MockDWaveSampler(), {}) dtest.assert_sampler_api(sampler) # checks adj consistent with nodelist/edgelist self.assertEqual(sampler.edgelist, []) self.assertTrue(hasattr(sampler, 'embedding')) self.assertIn('embedding', sampler.properties)
def test_instantiation_triangle(self): embedding = {'a': (0, 4), 'b': (1, 5), 'c': (2, 6)} sampler = FixedEmbeddingComposite(MockDWaveSampler(), embedding) self.assertEqual(embedding, sampler.embedding) dimod.testing.assert_sampler_api(sampler) # checks adj consistent with nodelist/edgelist self.assertEqual(sampler.nodelist, ['a', 'b', 'c']) self.assertEqual(sampler.edgelist, [('a', 'b'), ('a', 'c'), ('b', 'c')])
def test_instantiation_empty_adjacency(self): sampler = FixedEmbeddingComposite(MockDWaveSampler(), source_adjacency={}) dtest.assert_sampler_api(sampler) # checks for attributes needed in a sampler self.assertEqual(sampler.edgelist, []) self.assertTrue(hasattr(sampler, 'embedding')) self.assertIn('embedding', sampler.properties)
def test_scale_aware_scale_composite(self): nodelist = [0, 1, 2] edgelist = [(0, 1), (1, 2), (0, 2)] embedding = {'a': [0], 'b': [1, 2]} sampler = FixedEmbeddingComposite(dimod.TrackingComposite( ScaleComposite( dimod.StructureComposite(dimod.NullSampler(), nodelist, edgelist))), embedding=embedding, scale_aware=True) _ = sampler.sample_ising({'a': 100, 'b': -100}, {'ab': 300}) self.assertIn('ignored_interactions', sampler.child.input) ignored = sampler.child.input['ignored_interactions'] self.assertTrue(ignored == [(1, 2)] or ignored == [(2, 1)])
def test_adjacency(self): square_adj = {1: [2, 3], 2: [1, 4], 3: [1, 4], 4: [2, 3]} sampler = FixedEmbeddingComposite(MockDWaveSampler(), source_adjacency=square_adj) self.assertTrue(hasattr(sampler, 'adjacency')) self.assertTrue(hasattr(sampler, 'embedding')) self.assertIn('embedding', sampler.properties) self.assertEqual(sampler.nodelist, [1, 2, 3, 4]) self.assertEqual(sampler.edgelist, [(1, 2), (1, 3), (2, 4), (3, 4)])
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 test_with_embedding_and_adjacency(self): self.assertRaises( TypeError, lambda: FixedEmbeddingComposite(MockDWaveSampler(), { 'a': [0, 4], 'b': [1], 'c': [5] }, { 'a': ['b', 'c'], 'b': ['a', 'c'], 'c': ['a', 'b'] }))
def get_embed_min_max_offset(sampler, embedding): embed = FixedEmbeddingComposite(sampler, embedding) embedding_idx = [ idx for embed_list in embedding.values() for idx in embed_list ] anneal_offset_ranges = np.array( embed.properties["child_properties"]["anneal_offset_ranges"]) min_offset = max( [offsets[0] for offsets in anneal_offset_ranges[embedding_idx]]) max_offset = min( [offsets[1] for offsets in anneal_offset_ranges[embedding_idx]]) return embed, min_offset, max_offset
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"]
def solve_dwave_mineng(bqm: dimod.binary_quadratic_model, solver_type="Advantage", num_reads=1000) -> pd.DataFrame: """Dwaveでquboを解く Args: bqm (dimod.binary_quadratic_model): QUBOを入力します solver_type (str, optional): solverのタイプを選ぶ. Defaults to "Advantage". num_reads (int, optional): Dwaveでの計算回数をしています. Defaults to 1000. Returns: pd.DataFrame: 結果を返します """ sampler: DWaveSampler = _get_dwave_sampler(solver_type=solver_type) embedding = minorminer.find_embedding(bqm.quadratic, sampler.edgelist) cbm = dwave.embedding.MinimizeEnergy(bqm, embedding) composite = FixedEmbeddingComposite(sampler, embedding) result = composite.sample(bqm, chain_strength=0.5, num_reads=num_reads, auto_scale=True, chain_break_method=cbm) df_result = result.to_pandas_dataframe() return df_result
def __init__(self): self.solvers_list = {} sampler = DWaveSampler(token=DWAVE_TOKEN, endpoint=DWAVE_ENDPOINT) for i in range(4, 10): embedding = np.load( os.path.join('embeddings', 'embedding_' + str(i) + '.npy')).item() for key in embedding.keys(): embedding[key] = [int(item) for item in embedding[key]] try: self.solvers_list[i] = FixedEmbeddingComposite( sampler, embedding=embedding) except Exception as e: pass self.backup_solver = EmbeddingComposite(sampler)
def example_instance(): nP = 2 jobs = [1, 2, 3, 4] diff = [] embedding = { 0: [1760, 1632, 1764], 1: [1628, 1636, 1634], 2: [1638, 1630, 1627], 3: [1752, 1624, 1759, 1767], 4: [1763, 1635, 1765], 5: [1761, 1633], 6: [1754, 1626, 1758, 1766], 7: [1631, 1639, 1625], 8: [1637, 1629] } # base_sampler = neal.SimulatedAnnealingSampler() base_sampler = DWaveSampler() #base_sampler.properties['extended_j_range'] = [-10.0, 10.0] G = dnx.chimera_graph(16, 16, 4) nodelist = G.nodes() edgelist = G.edges() sampler = dimod.StructureComposite(base_sampler, nodelist, edgelist) new_sampler = FixedEmbeddingComposite(sampler, embedding) # print new_sampler.properties # print new_sampler.parameters #new_sampler = VirtualGraphComposite(sampler, embedding, chain_strength=-6.0) Q = create.createQUBO(jobs, nP, diff) solutions = { 'energy': [], "valid": [], 'max_time': [], 'chain_break_fraction': [] } for k in range(10): s = solve.solveQUBO(Q, jobs, nP, new_sampler, 0) solutions['energy'].append(s['energy']) solutions['valid'].append(s['valid']) solutions['max_time'].append(s['max_time']) solutions['chain_break_fraction'].append(s['chain_break_fraction']) solve.evaluate(solutions) print(solutions) print("Durchschnittliche Anteil gebrochender Ketten: ", sum(solutions['chain_break_fraction']) / 100)
def execute_dwave(self): """ Executes request to D-Wave API using predefined Ising_SVP_Experiment attributes (from preprocess()) Saves results to response_dict attribute """ self.response_dict = {} for i in range(self.t): response = FixedEmbeddingComposite( DWaveSampler(qpu=True), embedding=self.embedding).sample_ising( self.l, self.q, num_reads=self.n_reads, annealing_time=self.times[i], auto_scale=False, chain_strength=2.0) self.response_dict[self.times[i]] = response
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 """ #print(Q) 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 = EmbeddingComposite( DWaveSampler(token="DEV-db4d47e5313cf3c52cac31dace7c5080a5ffc46d") ).sample_qubo(Q, num_reads=1000) #response = self.sampler.sample_qubo(Q, chain_strength=self.chainstrength, num_reads=self.num_samps) #for sample, energy, num_occurrences, chain_break_fraction in list(response.data()): # print(sample, "Energy: ", energy, "Occurrences: ", num_occurrences) #print(response.samples()[0,[range(0,71)]]) #print(response._asdict()['vectors']['energy']) #print(response._asdict()['vectors']['num_occurrences']) saempeul = np.empty((0, 72)) for sample, in response.data(fields=['sample']): saempeul = np.append(saempeul, sample) #print(saempeul) return saempeul, response._asdict()['vectors']['energy']['data'], \ response._asdict()['vectors']['num_occurrences']['data']
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
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
def run_dwave(H, sampler=dwaveSampler, solve_parameters=None): '''Runs QUBO from a given H, on the spesified sampler. :param H: Hamiltoninan :param sampler: DWaveSampler() or dimod.ExactSolver() object :return: Returns the sample data for the problem ''' model = H.compile() qubo, offset = model.to_qubo() print("solve_parameters", solve_parameters) if "prune" in solve_parameters: pruner = solve_parameters["prune"] print(str(pruner), "dsandaskjdasn") if "dwave" in str(pruner): print("WORKINGdwavedsakmadksm") quantumSample = CutOffComposite(AutoEmbeddingComposite(sampler), 0.75) if "xanadu" in str(pruner): print("Xanadu!!!!!!!!!!!") quantumSample = XanaduCutOffComposite( AutoEmbeddingComposite(sampler), 0.75) else: embedding = get_embedding_with_short_chain( J=qubo, processor=dwaveSampler.edgelist) quantumSample = FixedEmbeddingComposite(sampler, embedding) results = quantumSample.sample_qubo(qubo, annealing_time=20, num_reads=1000) try: new_qubo = quantumSample.new_qubo except AttributeError: new_qubo = None return results, new_qubo, model.to_dimod_bqm()
bqm = dwavebinarycsp.stitch(csp) chimera_cell = [(i, j + 4) for j in range(4) for i in range(4)] embeddings = [ minorminer.find_embedding(bqm.to_qubo()[0].keys(), chimera_cell) for i in range(100) ] min_emb = min(embeddings, key=lambda x: len(sum(x.values(), []))) print("Minimum embedding configuration:", min_emb) print("Minimum embedding length:", len(sum(min_emb.values(), []))) # Verification of the found embedding print("Verification of the found embedding") sampler = FixedEmbeddingComposite(DWaveSampler(), min_emb) response = sampler.sample(bqm, num_reads=5000) for sample, energy, occurences in response.data( ['sample', 'energy', 'num_occurrences']): print(list(sample.values()), 'Occurrences:', occurences, 'Energy:', energy) # Bonus question: running in parallel print("Bonus question: running in parallel") sampler2 = FixedEmbeddingComposite(TilingComposite(DWaveSampler(), 1, 1, 4), min_emb) response = sampler.sample(bqm, num_reads=5000) for sample, energy, occurences in response.data( ['sample', 'energy', 'num_occurrences']): print(list(sample.values()), 'Occurrences:', occurences, 'Energy:', energy) print("Adjacency:", sampler2.adjacency)
import itertools import networkx as nx from dwave_qbsolv import QBSolv from dwave.system.samplers import DWaveSampler from dwave.system.composites import FixedEmbeddingComposite import minorminer # define (sub)problem size solver_limit = 3 qubo_size = 4 # find embedding of subproblem-sized complete graph to the QPU G = nx.complete_graph(solver_limit) system = DWaveSampler() embedding = minorminer.find_embedding(G.edges, system.edgelist) # solve a random problem Q = { t: random.uniform(-1, 1) for t in itertools.product(range(qubo_size), repeat=2) } response = QBSolv().sample_qubo(Q, solver=FixedEmbeddingComposite( system, embedding), solver_limit=solver_limit) print("Q=" + str(Q)) print("samples=" + str(list(response.samples()))) print("energies=" + str(list(response.data_vectors['energy'])))
D=dict() for i in range(r*m*n): for j in range(i+1): if i!=j: D[(i,j)]= Coefficients[i,j]+Coefficients[j,i] elif i==j: D[(i,j)]= Coefficients[i,j] # Solve the Puzzle use_qpu=True if use_qpu: solver_limit = 256 G = nx.complete_graph(solver_limit) system = DWaveSampler(token='DEV-6189564036d19f88b3a555b4175a353d6d2c0218') embedding = minorminer.find_embedding(D.keys(), system.edgelist) print(embedding) res = QBSolv().sample_qubo(D, solver=FixedEmbeddingComposite(system, embedding), solver_limit=solver_limit,token='DEV-6189564036d19f88b3a555b4175a353d6d2c0218', num_reads=20) #Emb = EmbeddingComposite(DWaveSampler(token='DEV-6189564036d19f88b3a555b4175a353d6d2c0218')) #res = Emb.sample_qubo(D, num_reads=10000) else: res = QBSolv().sample_qubo(D,num_repeats=20) samples = list(res.samples()) energy = list(res.data_vectors['energy']) print(samples) print(energy) # Represent the Results for i in range(len(samples)): result = samples[i] output = [] # ignore ancillary variables, which are all negative, only get positive bits for x in range(r*m*n): output.append(result[x])