def solve(self): if (self.useQPU): sampler = EmbeddingComposite(DWaveSampler(solver={'qpu': True})) sampleset = sampler.sample_qubo(self.Q, num_reads=self.n_reads, chain_strength=self.chain) elif (self.useNeal): bqm = BinaryQuadraticModel.from_qubo(self.Q, offset=self.offset) sampler = neal.SimulatedAnnealingSampler() sampleset = sampler.sample(bqm, num_reads=self.n_reads, chain_strength=self.chain) elif (self.useHyb): bqm = BinaryQuadraticModel.from_qubo(self.Q, offset=self.offset) sampler = LeapHybridSampler() sampleset = sampler.sample(bqm, num_reads=self.n_reads) else: bqm = BinaryQuadraticModel.from_qubo(self.Q, offset=self.offset) sampler = TabuSampler() sampleset = sampler.sample(bqm, num_reads=self.n_reads, chain_strength=self.chain) self.sampleset = sampleset
def solve_QPU( self, h1=1.0, num=100, sol="DW_2000Q_6", emb_param={ "verbose": 2, "max_no_improvement": 6000, "timeout": 600, "chainlength_patience": 1000, "threads": 15 }): ''' EmbeddingComposite サンプラを用いた、Solver。結果を変数に格納する self.best_dist 得られた最良の距離(最短距離) self.best_route 得られた最良のルート parameters ----- float h1(default 1.0) : ModelからQUBO行列を作成する際の距離の重み float h1(default 1.0) : ModelからQUBO行列を作成する際の制約の重み int num : サンプリング回数 str sol : Solver名 dict emb_param : 内部で呼ばれるfind_embeddingのオプション returns ----- なし ''' sampler = EmbeddingComposite(DWaveSampler(solver=sol)) #QUBO変換 Q, offset = self.model.to_qubo(feed_dict={"H1": h1}) #D-Waveへデータ送信 self.responses = sampler.sample_qubo(Q, num_reads=num, chain_strength=5.0, embedding_parameters=emb_param, postprocess="optimization") #結果をDecode(Constraintをチェックするため) self.solutions = self.model.decode_dimod_response(self.responses, feed_dict={"H1": h1}) #ベストな距離を変数に格納する self.best_dist = 100000 self.best_route = [] for sol in self.solutions: #制約違反がない結果について、過去のBestの距離と比較 if len(sol[1]) == 0: tmp_sol = [ sum(i * val for i, val in sol[0]['x'][j].items()) for j in range(self.size) ] if self.route_len(tmp_sol) < self.best_dist: self.best_dist = self.route_len(tmp_sol) self.best_route = tmp_sol
def solve(self, useQPU=False, useNeal=False, useHyb=True, time_limit = 10, num_reads = 100, chain_strength = 10000): Q = self.Q BQM_offset = 0 # TODO: Use the accumulated quadratic constants from the constraints bqm = BinaryQuadraticModel.from_qubo(Q, offset=BQM_offset) self.sampleset = None # Call the requested solver if ( useQPU ): print("Solving using the DWaveSampler on the QPU...") sampler = EmbeddingComposite(DWaveSampler(solver={'qpu': True})) sampleset = sampler.sample_qubo(Q, num_reads=num_reads,chain_strength = chain_strength) elif ( useHyb ): print("Solving using the LeapHybridSolver...") sampler = LeapHybridSampler() sampleset = sampler.sample(bqm, time_limit = time_limit) elif ( useNeal ): print("Solving using the SimulatedAnnealing...") sampler = neal.SimulatedAnnealingSampler() sampleset = sampler.sample(bqm, num_reads = num_reads) else: print("Solving using the TabuSampler...") sampler = TabuSampler() sampleset = sampler.sample(bqm, num_reads = num_reads) self.sampleset = sampleset count = 0 for res in self.sampleset.data(): count += 1 return (count)
def generateRealSamples(qubo, num_reads=10): sampler = DWaveSampler() embedding = EmbeddingComposite(sampler) return embedding.sample_qubo(qubo, num_reads=guarded_num_reads(num_reads))
# Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. ''' Problem: Partition the set [-5, 9, 4] such that the sum of the subsets are equal ''' # 1. Import packages from dwave.system import DWaveSampler, EmbeddingComposite # 2. Define the problem Q = { ('x0', 'x0'): 260, ('x1', 'x1'): 36, ('x2', 'x2'): -64, ('x0', 'x1'): -360, ('x1', 'x2'): 288, ('x0', 'x2'): -160 } # 3. Instantiate a solver solver = EmbeddingComposite(DWaveSampler(solver={'qpu': True})) # 4. Solve the problem sampleset = solver.sample_qubo(Q, chain_strength=200, num_reads=100) # 5. Interpret results print(sampleset)
elif m == myK: Q[i, j] = -2**(n - myK) * Hlambda[alpha, beta] else: Q[i, j] = 2**(n + m - 2 * myK) * Hlambda[alpha, beta] if i < j: Q[i, j] *= 2 # Send the job to the requested sampler. if quantum == 1: print("Using DWaveSampler") sampler = EmbeddingComposite( DWaveSampler(solver={'topology__type__eq': 'pegasus'}, annealing_time=mytime)) sampleset = sampler.sample_qubo(Q, num_reads=myreads, chain_strength=mychain) rawoutput = sampleset.aggregate() else: print("Using SimulatedAnnealingSampler") sampler = SimulatedAnnealingSampler() sampleset = sampler.sample_qubo(Q, num_reads=myreads) rawoutput = sampleset.aggregate() # Record the input choices, display the raw data, and provide headers for the physics output that will follow. print("myx=", myx) print("myB=", myB) print("myK=", myK) print("mylambda=", mylambda) print("myreads=", myreads) print("mychain=", mychain)
('q12', 'q23'): -4, ('q13', 'q23'): 2, ('q14', 'q23'): 4, ('q21', 'q23'): 990, ('q22', 'q23'): 980, ('q11', 'q24'): -4, ('q12', 'q24'): -8, ('q13', 'q24'): 4, ('q14', 'q24'): 8, ('q21', 'q24'): 980, ('q22', 'q24'): 960, ('q23', 'q24'): 20 } Q = dict(linear) Q.update(quadratic) # Minor Embed and sample 10 times on a default D-Wave sytem, repeat up to 100 times # or until the lowest energy is found tic = time.perf_counter() for i in range(1, 100): sampleset = sampler_auto.sample_qubo(Q, num_reads=10) print(sampleset) print(sampleset.first[1]) if sampleset.first[1] == -26: print("Lowest energy was reached. \n") print("This took {0} samples of 10".format(i)) break toc = time.perf_counter() print(f"Found the lowest energy in {toc - tic:0.10f} seconds") print(sampleset.first)
# Update Q matrix for every edge in the graph for i, j in G.edges: Q[(i,i)]+= -1 Q[(j,j)]+= -1 Q[(i,j)]+= 2 # ------- Run our QUBO on the QPU ------- # Set up QPU parameters chain_strength = 0.1 num_reads = 10 # Run the QUBO on a solver with the specified topology sampler = EmbeddingComposite(DWaveSampler(solver={'topology__type__eq': 'pegasus'})) sampleset = sampler.sample_qubo(Q, chain_strength=chain_strength, num_reads=num_reads, label='Training - Embedding', return_embedding=True) print("\nEmbedding found:\n", sampleset.info['embedding_context']['embedding']) print("\nSampleset:") print(sampleset) # ------- Print results to user ------- print("\nSolutions:") print('-' * 60) print('{:>15s}{:>15s}{:^15s}{:^15s}'.format('Set 0','Set 1','Energy','Cut Size')) print('-' * 60) for sample, E in sampleset.data(fields=['sample','energy']): S0 = [k for k,v in sample.items() if v == 0]
from dwave.system import DWaveSampler, EmbeddingComposite Q = {} g = 36 Q[(0, 0)] = 17 - 3 * g Q[(1, 1)] = 21 - 3 * g Q[(2, 2)] = 19 - 3 * g Q[(0, 1)] = 2 * g Q[(0, 2)] = 2 * g Q[(1, 2)] = 2 * g sampler = EmbeddingComposite(DWaveSampler(solver={'qpu': True})) res = sampler.sample_qubo(Q, chain_strength=30, num_reads=10) print(res)
] G = construct_arbitrage_graph(securities, exchange_rates) edge_weights = nx.get_edge_attributes(G,'weight') if DRAW: nx.draw(G, pos=nx.circular_layout(G), with_labels=True, connectionstyle='arc3, rad = 0.1') #nx.draw_networkx_edge_labels(G, pos=nx.spring_layout(G), edge_labels=edge_weights) plt.show() Q, edges = construct_qubo(G) #print(Q) sampler = DWaveSampler() #print(sampler.properties['h_range']) #print(sampler.properties['j_range']) sampler_embedded = EmbeddingComposite(sampler) sampleset = sampler_embedded.sample_qubo(Q, num_reads=10000) sample_result = sampleset.record.tolist() sample_result.sort(key = lambda s:s[1]) # sort based on energy #print(sampleset) """for r,sol in enumerate(sample_result): picked = [] zeroed = [] for i,e in enumerate(sol[0]): if e == 1: picked.append(edges[i]) zeroed.append(1) else:
M[0][2] = 0 M[1][0] = 4 * y M[1][1] = 3 - lam M[1][2] = y M[2][0] = 0 M[2][1] = y M[2][2] = 3 - lam #--------------------------------------------- P = np.kron(M, qubit_table(k)) Q = defaultdict(float) Q = np.triu(P, k=1) + np.triu(P, k=0) sampler = EmbeddingComposite(DWaveSampler()) sampleset = sampler.sample_qubo(Q, num_reads=n_reads, chain_strength=chain) print("k=", k, "y=", y, "chain=", chain, "lam=", lam, "n_reads=", n_reads) print(sampleset) #Print the results in a file out_file = "RES_k_{}_y_{}_ch_{}_l_{}_nr_{}.txt".format(k, y, chain, lam, n_reads) with open(out_file, 'a') as file: sys.stdout = file # Change the standard output to the file we created. print("\n RUN " "") print("k=", k, "y=", y, "chain=", chain, "lam=", lam, "n_reads=", n_reads) print(sampleset)
# (0, 0, -41, 26, 32) # (0, 0, 0, -50, 42) # (0, 0, 0, 0, -57)} Q = { ('x1', 'x1'): -20, ('x1', 'x2'): 6, ('x1', 'x3'): 8, ('x1', 'x4'): 10, ('x1', 'x5'): 12, ('x2', 'x2'): -33, ('x2', 'x3'): 14, ('x2', 'x4'): 18, ('x2', 'x5'): 22, ('x3', 'x3'): -44, ('x3', 'x4'): 26, ('x3', 'x5'): 32, ('x4', 'x4'): -53, ('x4', 'x5'): 42, ('x5', 'x5'): -60, } # Define the sampler that will be used to run the problem sampler = EmbeddingComposite(DWaveSampler()) # Run the problem on the sampler and print the results sampleset = sampler.sample_qubo(Q, num_reads=10, label='Example - Simple Ocean Programs: QUBO') print(sampleset)
d[i] += 1 if j in d: d[j] += 1 # Set formulation type based on user input formulation = sys.argv[1] # Set parameters to run the problem chainstrength = 3 # update as needed num_reads = 10 # update as needed sampler = EmbeddingComposite(DWaveSampler()) # Formulate and run the problem based on command line input if formulation == "qubo": Q = get_qubo() sample_set = sampler.sample_qubo(Q, chain_strength=chainstrength, num_reads=num_reads) elif formulation == "ising": h, J = get_ising() sample_set = sampler.sample_ising(h, J, chain_strength=chainstrength, num_reads=num_reads) elif formulation == "bqm": Q = get_qubo() bqm = get_bqm(Q) sample_set = sampler.sample(bqm) # Determine the resulting sets result = list(sample_set.first.sample[i] for i in G.nodes) set_1, set_2 = [], [] for i in range(len(result)): if result[i] == 1: set_1.append(i) else:
from dwave.system import DWaveSampler, EmbeddingComposite import random import pyqubo sampler = EmbeddingComposite(DWaveSampler()) N = int(input()) m = int(input()) weight = [random.randint(-100, 100) for i in range(N)] x = pyqubo.Array.create('bin_array', shape=N, vartype='BINARY') lagrangian = 0 for elem in weight: lagrangian += abs(elem) hamiltonian = -sum( a * j for a, j in zip(weight, x)) + lagrangian * (sum(i for i in x) - m)**2 Q, offset = hamiltonian.compile().to_qubo() sampleset = sampler.sample_qubo(Q, num_reads=1000) print(sampleset) # doctest: +SKIP print(' '.join(map(str, weight)))
# Solve A*x=b by `numpy.linalg.lstsq` np_x = np.linalg.lstsq(A, true_b, rcond=None)[0] # Solve A_discrete*q=b problem as BQM optimization # through simulated annealing or quantum annealing Q = bl_lstsq.get_qubo(A_discrete, true_b, eq_scaling_val=eq_scaling_val) if sampler_type == 'QA': try: sampler = EmbeddingComposite(DWaveSampler(solver={'qpu': True})) _sampler_args = {} if 'num_reads' in sampler.parameters: _sampler_args['num_reads'] = num_reads if 'answer_mode' in sampler.parameters: _sampler_args['answer_mode'] = 'raw' sampleset = sampler.sample_qubo(Q, **_sampler_args) except ValueError: warnings.warn('Cannot access QPU, use \ SimulatedAnnealingSampler instead.') sampler = SimulatedAnnealingSampler() sampleset = sampler.sample_qubo(Q, num_reads=num_reads) elif sampler_type == 'SA': sampler = SimulatedAnnealingSampler() sampleset = sampler.sample_qubo(Q, num_reads=num_reads) else: raise (ValueError("The sampler_type is wrong, \ please enter 'SA' or 'QA'")) # Solve A_discrete*q=b by brute force # Warning: this may take a lot of time! best_q, best_x, min_norm = bl_lstsq.bruteforce(A_discrete, true_b, bit_value)
from collections import defaultdict import networkx as nx # 2. Set up the problem # Create empty graph G = nx.Graph() # Add edges to the graph (also adds nodes) G.add_edges_from([('a', 'b'), ('b', 'c'), ('b', 'd'), ('c', 'd'), ('c', 'f'), ('d', 'f'), ('d', 'e'), ('e', 'f')]) print(G.edges) # ------- Set up our QUBO dictionary ------- # Initialize our Q matrix Q = defaultdict(int) # Update Q matrix for every edge in the graph for i, j in G.edges: Q[(i, i)] += -1 Q[(j, j)] += -1 Q[(i, j)] += 2 # 3. Instantiate a solver sampler = EmbeddingComposite(DWaveSampler(solver={'qpu': True})) # 4. Solve the problem sampleset = sampler.sample_qubo(Q, chain_strength=8, num_reads=100) # 5. Interpret the results - print the results with the lowest energy print(sampleset.lowest())
def solve(self, R, qubo, samples, exact, verbose, useQPU, useHyb, useNeal, useTabu): use_QUBO = qubo # We obtain the calculations performed at load time c_coeffs = self.get_qubo_coeffs(R) c_a = c_coeffs['c_a'] c_b = c_coeffs['c_b'] c_c = c_coeffs['c_c'] a1 = c_coeffs['a1'] a2 = c_coeffs['a2'] a3 = c_coeffs['a3'] g_values = self.get_g_values(R) g0 = g_values['g0'] g1 = g_values['g1'] g2 = g_values['g2'] g3 = g_values['g3'] g4 = g_values['g4'] e = g_values['e'] g3_addition = g_values['g3add'] # Solve the equation. First solution is lowest energy if use_QUBO: #Using QUBO Q = defaultdict(float) Q[0, 0] = c_a Q[0, 1] = c_b Q[1, 0] = c_b Q[1, 1] = c_a #Q = [(2 * a2 - 2 * a3, 2 * a3),(2 * a3,2 * a2 - 2 * a3 )] offset = 0 if (useQPU): chain_strength = 4 if (verbose == True): print("Solving using the DWaveSampler on the QPU...") sampler = EmbeddingComposite( DWaveSampler(solver={'qpu': True})) sampleset = sampler.sample_qubo(Q, num_reads=samples, chain_strength=chain_strength) elif (useHyb): if (verbose == True): print("Solving using the LeapHybridSolver...") time_limit = 3 bqm = BinaryQuadraticModel.from_qubo(Q, offset=offset) sampler = LeapHybridSampler() sampleset = sampler.sample(bqm, time_limit=time_limit) elif (useNeal): if (verbose == True): print("Solving using the Leap SimulatedAnnealing...") bqm = BinaryQuadraticModel.from_qubo(Q, offset=offset) sampler = neal.SimulatedAnnealingSampler() sampleset = sampler.sample(bqm, num_reads=samples) else: if (verbose == True): print("Solving using the TabuSampler...") sampler = TabuSampler() bqm = BinaryQuadraticModel.from_qubo(Q, offset=offset) sampleset = sampler.sample(bqm, num_reads=samples) if (verbose == True): print(sampleset.first.sample) if (verbose == True): print(sampleset) # Step 3: Get x0 and x1 for first energy result for set in sampleset.data(): x0 = set.sample[0] x1 = set.sample[1] energy = set.energy if (verbose == True): print("x0,x1,ener : ", x0, x1, energy) break H_b = self.get_energy_from_binary_spins(R, x0, x1) Y = 4 * x0 * x1 + (2 * a2 - 2 * a3) * x0 + ( 2 * a2 - 2 * a3) * x1 + a3 - 2 * a2 + a1 # convert x0,x1 to ising spins sz0 = (2 * x0) - 1 sz1 = (2 * x1) - 1 else: # Using SPIN (ising): H = h_1 * s_1 + h_2 * s_2 + J_{1,2} * s_1 *s_2 sampler = TabuSampler() response = sampler.sample_ising({ 'a': c_a, 'b': c_a }, {('a', 'b'): c_b}, num_reads=samples) if (verbose == True): print(response) for set in response.data(): sz0 = set.sample['a'] sz1 = set.sample['b'] energy = set.energy if (verbose == True): print("sz0,sz1,ener : ", sz0, sz1, energy) break H_b = self.get_energy_from_ising_spins(R, sz0, sz1) # Step 4: Calculate Y = ( a1 + a2( sz0 + sz1 ) + a3 (sz0*sz1)) Y = (a1 + a2 * (sz0 + sz1) + a3 * (sz0 * sz1)) # Convert to get x0,x1 x0 = (sz0 + 1) / 2 x1 = (sz1 + 1) / 2 # Get hx1 and hx2 in : # hx**2 + 2*g3*hx = Y # a = 1, b = 2g3, c = -Y a = 1 b = 2 * g3 c = -Y #print("a,b,c,b**2-4*a*c : ", a,b,c,b**2-4*a*c) # Solve H1 for x (minimum of the two possibilities) hx1 = (-b + np.sqrt(b**2 - 4 * a * c)) / (2 * a) hx2 = (-b - np.sqrt(b**2 - 4 * a * c)) / (2 * a) if (hx2 < hx1): swp = hx2 hx2 = hx1 hx1 = swp # Add g3_addition to hx1 hx1 += g3_addition H0_ver = (g1 * sz0) + (g2 * sz1) + (g3 * sz0 * sz1) H0 = hx1 H = H0 + g0 assert (H_b == H) return (H)