def solve_qubo(Q, sampler="CPU", # CPU or QPU k=10, chain_strength=None): """ Given an upper triangular matrix Q of size NxN, solves the quadratic unconstrained binary optimization (QUBO) problem given by minimize sum(x[i] * Q[i,j] * x[j] for i in range(N), for j in range(i+1, N)) Uses dimod.SimulatedAnnealingSampler, which solves the problem k times through simulated annealing (on a regular CPU). This method returns the best solution found. """ # assert isinstance(Q, np.ndarray) # assert sampler in ["CPU", "QPU"] n = Q.shape[0] nz = len(Q[Q != 0]) print("Solving QUBO problem (%d vars, %d nz) on %s..." % (n, nz, sampler)) start = time.time() if sampler == "CPU": sampler = dimod.SimulatedAnnealingSampler() response = sampler.sample_qubo(Q, num_reads=k) else: if chain_strength is None: chain_strength = int(10 * np.max(np.abs(Q))) sampler = AutoEmbeddingComposite(DWaveSampler(solver=dict(qpu=True))) response = sampler.sample_qubo(Q, num_reads=k, chain_strength=chain_strength) elapsed = time.time() - start print("Solved in %.2f seconds" % elapsed) solution = min(response.data(["sample", "energy"]), key=lambda s: s.energy) return solution, response
def dimod_solver(self): """ Uses dimod package from D-Wave to implement a binary quadratic model and then use a simulated annealer to sample from the model. """ linear = self.h_dict print(linear) quadratic = self.j print(quadratic) #offset = self.offset offset = 0 model = dimod.BinaryQuadraticModel(linear, quadratic, offset, dimod.Vartype.SPIN) response = dimod.SimulatedAnnealingSampler().sample(model) #response = dimod.ExactSolver().sample(model) #print(response) min_energy = 0 for sample in response.data(['sample', 'energy']): sample_dict = { 'sample': {k: int((1 + sample[0][k]) / 2) for k in sample[0]} } sample_dict.update({'energy': sample[1]}) self.samples.append(sample_dict) min_energy = min(sample[1], min_energy) self.solution = { f'x{k+1}': v for k, v in sample_dict['sample'].items() if k < len(self.masses) } if min_energy == sample[1] else self.solution if min_energy == sample[1]: print(sample) self._solution_blocks()
def test_dimod_vs_list(self): G = nx.complete_graph(4) for u, v in G.edges(): G[u][v]['weight'] = 1 route = tsp.traveling_salesperson(G, dimod.ExactSolver()) route = tsp.traveling_salesperson(G, dimod.SimulatedAnnealingSampler())
def run_sim(model): ''' Run QUBO problem using D-Wave's simulated annealing Args: model - BQM model to solve Returns: solution set ''' return dimod.SimulatedAnnealingSampler().sample(model)
def test_bug1(self): # IN IN OUT AUX h = {0: -.5, 1: 0, 2: 1, 3: -.5} J = {(0, 2): -1, (1, 2): -1, (0, 3): .5, (1, 3): -1} J[(0, 4)] = -.1 J[(4, 5)] = -.1 J[(5, 6)] = -.1 h[4] = 0 h[5] = 0 h[6] = .1 response = dimod.SimulatedAnnealingSampler().sample_ising(h, J, num_reads=100)
def sample(self, bqm, num_reads=10, flux_biases=[]): # we are altering the bqm new_bqm = bqm.copy() for v, fbo in enumerate(flux_biases): self.flux_biases_flag = True new_bqm.add_variable(v, 1000. * fbo) # add the bias response = dimod.SimulatedAnnealingSampler().sample(new_bqm, num_reads=num_reads) energies = [bqm.energy(sample) for sample in response.samples(sorted_by=None)] return dimod.Response.from_dicts(response.samples(sorted_by=None), {'energy': energies}, vartype=bqm.vartype)
def setUp(self): self.sampler = dimod.SimulatedAnnealingSampler() self.sampler_factory = dimod.SimulatedAnnealingSampler
import dwave_networkx as dnx import networkx as nx import dimod # シュミレーション # from dwave.system.samplers import DWaveSampler # 実機 # from dwave.system.composites import EmbeddingComposite # 実機 sampler = dimod.SimulatedAnnealingSampler() # シュミレーション # sampler = EmbeddingComposite(DWaveSampler()) # 実機 G = nx.Graph() G.add_edges_from([(0,1),(0,2),(1,3),(2,3),(3,4)]) # 頂点被覆問題をとくためのライブラリ(min_vertex_cover) candidate = dnx.min_vertex_cover(G, sampler) print(candidate)
sampler.parameters ################################################################################################################################ # S I M U L A T O R ################################################################################################################################ import dimod # cannot put no of repetitions #solver = dimod.ExactSolver().sample(bqm) #solver = dimod.SimulatedAnnealingSampler() #response = solver.sample_qubo(Q) bqm = dimod.BinaryQuadraticModel.from_qubo(Q) #response = dimod.ExactSolver().sample(bqm) # other solver simulator? response = dimod.SimulatedAnnealingSampler().sample(bqm, num_reads=10) #for sample, energy, num_occurrences in response.data(['sample', 'energy', 'num_occurrences']): # print("sample: ", sample, "energy: ", energy, "num_occurences: ", num_occurrences) # rearrange the response response_df = pd.DataFrame([ (str(sample), energy, num_occurrences) for sample, energy, num_occurrences in response.data( ['sample', 'energy', 'num_occurrences']) ]) response_df.columns = ['sample', 'energy', 'num_occurrences'] response_pv = response_df.pivot_table(index=['sample', 'energy'], values='num_occurrences', aggfunc=sum) print(response_pv.sort_values(by='num_occurrences', ascending=False))
def test_dimod_vs_list(self): G = nx.path_graph(5) indep_set = dnx.maximum_independent_set(G, dimod.ExactSolver()) indep_set = dnx.maximum_independent_set(G, dimod.SimulatedAnnealingSampler())
print(model) print() # We can solve it exactly from dimod.reference.samplers import ExactSolver sampler = ExactSolver() solution = sampler.sample(model) print("The exact solution is") print(solution) print() # Or with *simulated annealing* (a heuristic method used in classical computers) sampler = dimod.SimulatedAnnealingSampler() response = sampler.sample(model, num_reads=10) print("The solution with simulated annealing is") print(response) print() # And, of course, with D-Wave's quantum computer from dwave.system.samplers import DWaveSampler from dwave.system.composites import EmbeddingComposite sampler = EmbeddingComposite(DWaveSampler()) sampler_name = sampler.properties['child_properties']['chip_id'] response = sampler.sample(model, num_reads=5000) print("The solution obtained by D-Wave's quantum annealer", sampler_name, "is") print(response)
def test_intro_example(self): # Dev note: test that the example in the intro documentation still works, if this fails go # update the example! # from dwave.system.samplers import DWaveSampler # from dwave.system.composites import EmbeddingComposite # import networkx as nx # import matplotlib.pyplot as plt # Represent the map as the nodes and edges of a graph provinces = [ 'AB', 'BC', 'MB', 'NB', 'NL', 'NS', 'NT', 'NU', 'ON', 'PE', 'QC', 'SK', 'YT' ] neighbors = [('AB', 'BC'), ('AB', 'NT'), ('AB', 'SK'), ('BC', 'NT'), ('BC', 'YT'), ('MB', 'NU'), ('MB', 'ON'), ('MB', 'SK'), ('NB', 'NS'), ('NB', 'QC'), ('NL', 'QC'), ('NT', 'NU'), ('NT', 'SK'), ('NT', 'YT'), ('ON', 'QC')] # Function for the constraint that two nodes with a shared edge not both select one color def not_both_1(v, u): return not (v and u) # # Function that plots a returned sample # def plot_map(sample): # G = nx.Graph() # G.add_nodes_from(provinces) # G.add_edges_from(neighbors) # # Translate from binary to integer color representation # color_map = {} # for province in provinces: # for i in range(colors): # if sample[province+str(i)]: # color_map[province] = i # # Plot the sample with color-coded nodes # node_colors = [color_map.get(node) for node in G.nodes()] # nx.draw_circular(G, with_labels=True, node_color=node_colors, node_size=3000, cmap=plt.cm.rainbow) # plt.show() # Valid configurations for the constraint that each node select a single color one_color_configurations = {(0, 0, 0, 1), (0, 0, 1, 0), (0, 1, 0, 0), (1, 0, 0, 0)} colors = len(one_color_configurations) # Create a binary constraint satisfaction problem csp = dwavebinarycsp.ConstraintSatisfactionProblem( dwavebinarycsp.BINARY) # Add constraint that each node (province) select a single color for province in provinces: variables = [province + str(i) for i in range(colors)] csp.add_constraint(one_color_configurations, variables) # Add constraint that each pair of nodes with a shared edge not both select one color for neighbor in neighbors: v, u = neighbor for i in range(colors): variables = [v + str(i), u + str(i)] csp.add_constraint(not_both_1, variables) # Convert the binary constraint satisfaction problem to a binary quadratic model bqm = dwavebinarycsp.stitch(csp) sampler = dimod.SimulatedAnnealingSampler() # # Set up a solver using the local system’s default D-Wave Cloud Client configuration file # # and sample 50 times # sampler = EmbeddingComposite(DWaveSampler()) # doctest: +SKIP response = sampler.sample(bqm, num_reads=10) # # Plot the lowest-energy sample if it meets the constraints sample = next(response.samples()) # doctest: +SKIP # if not csp.check(sample): # doctest: +SKIP # print("Failed to color map") # else: # plot_map(sample) if not csp.check(sample): pass
def phase_2(enemy, our, previous_enemy): h_const_2 = 2 num_checkers_on_board = np.sum(our) + np.sum(enemy) num_checker_constraint = -num_spots + num_checkers_on_board c = num_checker_constraint constraint_const_2 = 40 j_const_2 = 2 mill_constant_2 = 1 linear = {} for i in range(num_spots): if our[i] == 1: linear[i + 1] = h_const_2 elif enemy[i] == 1: linear[i + 1] = -h_const_2 else: linear[i + 1] = 0 #print(linear) # Adding quadratic terms for constraint quadratic = {} for i in range(1, num_spots): for j in range(i + 1, num_spots + 1): quadratic[(i, j)] = 2 * constraint_const_2 # Update linear for constraint for i in range(1, num_spots + 1): linear[i] -= 2 * c * constraint_const_2 offset = (c**2 + num_spots) * constraint_const # Think about sign # Set interactions, i.e. update quadratic for i in range(num_spots): if enemy[i]: idx = b.get_rowcol_idx(i) for j in idx: if i < j: quadratic[(i + 1, j + 1)] += -j_const_2 else: quadratic[(j + 1, i + 1)] += -j_const_2 # update quadratic for mill energy decrease for i in range(0, num_spots): if enemy[i] == 0: continue idx = b.get_rowcol_idx(i) for j in idx: if enemy[j]: if i < j: quadratic[(i + 1, j + 1)] -= 2 * mill_constant_2 else: quadratic[(j + 1, i + 1)] -= 2 * mill_constant_2 else: if i < j: quadratic[(i + 1, j + 1)] += 2 * mill_constant_2 else: quadratic[(j + 1, i + 1)] += 2 * mill_constant_2 offset -= (2 * num_spots) * mill_constant_2 vartype = dimod.SPIN bqm = dimod.BinaryQuadraticModel(linear, quadratic, offset, vartype) sampler = dimod.SimulatedAnnealingSampler() sample_set = sampler.sample(bqm, num_reads=10) #sampler = dimod.ExactSolver() #sample_set = sampler.sample(bqm) next_state = sample_set.samples()[0] # Maybe do sampling instead?? #print(next_state) #print("Previous: " + str(previous_enemy)) #print("New: " + str(enemy)) #print(quadratic) for i in range(1, num_spots + 1): if next_state[i] == 1: enemy[i - 1] = 1 b.place_marker(pos=i - 1, player_num=2) # Find the move move = enemy - previous_enemy print(move) for i in range(num_spots): if move[i]: move_to = i + 1 print("Moved to: " + str(move_to)) previous_enemy = list(enemy) print(b) print(sample_set) # Choose our input our_pos = int(input('Give position to place marker (1-24): ')) our[our_pos - 1] = 1 b.place_marker(pos=our_pos - 1, player_num=1) return
linear = {('x0', 'x0'): -1, ('x1', 'x1'): -1, ('x2', 'x2'): -3} quadratic = {('x0', 'x1'): 2, ('x0', 'x2'): 2, ('x1', 'x2'): 2} Q = dict(linear) Q.update(quadratic) """ from dwave.system.samplers import DWaveSampler from dwave.system.composites import EmbeddingComposite response = EmbeddingComposite(DWaveSampler()).sample_qubo(Q, num_reads=1000) for sample, energy, num_occurrences, chain_break_fraction in list(response.data()): print(sample, "Energy: ", energy, "Occurrences: ", num_occurrences) """ import dimod b = dimod.BinaryQuadraticModel.from_qubo(Q, 0.0) r = dimod.SimulatedAnnealingSampler().sample(b) for sample, energy, num_occurrences in r.data( ['sample', 'energy', 'num_occurrences']): print(sample, "Energy: ", energy, "Occurrences: ", num_occurrences)
for p in phi: J += summand(t, p) return J N = 6 h = {} for i in range(N): m_str = "x" + str(i) h[m_str] = 0 J = {} for m1 in range(0, N): for n1 in range(0, N): for m2 in range(0, N): for n2 in range(0, N): if (m1 != m2 or n1 != n2): str_mn = ('x' + str(m1 * N + n1), 'x' + str(m2 * N + n2)) J[str_mn] = (Jmn_int(m1, n1, m2, n2)) import numpy as np sampleset = dimod.SimulatedAnnealingSampler().sample_ising(h, J) print(sampleset.first) mat_dict = sampleset.first[0] opt_code_2d = np.zeros(shape=(N, N)) for m in range(N): for n in range(N): dict_string = 'x' + str(m * N + n) opt_code_2d[m, n] = mat_dict[dict_string] RCS_calc(opt_code_2d, N)
def __init__(self, H, qpu, vartype, encoding): """ Class that takes a dictionary representation of an ising-hamiltonian and submits problem to a quantum annealer qpu: string specifies quantum processing unit to be used during calculation--referring to name specifying this information in dwave config file vartype: string QUBO or Ising (all case variants acceptable) encoding: string logical or direct. If logical, embeds onto chip under the hood. If direct, assumes manual embedding and tries to put directly onto chip as is. H: dict The hamiltonian represented as a dict of the form {(0, 0): h0, (0, 1): J01, ...} OR {(0, 0): 'h0', (0, 1): 'J0', (1, 1): 'h1', ...} """ # poplate run information super().__init__(qpu, vartype, encoding) # create a set of regex rules to parse h/J string keys in H # also creates a "rules" dictionary to relate qubit weights to relevant factor self.hvrule = re.compile('h[0-9]*') self.Jvrule = re.compile('J[0-9]*') self.weight_rules = {} # create list of qubits/ couplers and # dicts that map indepndent params to # all qubits/ couplers that have that value self.H = H self.qubits = [] self.params_to_qubits = {} self.couplers = [] self.params_to_couplers = {} for key, value in H.items(): if key[0] == key[1]: self.qubits.append(key[0]) if type(value) != str: div_idx = -1 else: div_idx = value.find('/') if div_idx == -1: self.weight_rules[key[0]] = 1 else: self.weight_rules[key[0]] = float(value[div_idx + 1:]) value = value[:div_idx] self.params_to_qubits.setdefault(value, []).append(key[0]) else: self.couplers.append(key) if type(value) != str: div_idx = -1 else: div_idx = value.find('/') if div_idx == -1: self.weight_rules[key] = 1 else: self.weight_rules[key] = float(value[div_idx + 1:]) value = value[:div_idx] self.params_to_couplers.setdefault(value, []).append(key) self.nqubits = len(self.qubits) self.Hsize = 2**(self.nqubits) if qpu == 'dwave': try: # let OCEAN handle embedding if encoding == "logical": # encode several times on graph # based on qubits encoded if len(self.qubits) <= 4: self.sampler = EmbeddingComposite( TilingComposite(DWaveSampler(), 1, 1, 4)) else: self.sampler = EmbeddingComposite(DWaveSampler()) # otherwise, assume 1-1 else: self.sampler = DWaveSampler() except: raise ConnectionError( "Cannot connect to DWave sampler. Have you created a DWave config file using 'dwave config create'?" ) elif qpu == 'test': self.sampler = dimod.SimulatedAnnealingSampler() elif qpu == 'numerical': self.processordata = loadAandB() self.graph = nx.Graph() self.graph.add_edges_from(self.couplers) self.data = pd.DataFrame() # save values/ metadata self.H = copy.deepcopy(H) if encoding == 'direct': self.wqubits = self.sampler.properties['qubits'] self.wcouplers = self.sampler.properties['couplers']
if include_in_list: list1.append(numbers[index]) else: list2.append(numbers[index]) return list1, list2 def print_result(sample_set): for sample in sample_set.samples(): list1, list2 = split_numbers_list(numbers, sample) print "list1: {}, sum: {}, list2: {}, sum: {}".format( list1, sum(list1), list2, sum(list2)) exact_solver = dimod.ExactSolver() simulated_annealing_sampler = dimod.SimulatedAnnealingSampler() dwave_sampler = EmbeddingComposite(DWaveSampler()) print "#" * 80 numbers = generate_numbers( 50) # generate a list of numbers to be split into equal sums bqm = to_bqm(numbers) # # ExactSolver fails when list has many items eg. len(numbers) == 100 # # start = time.time() # sample_set = solve(exact_solver, bqm) # end = time.time() # print "Using ExactSolver (elapsed time: {}s)".format(end-start) # sample_set = sample_set.truncate(5)
test_size=0.20, stratify=bc_data.target, ) # Transform {0,1} labels into {-1,1} labels. y_train = 2 * y_train - 1 y_test = 2 * y_test - 1 # Train classical model ab_clf = AdaBoostClassifier(n_estimators=20) ab_clf.fit(X_train, y_train) sampler = {} if len(sys.argv) < 2: sampler['sampler'] = dimod.SimulatedAnnealingSampler() sampler['params'] = {} else: token = sys.argv[1] sampler['sampler'] = EmbeddingComposite( DWaveSampler(token=token, solver={'qpu': True})) sampler['params'] = { 'num_reads': 1000, 'auto_scale': True, 'num_spin_reversal_transforms': 10, 'postprocess': 'optimization', } skb = SkewBoost(ab_clf.estimators_) # Train SkewBoost on a D-Wave QPU or using SimulatedAnnealingSampler skb.fit(X_train,