def find_valid_y_time_ntimes(self): valid_y_info_dic = {} #sample:[occurrences, chain_break_fraction] calculation_time = 0 for _ in range(self.n): s3_destination_folder = ('amazon-braket-ecc806acea4c', 'qaExactLogisticRegression_ssato') dw = BraketDWaveSampler( s3_destination_folder, device_arn='arn:aws:braket:::device/qpu/d-wave/DW_2000Q_6') qa_sampler = AutoEmbeddingComposite(dw) res = qa_sampler.sample(self.bqm, chain_strength=self.chain_strength, chain_break_fraction=True, num_reads=self.num_reads) for sample, energy, num_occurrences, chain_break_fraction in res.data( [ 'sample', 'energy', 'num_occurrences', 'chain_break_fraction' ]): if energy == 0.0: sample_tuple = tuple(sample.values()) if sample_tuple in list(valid_y_info_dic.keys()): valid_y_info_dic[sample_tuple][0] += num_occurrences else: valid_y_info_dic[sample_tuple] = [ num_occurrences, chain_break_fraction ] calculation_time += res.info['additionalMetadata'][ 'dwaveMetadata']['timing']['qpuAccessTime'] * 10**(-6) return valid_y_info_dic, calculation_time
def __init__(self, num_reads=100, anneal_schedule=None, qpu_sampler=None, sampling_params=None, auto_embedding_params=None, **runopts): super(ReverseAnnealingAutoEmbeddingSampler, self).__init__(**runopts) self.num_reads = num_reads if anneal_schedule is None: anneal_schedule = [[0, 1], [0.5, 0.5], [1, 1]] self.anneal_schedule = anneal_schedule if qpu_sampler is None: qpu_sampler = DWaveSampler( solver=dict(max_anneal_schedule_points__gte=len(self.anneal_schedule))) # validate schedule, raising `ValueError` on invalid schedule or # `RuntimeError` if anneal schedule not supported by QPU (this could # happen only if user provided the `qpu_sampler`) qpu_sampler.validate_anneal_schedule(anneal_schedule) if sampling_params is None: sampling_params = {} self.sampling_params = sampling_params # embed on the fly and only if needed if auto_embedding_params is None: auto_embedding_params = {} self.sampler = AutoEmbeddingComposite(qpu_sampler, **auto_embedding_params)
def aws_get_response(bqm, chain_strength, num_reads): s3_destination_folder = ('amazon-braket-ecc806acea4c', 'qaExactLogisticRegression_ssato') dw = BraketDWaveSampler( s3_destination_folder, device_arn='arn:aws:braket:::device/qpu/d-wave/DW_2000Q_6') qa_sampler = AutoEmbeddingComposite(dw) res = qa_sampler.sample(bqm, chain_strength=chain_strength, chain_break_fraction=True, num_reads=num_reads) return res
def __init__(self, num_reads=100, qpu_sampler=None, qpu_params=None, **runopts): super(QPUSubproblemAutoEmbeddingSampler, self).__init__(**runopts) self.num_reads = num_reads if qpu_sampler is None: qpu_sampler = DWaveSampler() # embed on fly and only if needed self.sampler = AutoEmbeddingComposite(qpu_sampler) if qpu_params is None: qpu_params = {} self.qpu_params = qpu_params
def _get_dwave_response( Q: dict, num_reads: int, anneal_time: int, pause_duration: int, pause_start: float, seed_embedding: int, ) -> pd.DataFrame: """Get the response from D-Wave for the problem specified by Q. :param Q: QUBO matrix :param num_reads: number of times the schedule is run on the quantum annealer :param anneal_time: time for the annealing part of the schedule :param pause_duration: time for the pause part of the schedule :param pause_start: value for the s parameter at which the pause starts :param seed_embedding: start random seed for the embedding generation :return: D-Wave response """ if pause_duration > 0: schedule = [[0.0, 0.0], [pause_start * anneal_time, pause_start], [pause_start * anneal_time + pause_duration, pause_start], [anneal_time + pause_duration, 1.0]] else: schedule = [[0.0, 0.0], [anneal_time, 1.0]] solver = DWaveSampler() sampler = AutoEmbeddingComposite( solver, find_embedding=embedding.find_embedding, embedding_parameters={ "random_seed": seed_embedding, "verbose": 2, "interactive": True, }, ) response = sampler.sample_qubo( Q, num_reads=num_reads, max_answers=num_reads, anneal_schedule=schedule, answer_mode='histogram', return_embedding=True, ) return response
def __init__(self, num_reads=100, qpu_sampler=None, sampling_params=None, auto_embedding_params=None, **runopts): super(QPUSubproblemAutoEmbeddingSampler, self).__init__(**runopts) self.num_reads = num_reads if qpu_sampler is None: qpu_sampler = DWaveSampler() if sampling_params is None: sampling_params = {} self.sampling_params = sampling_params # embed on the fly and only if needed if auto_embedding_params is None: auto_embedding_params = {} self.sampler = AutoEmbeddingComposite(qpu_sampler, **auto_embedding_params)
class QPUSubproblemAutoEmbeddingSampler(traits.SubproblemSampler, traits.SISO, Runnable): r"""A quantum sampler for a subproblem with automated heuristic minor-embedding. Args: num_reads (int, optional, default=100): Number of states (output solutions) to read from the sampler. qpu_sampler (:class:`dimod.Sampler`, optional, default=\ :class:`~dwave.system.samplers.DWaveSampler`\ ()): Quantum sampler such as a D-Wave system. Subproblems that do not fit the sampler's structure are minor-embedded on the fly with :class:`~dwave.system.composites.AutoEmbeddingComposite`. sampling_params (dict): Dictionary of keyword arguments with values that will be used on every call of the (embedding-wrapped QPU) sampler. auto_embedding_params (dict, optional): If provided, parameters are passed to the :class:`~dwave.system.composites.AutoEmbeddingComposite` constructor as keyword arguments. See :ref:`samplers-examples`. """ def __init__(self, num_reads=100, qpu_sampler=None, sampling_params=None, auto_embedding_params=None, **runopts): super(QPUSubproblemAutoEmbeddingSampler, self).__init__(**runopts) self.num_reads = num_reads if qpu_sampler is None: qpu_sampler = DWaveSampler() if sampling_params is None: sampling_params = {} self.sampling_params = sampling_params # embed on the fly and only if needed if auto_embedding_params is None: auto_embedding_params = {} self.sampler = AutoEmbeddingComposite(qpu_sampler, **auto_embedding_params) def __repr__(self): return ("{self}(num_reads={self.num_reads!r}, " "qpu_sampler={self.sampler!r}, " "sampling_params={self.sampling_params!r})").format(self=self) 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) response = self.sampler.sample(state.subproblem, **params) return state.updated(subsamples=response)
def pyqubo_response(df, param_a, param_b, param_c, num_reads, do_qbsolve): t_list = calc_marginals(df) #make H N = len(df) Y = Array.create('Y', shape=N, vartype='BINARY') ysum = sum(y for y in Y) H_0 = (ysum - t_list[0])**2 sex = df['SEX'].values.tolist() sex_array = sum(s * y for s, y in zip(sex, Y)) H_1 = (sex_array - t_list[1])**2 aop = df['AOP'].values.tolist() aop_array = sum(a * y for a, y in zip(aop, Y)) H_2 = (aop_array - t_list[2])**2 alpha = Placeholder("alpha") beta = Placeholder("beta") gamma = Placeholder("gamma") H = alpha * H_0 + beta * H_1 + gamma * H_2 #パラメータ feed_dict = {'alpha': param_a, 'beta': param_b, 'gamma': param_c} #QUBOのコンパイル model = H.compile() qubo, offset = model.to_qubo(feed_dict=feed_dict) if do_qbsolve == True: res = QBSolv().sample_qubo(qubo, num_reads=num_reads) else: s3_destination_folder = ('amazon-braket-ecc806acea4c', 'qaExactLogisticRegression_ssato') dw = BraketDWaveSampler( s3_destination_folder, device_arn='arn:aws:braket:::device/qpu/d-wave/DW_2000Q_6') qa_sampler = AutoEmbeddingComposite(dw) res = qa_sampler.sample(bqm, chain_strength=chain_strength, auto_scale=True, chain_break_fraction=True, num_reads=num_reads) return res
class ReverseAnnealingAutoEmbeddingSampler(traits.SubproblemSampler, traits.SISO, Runnable): """A quantum reverse annealing sampler for a subproblem with automated heuristic minor-embedding. Args: num_reads (int, optional, default=100): Number of states (output solutions) to read from the sampler. qpu_sampler (:class:`dimod.Sampler`, optional, default=:class:`AutoEmbeddingComposite`(:class:`DWaveSampler`())): Quantum sampler such as a D-Wave system. Subproblems that do not fit the sampler's structure are minor-embedded on the fly with :class:`~dwave.system.composites.AutoEmbeddingComposite`. anneal_schedule (list(list), optional, default=[[0, 1], [0.5, 0.5], [1, 1]]): An anneal schedule defined by a series of pairs of floating-point numbers identifying points in the schedule at which to change slope. The first element in the pair is time t in microseconds; the second, normalized persistent current s in the range [0,1]. The resulting schedule is the piecewise-linear curve that connects the provided points. For more details, see :meth:`~dwave.system.DWaveSampler.validate_anneal_schedule`. """ def __init__(self, num_reads=100, qpu_sampler=None, anneal_schedule=None, **runopts): super(ReverseAnnealingAutoEmbeddingSampler, self).__init__(**runopts) self.num_reads = num_reads if anneal_schedule is None: anneal_schedule = [[0, 1], [0.5, 0.5], [1, 1]] self.anneal_schedule = anneal_schedule if qpu_sampler is None: qpu_sampler = DWaveSampler( solver={'max_anneal_schedule_points__gte': len(self.anneal_schedule)}) # validate schedule, raising `ValueError` on invalid schedule or # `RuntimeError` if anneal schedule not supported by QPU (this could # happen only if user provided the `qpu_sampler`) qpu_sampler.validate_anneal_schedule(anneal_schedule) # embed on fly and only if needed self.sampler = AutoEmbeddingComposite(qpu_sampler) def __repr__(self): return ("{self}(num_reads={self.num_reads!r}, " "qpu_sampler={self.sampler!r}, " "anneal_schedule={self.anneal_schedule!r})").format(self=self) def next(self, state, **runopts): # TODO: handle more than just the first subsample (not yet supported via API) subsamples = self.sampler.sample( state.subproblem, num_reads=self.num_reads, initial_state=state.subsamples.first.sample, anneal_schedule=self.anneal_schedule) return state.updated(subsamples=subsamples)
class QPUSubproblemAutoEmbeddingSampler(Runnable, traits.SubproblemSampler): """A quantum sampler for a subproblem with automated heuristic minor-embedding. Args: num_reads (int, optional, default=100): Number of states (output solutions) to read from the sampler. qpu_sampler (:class:`dimod.Sampler`, optional, default=:class:`AutoEmbeddingComposite`(:class:`DWaveSampler`())): Quantum sampler such as a D-Wave system. Subproblems that do not fit the sampler's structure are minor-embedded on the fly with :class:`~dwave.system.composites.AutoEmbeddingComposite`. qpu_params (dict): Dictionary of keyword arguments with values that will be used on every call of the QPU sampler. See :ref:`samplers-examples`. """ def __init__(self, num_reads=100, qpu_sampler=None, qpu_params=None, **runopts): super(QPUSubproblemAutoEmbeddingSampler, self).__init__(**runopts) self.num_reads = num_reads if qpu_sampler is None: qpu_sampler = DWaveSampler() # embed on fly and only if needed self.sampler = AutoEmbeddingComposite(qpu_sampler) if qpu_params is None: qpu_params = {} self.qpu_params = qpu_params def __repr__(self): return ("{self}(num_reads={self.num_reads!r}, " "qpu_sampler={self.sampler!r}, " "qpu_params={self.qpu_params!r})").format(self=self) def next(self, state, **runopts): num_reads = runopts.get('num_reads', self.num_reads) qpu_params = runopts.get('qpu_params', self.qpu_params) params = qpu_params.copy() params.update(num_reads=num_reads) response = self.sampler.sample(state.subproblem, **params) return state.updated(subsamples=response)
def test_unstructured(self): child = dimod.NullSampler() sampler = AutoEmbeddingComposite(child) sampler.sample_ising({}, {(0, 1): -1}) sampler.sample_ising({}, {('a', 0): -1}, embedding_parameters={})
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()
def p_value_transition(self, output_path): t1 = int(np.dot(self.df['Y'], self.df['LI'])) t1_y = 0 p_dic = {} valid_y_list = [] for _ in range(self.n): s3_destination_folder = ('amazon-braket-ecc806acea4c', 'qaExactLogisticRegression_ssato') dw = BraketDWaveSampler( s3_destination_folder, device_arn='arn:aws:braket:::device/qpu/d-wave/DW_2000Q_6') qa_sampler = AutoEmbeddingComposite(dw) res = qa_sampler.sample(self.bqm, chain_strength=self.chain_strength, chain_break_fraction=True, num_reads=self.num_reads) for sample, energy, num_occurrences, chain_break_fraction in res.data( [ 'sample', 'energy', 'num_occurrences', 'chain_break_fraction' ]): if energy == 0.: this_time_y = tuple(sample.values()) if this_time_y in valid_y_list: continue else: valid_y_list.append(this_time_y) # this_time_y_se = pd.Series(this_time_y) if int(np.dot(this_time_y_se, self.df['LI'])) == t1: t1_y += 1 p_dic[len(valid_y_list)] = t1_y / len(valid_y_list) plt.xlabel('number of valid y') plt.ylabel('p value') plt.plot(list(p_dic.keys()), list(p_dic.values())) plt.savefig(output_path) plt.show() plt.close() return valid_y_list, p_dic
def num_y_transition(self, path): time_list = [] # valid_y_num_nodup = {} time_0 = time.time() for _ in range(self.n): s3_destination_folder = ('amazon-braket-ecc806acea4c', 'qaExactLogisticRegression_ssato') dw = BraketDWaveSampler( s3_destination_folder, device_arn='arn:aws:braket:::device/qpu/d-wave/DW_2000Q_6') qa_sampler = AutoEmbeddingComposite(dw) res = qa_sampler.sample(self.bqm, chain_strength=self.chain_strength, chain_break_fraction=True, num_reads=self.num_reads) for sample, energy, num_occurrences, chain_break_fraction in res.data( [ 'sample', 'energy', 'num_occurrences', 'chain_break_fraction' ]): if energy == 0.: sample_tuple = tuple(sample.values()) if sample_tuple in list(valid_y_num_nodup.keys()): continue else: valid_y_num_nodup[sample_tuple] = 1 time_1 = time.time() elapsed_time = time_1 - time_0 time_list.append(elapsed_time) valid_y_num_list = [i for i in range(1, len(valid_y_num_nodup) + 1)] plt.xlabel('time') plt.ylabel('number of valid y') plt.plot(time_list, valid_y_num_list) plt.savefig(path) plt.show() plt.close() return time_list
def test_smoke(self): nodelist = [0, 1, 2, 3] edgelist = [(0, 1), (1, 2), (2, 3), (0, 3)] child = dimod.StructureComposite(dimod.NullSampler(), nodelist, edgelist) sampler = AutoEmbeddingComposite(child) sampler.sample_ising({}, {(0, 1): -1}) sampler.sample_ising({}, {('a', 0): -1})
def test_broken_find_embedding(self): nodelist = [0, 1, 2, 3] edgelist = [(0, 1), (1, 2), (2, 3), (0, 3)] child = dimod.StructureComposite(dimod.NullSampler(), nodelist, edgelist) def find_embedding(*args, **kwargs): raise NotImplementedError sampler = AutoEmbeddingComposite(child, find_embedding=find_embedding) sampler.sample_ising({}, {(0, 1): -1}) with self.assertRaises(NotImplementedError): sampler.sample_ising({}, {('a', 0): -1})
def calculate(self, G, cost_matrix, starting_node): #if(len(G.nodes) > 9): # print("Dwave 2000Q systems can only embed up to 9 nodes on the lattice with current algorithm") # return [] # Different tests to make it happen! #Q = dnx.algorithms.traveling_salesman_qubo(G) #bqm = dimod.BinaryQuadraticModel.from_networkx_graph(G, 'BINARY', edge_attribute_name='weight') #response = EmbeddingComposite(DWaveSampler(solver='DW_2000Q_6')).sample(bqm, chain_strength=300, num_reads=1000) #print(response) #sampler = AutoEmbeddingComposite(DWaveSampler(solver='DW_2000Q_6')) sampler = AutoEmbeddingComposite( DWaveSampler(solver='Advantage_system1.1')) #sampleset = dimod.SimulatedAnnealingSampler().sample_qubo(Q) result = dnx.traveling_salesperson(G, sampler, start=starting_node, lagrange=90.0, weight='weight') return result
class ReverseAnnealingAutoEmbeddingSampler(traits.SubproblemSampler, traits.SubsamplesIntaking, traits.SISO, Runnable): r"""A quantum reverse annealing sampler for a subproblem with automated heuristic minor-embedding. Args: num_reads (int, optional, default=100): Number of states (output solutions) to read from the sampler. anneal_schedule (list(list), optional, default=[[0, 1], [0.5, 0.5], [1, 1]]): An anneal schedule defined by a series of pairs of floating-point numbers identifying points in the schedule at which to change slope. The first element in the pair is time t in microseconds; the second, normalized persistent current s in the range [0,1]. The resulting schedule is the piecewise-linear curve that connects the provided points. For more details, see :meth:`~dwave.system.DWaveSampler.validate_anneal_schedule`. qpu_sampler (:class:`dimod.Sampler`, optional): Quantum sampler such as a D-Wave system. Subproblems that do not fit the sampler's structure are minor-embedded on the fly with :class:`~dwave.system.composites.AutoEmbeddingComposite`. If sampler is not provided, it defaults to:: qpu_sampler = DWaveSampler( solver=dict(max_anneal_schedule_points__gte=len(anneal_schedule))) sampling_params (dict): Dictionary of keyword arguments with values that will be used on every call of the (embedding-wrapped QPU) sampler. auto_embedding_params (dict, optional): If provided, parameters are passed to the :class:`~dwave.system.composites.AutoEmbeddingComposite` constructor as keyword arguments. """ def __init__(self, num_reads=100, anneal_schedule=None, qpu_sampler=None, sampling_params=None, auto_embedding_params=None, **runopts): super(ReverseAnnealingAutoEmbeddingSampler, self).__init__(**runopts) self.num_reads = num_reads if anneal_schedule is None: anneal_schedule = [[0, 1], [0.5, 0.5], [1, 1]] self.anneal_schedule = anneal_schedule if qpu_sampler is None: qpu_sampler = DWaveSampler( solver=dict(max_anneal_schedule_points__gte=len(self.anneal_schedule))) # validate schedule, raising `ValueError` on invalid schedule or # `RuntimeError` if anneal schedule not supported by QPU (this could # happen only if user provided the `qpu_sampler`) qpu_sampler.validate_anneal_schedule(anneal_schedule) if sampling_params is None: sampling_params = {} self.sampling_params = sampling_params # embed on the fly and only if needed if auto_embedding_params is None: auto_embedding_params = {} self.sampler = AutoEmbeddingComposite(qpu_sampler, **auto_embedding_params) def __repr__(self): return ("{self}(num_reads={self.num_reads!r}, " "anneal_schedule={self.anneal_schedule!r}, " "qpu_sampler={self.sampler!r}, " "sampling_params={self.sampling_params!r})").format(self=self) def next(self, state, **runopts): num_reads = runopts.get('num_reads', self.num_reads) anneal_schedule = runopts.get('anneal_schedule', self.anneal_schedule) sampling_params = runopts.get('sampling_params', self.sampling_params) params = sampling_params.copy() params.update(num_reads=num_reads, anneal_schedule=anneal_schedule) # TODO: handle more than just the first subsample (not yet supported via API) subsamples = self.sampler.sample( state.subproblem, initial_state=state.subsamples.first.sample, **params) return state.updated(subsamples=subsamples)
assert len(w) == 1 assert issubclass(w[-1].category, DeprecationWarning) assert "renamed" in str(w[-1].message) def test_ising_sample(self): h = {'a': 1, 'b': -2} J = {('a', 'b'): -3} sampler = LazyFixedEmbeddingComposite(MockDWaveSampler()) response = sampler.sample_ising(h, J) # Check that at least one response was found self.assertGreaterEqual(len(response), 1) @dimod.testing.load_sampler_bqm_tests( AutoEmbeddingComposite(MockDWaveSampler())) class TestAutoEmbeddingComposite(unittest.TestCase): def test_broken_find_embedding(self): nodelist = [0, 1, 2, 3] edgelist = [(0, 1), (1, 2), (2, 3), (0, 3)] child = dimod.StructureComposite(dimod.NullSampler(), nodelist, edgelist) def find_embedding(*args, **kwargs): raise NotImplementedError sampler = AutoEmbeddingComposite(child, find_embedding=find_embedding) sampler.sample_ising({}, {(0, 1): -1}) with self.assertRaises(NotImplementedError):
from dwave.system.samplers import DWaveSampler from dwave.system.composites import AutoEmbeddingComposite, EmbeddingComposite from dwave.embedding.chain_strength import uniform_torque_compensation import dimod import timeit import time #繰り返さない! dw_sampler = DWaveSampler( endpoint="https://cloud.dwavesys.com/sapi", solver = 'DW_2000Q_6', token = "TOKY-1319d5c52b9aa35f34b40feba0cea58a4f5d3c09", retry_interval=5 ) qa_sampler = AutoEmbeddingComposite(dw_sampler) def calc_marginals(df): return np.array([ sum(df['Y']), np.dot(df['Y'], df['SEX']), np.dot(df['Y'], df['AOP']), ]) def make_Hamiltonian(df): t_list = calc_marginals(df) N=len(df) dup_list = [(i, i) for i in range(N)] comb_list = [(i, j) for i in range(N) for j in range(i+1, N)] lin_Y = [1-2*t_list[0] for (i, _) in dup_list] #同じy同士
def getSampler(self): return AutoEmbeddingComposite(KerberosSampler())
# Verify deprecation warning assert len(w) == 1 assert issubclass(w[-1].category, DeprecationWarning) assert "renamed" in str(w[-1].message) def test_ising_sample(self): h = {'a': 1, 'b': -2} J = {('a', 'b'): -3} sampler = LazyFixedEmbeddingComposite(MockDWaveSampler()) response = sampler.sample_ising(h, J) # Check that at least one response was found self.assertGreaterEqual(len(response), 1) @dimod.testing.load_sampler_bqm_tests(AutoEmbeddingComposite(MockDWaveSampler())) class TestAutoEmbeddingComposite(unittest.TestCase): def test_broken_find_embedding(self): nodelist = [0, 1, 2, 3] edgelist = [(0, 1), (1, 2), (2, 3), (0, 3)] child = dimod.StructureComposite(dimod.NullSampler(), nodelist, edgelist) def find_embedding(*args, **kwargs): raise NotImplementedError sampler = AutoEmbeddingComposite(child, find_embedding=find_embedding) sampler.sample_ising({}, {(0, 1): -1}) with self.assertRaises(NotImplementedError): sampler.sample_ising({}, {('a', 0): -1})