def test_dwave_system(self): from dwave.system import DWaveSampler, EmbeddingComposite sampler = EmbeddingComposite(DWaveSampler()) h = {'a': -1, 'b': +1} J = {('a', 'b'): -1} resp = sampler.sample_ising(h, J)
def main(token='', n_vertices=0, neighbours=None, filename=None, local=False): ''' Using any graph at all, if given the number of nodes and the neighbours, 0-indexed, this will try to minimize the number of same-coloured neighbours. Runs on the Basic Dwave Solver, so very quickly and painlessly. :param n_vertices: This is the number of vertices in the graph to be 2-coloured. Vertices should be 0-indexed. :param neighbours: This is the adjacency list describing the graph. This should only describe vertex indices, 0-indexed. :param filename: If the problem is desired to be loaded from a file, this string should be the path to that file. :param local: Utilized solely by __main__, will make the program output the whole solution for display in Dwave's web inspector. :param token: The Dwave token to be used. This should be a string, in the format used on the dwave leap website. :return: This returns a dictionary. The only key is "solution", containing an ordered list of the states of the vertices for the best solution. Each state is either 1 or -1. ''' if filename == None: filename = 'problem.txt' if neighbours == None: n_vertices, neighbours = load_problem(filename) # 2. Define problem h = [0 for x in range(n_vertices)] J = dict((tuple(neighbour), 10) for neighbour in neighbours) # print(J) # 3. Instantiate solver sampler = EmbeddingComposite(DWaveSampler(token=token)) # 4. Sample problem solution = sampler.sample_ising(h, J, chain_strength=50, num_reads=50) # 5. Use response best_solution = [int(solution.first.sample[x]) for x in range(n_vertices)] # print( best_solution ) if local: return solution else: return {'solution': best_solution}
from dwave.system import DWaveSampler, EmbeddingComposite import dwave.inspector sampler = EmbeddingComposite(DWaveSampler(solver='DW_2000Q_6', #token='', )) h = {} J = { ('Lisa', 'Timo'): 3, # Ergänzen Sie hier die Werte # der anderen Koppler } response = sampler.sample_ising( h, J, num_reads=100, chain_strength=1, # hiermit müssen Sie # rumspielen um # gute Lösungen zu # bekommen annealing_time=20, # diesen Wert # können Sie zstl. # ändern um bessere # Lösungen zu # bekommen ) dwave.inspector.show(response)
neighbours = tuple( tuple(int(x) for x in line.rstrip().split()) for line in content[1:]) return n, neighbours filename = 'flipCoinProblem.txt' n_vertices, neighbours = load_problem(filename) # 2. Define problem h = [0 for x in range(n_vertices)] # Make sure to set coupling to -10 to force all nodes to have the same state/color/spin. J = dict((tuple(neighbour), -10) for neighbour in neighbours) # 3. Instantiate solver sampler = EmbeddingComposite(DWaveSampler(token='')) # 4. Sample problem solution = sampler.sample_ising(h, J, chain_strength=50, num_reads=50) # 5. Use response best_solution = [int(solution.first.sample[x]) for x in range(n_vertices)] # print( best_solution ) print(best_solution)
What happens to the number of solutions in each state and the energies?) 4. What happens if you multiply all of the h and J biases by the same factor (2x, 5x, 10x)? Do your solutions change? What about their energies? 5. What happens if you ferromagnetically couple the chain, and impose opposite h bias on each end of the chain? What if those biases have different magnitude? ''' # Modifiable parameters num_qubits = 10 # Number of qubits in our chain fm_qubit_bias = [ 0 ] * num_qubits # List of biases to apply to each qubit in our chain fm_coupler_strength = -1 # The coupling we want to apply to two adjacent qubits num_reads = 10 # The number of times the QPU is sampled # Ising model parameters h = fm_qubit_bias J = {} # coupling strength is specified using a dictionary for i in range(num_qubits - 1): J[(i, i + 1)] = fm_coupler_strength # Submit the problem to the QPU sampler = EmbeddingComposite(DWaveSampler(solver={'qpu': True})) response = sampler.sample_ising(h, J, num_reads=num_reads) # Show the problem visualization on the QPU #inspector.show(response) print("QPU response") print(response)
# --------------------------------------------------------------------------# # Import the functions and packages that are used from dwave.system import EmbeddingComposite, DWaveSampler from dimod import BinaryQuadraticModel # Define the problem as a Python dictionary and convert it to a BQM Q = { ('B', 'B'): 1, ('K', 'K'): 1, ('A', 'C'): 2, ('A', 'K'): -2, ('B', 'C'): -2 } bqm = BinaryQuadraticModel.from_qubo(Q) # Convert the bqm to an Ising model ising_model = bqm.to_ising() # 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_ising(h=ising_model[0], J=ising_model[1], num_reads=10) print(sampleset)
fm_qubit_bias = [ 0 ] * num_qubits # List of biases to apply to each qubit in our chain fm_coupler_strength = -1 # The coupling we want to apply to two adjacent qubits annealing_time = 20 anneal_schedule = [(0.0, 0.0), (20, 1)] # Ising model parameters h = fm_qubit_bias J = {} for i in range(num_qubits - 1): J[(i, i + 1)] = fm_coupler_strength # Submit the problem to the QPU # NOTE: The annealing_time and annealing_schedule parameters are mutually exclusive. You can only use one at a time. # To use annealing_time: # response = sampler.sample_ising(h, J, annealing_time=annealing_time num_reads=10) # To use annealing_schedule: # response = sampler.sample_ising(h, J, annealing_schedule=annealing_schedule num_reads=10) sampler = EmbeddingComposite(DWaveSampler(solver={'qpu': True})) sampleset = sampler.sample_ising(h, J, anneal_schedule=anneal_schedule, num_reads=100) inspector.show(sampleset) print("QPU response") print(sampleset)
J_PeriodicBC[(0, num_qubits - 1)] = fm_coupler_strength # J_PeriodicBC[(num_qubits-1,0)] = fm_coupler_strength # HW 3.e Chimera graph J_Chimera = {} left = [i for i in range(num_qubits) if not i % 2] right = [i for i in range(num_qubits) if i % 2] for i in left: for j in right: J_Chimera[(i, j)] = fm_coupler_strength # HW 3.f Chimera graph #J_Chimera[(0,2)] = fm_coupler_strength # HW 3.g Clique J_Clique = {} qubit_list = list(range(num_qubits)) for i in range(num_qubits): qubit_list.remove(i) for j in qubit_list: J_Clique[(i, j)] = fm_coupler_strength # Submit the problem to the QPU sampler = EmbeddingComposite(DWaveSampler(solver={'qpu': True})) response = sampler.sample_ising(h, J_Chimera, num_reads=num_reads) # Show the problem visualization on the QPU inspector.show(response) print("QPU response") print(response)
from dwave.system import DWaveSampler, EmbeddingComposite import dwave.inspector sampler = EmbeddingComposite(DWaveSampler( solver='DW_2000Q_6', #token='', )) h = {} J = { ('Lisa','Timo'): 3, ('Lisa','Anna'): 2, ('Lisa','Tom'): 6, ('Timo','Anna'): 5, ('Timo','Tom'): 3, ('Anna','Tom'): 5, } response = sampler.sample_ising( h, J, num_reads=100, chain_strength=4, annealing_time=100, ) dwave.inspector.show(response)
# You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # 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. # import packages that are needed from dwave.system import EmbeddingComposite, DWaveSampler import dwave.inspector as inspector # h specifies the local biases applied to each variable (qubit in this case) h = {0: -1, 1: 1} # J specifies the coupling between two variables (in this case, adjacent qubits) J = {(0, 1): -1} sampler = EmbeddingComposite(DWaveSampler(solver={'qpu': True})) # Run the problem on the sampler and print the results sampleset = sampler.sample_ising(h, J, num_reads=10) # Show the problem visualization on the QPU #inspector.show(response) print("QPU response") print(sampleset)
row += str(round(th[i], 2)) + '\t' elif (i, j) in tJ: tJ[(i, j)] = tJ[(i, j)] / scale_factor row += str(round(tJ[(i, j)], 2)) + '\t' else: row += str(0) + '\t' print(row) input() print("\nSending problem to QPU...") sampler = EmbeddingComposite(DWaveSampler( solver={'qpu': True })) # Use EmbeddingComposite to work around any missing qubits sampleset = sampler.sample_ising(th, tJ, num_reads=10, label='Training - QUBO Lifecycle') print("\nBest QMI solution found:\n") best_QMI_solution = sampleset.first.sample print(best_QMI_solution) input() print("\nConverting QMI solution to Ising ...") best_Ising_solution = dict(best_QMI_solution) del best_Ising_solution[4] # Resolve a potential chain break print("\nBest Ising solution found:\n") print(best_Ising_solution)
# http://www.apache.org/licenses/LICENSE-2.0 # # 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. # --------------------------------------------------------------------------# # This program demonstrates a basic Ocean program that runs an Ising problem # on the D-Wave QPU. # --------------------------------------------------------------------------# # Import the functions and packages that are used from dwave.system import EmbeddingComposite, DWaveSampler # Define the problem as two Python dictionaries: # h for linear terms, J for quadratic terms h = {} J = {('A', 'K'): -0.5, ('B', 'C'): -0.5, ('A', 'C'): 0.5} # 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_ising( h, J, num_reads=10, label='Example - Simple Ocean Programs: Ising') print(sampleset)
# 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: set_2.append(i) # Calculate max_cuts
# Import the functions and packages that are used from dwave.system import EmbeddingComposite, DWaveSampler from dimod import BinaryQuadraticModel # Define the problem as a Python dictionary and convert it to a BQM Q = { ('B', 'B'): 1, ('K', 'K'): 1, ('A', 'C'): 2, ('A', 'K'): -2, ('B', 'C'): -2 } bqm = BinaryQuadraticModel.from_qubo(Q) # Convert the bqm to an Ising model ising_model = bqm.to_ising() # 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_ising( h=ising_model[0], J=ising_model[1], num_reads=10, label='Example - Simple Ocean Programs: Conversion') print(sampleset)
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)