def __init__(self, N, M, L, annealing_time, programming_thermalization, readout_thermalization): self.N = N self.M = M self.L = L self.Vr = np.zeros((M, N)) self.Wr = np.zeros((L, M)) self.Wg = np.zeros((M, L)) self.Vg = np.zeros((N, M)) self.J = np.zeros((L, L)) self.h = np.zeros(L) self.bvr = np.zeros((M, )) self.bwr = np.zeros((L, )) self.bwg = np.zeros((M, )) self.bvg = np.zeros((N, )) self.annealing_time = annealing_time self.programming_thermalization = programming_thermalization self.readout_thermalization = readout_thermalization self.hidden_graph = [] #Adjacency Matrix of the hidden layer for i in range(L): #Creates the abovesaid Adjacency Matrix for j in range(i + 1, L): self.hidden_graph.append((i, j)) self.sampler_manual = DWaveSampler(solver={'qpu': True }) #DWave sampler instance self.embedding = find_embedding( self.hidden_graph, self.sampler_manual.edgelist, random_seed=10) #Calculates and stores heuristic embedding
def __init__(self, sub_m=4, sub_n=4, t=4, sampler=None, solver='DW_2000Q_2_1', token=None): self.sub_m = sub_m self.sub_n = sub_n self.t = t self.solver = solver if sampler is None: if token: self.sampler = DWaveSampler(solver=self.solver, token=token) else: self.sampler = DWaveSampler(solver=self.solver) self.tiling_composite = self.tile_qpu() self.bqm = dimod.BQM.empty('SPIN') self.null_bqm = dimod.BQM.empty('SPIN') self.tiles = {} self.var2idx = {}
def __init__(self, params, graph_type="chimera", n_nodes=None, n_edges=None): self.params = params self.graph_type = graph_type device_name = { 'chimera': 'DW_2000Q_6', 'pegasus': 'Advantage_system1.1', 'simulator': None } if graph_type == 'simulator': self.sampler = DWaveSampler(solver={'qpu': False}) else: self.sampler = DWaveSampler(solver={ 'qpu': True, 'name': device_name[graph_type] }) self.list_edges = np.array(self.sampler.edgelist) self.list_nodes = np.array(self.sampler.nodelist) nodes_file = "data/pegasus/list_nodes.npy" edges_file = "data/pegasus/list_edges.npy" if graph_type == 'pegasus': if n_nodes is not None: if os.path.exists(nodes_file): print("Loading list nodes...") self.list_nodes = np.load(nodes_file) else: print("Taking subgraph...") self.list_nodes = take_subgraph(self.sampler, n_nodes) np.save(nodes_file, self.list_nodes) self.graph = self.sampler.to_networkx_graph().subgraph( self.list_nodes) self.list_edges = np.array(self.graph.edges) if n_edges is not None: if os.path.exists(edges_file): print("Loading list edges...") self.list_edges = np.load(edges_file) else: print("Removing edges...") edges_idx = np.sort( np.random.choice(len(self.list_edges), n_edges, replace=False)) self.list_edges = self.list_edges[edges_idx] np.save(edges_file, self.list_edges) print("Number of qubits", len(self.list_nodes)) print("Number of edges", len(self.list_edges)) super().__init__()
def objective(trial): b1 = trial.suggest_uniform('b1', 0.0, 20) b2 = trial.suggest_uniform('b2', 0.0, 20) b3 = trial.suggest_uniform('b3', 0.0, 20) def_dict = { "balancer1": b1, "balancer2": b2, "balancer3": b3, "IntChain": 1.0 } bqm = model.to_dimod_bqm(feed_dict=def_dict) sampler = EmbeddingComposite(DWaveSampler(sampler="DW_2000Q_6")) responses = sampler.sample(bqm, num_reads=5000) solutions = model.decode_dimod_response(responses, feed_dict=def_dict) cnt = 0 for idx, sol in enumerate(solutions): if len(sol[1]) < 10: cnt += responses.record[idx][2] return cnt
def cluster_points(scattered_points, filename): # Set up problem # Note: max_distance gets used in division later on. Hence, the max(.., 1) # is used to prevent a division by zero coordinates = [Coordinate(x, y) for x, y in scattered_points] max_distance = max(get_max_distance(coordinates), 1) # Build constraints csp = dwavebinarycsp.ConstraintSatisfactionProblem(dwavebinarycsp.BINARY) # Apply constraint: coordinate can only be in one colour group choose_one_group = {(0, 0, 1), (0, 1, 0), (1, 0, 0)} for coord in coordinates: csp.add_constraint(choose_one_group, (coord.r, coord.g, coord.b)) # Build initial BQM bqm = dwavebinarycsp.stitch(csp) # Edit BQM to bias for close together points to share the same color for i, coord0 in enumerate(coordinates[:-1]): for coord1 in coordinates[i + 1:]: # Set up weight d = get_distance(coord0, coord1) / max_distance # rescale distance weight = -math.cos(d * math.pi) # Apply weights to BQM bqm.add_interaction(coord0.r, coord1.r, weight) bqm.add_interaction(coord0.g, coord1.g, weight) bqm.add_interaction(coord0.b, coord1.b, weight) # Edit BQM to bias for far away points to have different colors for i, coord0 in enumerate(coordinates[:-1]): for coord1 in coordinates[i + 1:]: # Set up weight # Note: rescaled and applied square root so that far off distances # are all weighted approximately the same d = math.sqrt(get_distance(coord0, coord1) / max_distance) weight = -math.tanh(d) * 0.1 # Apply weights to BQM bqm.add_interaction(coord0.r, coord1.b, weight) bqm.add_interaction(coord0.r, coord1.g, weight) bqm.add_interaction(coord0.b, coord1.r, weight) bqm.add_interaction(coord0.b, coord1.g, weight) bqm.add_interaction(coord0.g, coord1.r, weight) bqm.add_interaction(coord0.g, coord1.b, weight) # Submit problem to D-Wave sampler sampler = EmbeddingComposite(DWaveSampler(solver={'qpu': True})) #sampler = neal.SimulatedAnnealingSampler() sampleset = sampler.sample(bqm, chain_strength=4, num_reads=1000) best_sample = sampleset.first.sample # Visualize graph problem dwave.inspector.show(bqm, sampleset) # Visualize solution groupings = get_groupings(best_sample) visualize_groupings(groupings, filename) return groupings
def get_sampler_from_config(self, profile=None, solver=None, sampler_type=None): """Return a dimod.Sampler object found in the user's configuration file, associated solver information, and any extra parameters needed.""" try: with Client.from_config(profile=profile, client=sampler_type) as client: if solver == None: solver = client.default_solver solver_name = solver["name__eq"] else: solver_name = solver solver = {"name": solver} if isinstance(client, hybrid.Client): sampler = LeapHybridSampler(profile=profile, solver=solver) elif isinstance(client, sw.Client): self.qmasm.abend("QMASM does not currently support remote software solvers") else: sampler = DWaveSampler(profile=profile, solver=solver) info = self._recursive_properties(sampler) info["solver_name"] = solver_name info["endpoint"] = client.endpoint if profile != None: info["profile"] = profile return sampler, info, {} except Exception as err: self.qmasm.abend("Failed to construct a sampler (%s)" % str(err))
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 test_quantum2(): ''' Example using D-Wave's quantum annealing Note: Embedding is done with the use of D-Wave composite ''' X = np.array([[1, 2], [1, 3], [9, 5], [9, 6]]) # input data k = 2 model = genModel(X, k) # generate BQM model (not yet embedded) sampler = EmbeddingComposite(DWaveSampler( solver={'qpu': True })) # sets D-Wave's sampler, embedding is done automatically solution_set = sampler.sample( model, num_reads=100, return_embedding=True) # run on the D-wave hardware print("Embedding: ", solution_set.info["embedding_context"]["embedding"]) # Count the number of qubits used num_qubits = 0 for entry in solution_set.info["embedding_context"]["embedding"].values(): num_qubits += len(entry) print("Number of qubits: ", num_qubits) M, assignments = postprocess2( X, solution_set.first.sample) # postprocess the solution print("Centroids: ") print(M) print("Assignments: " + str(assignments))
def _get_sampler(self, profile, solver): "Return a dimod.Sampler object." # Handle built-in software samplers as special cases. info = {} if solver != None: info["solver_name"] = solver if solver == "exact": return ExactSolver(), info elif solver == "neal": return SimulatedAnnealingSampler(), info elif solver == "tabu": return TabuSampler(), info # In the common case, read the configuration file, either the # default or the one named by the DWAVE_CONFIG_FILE environment # variable. if profile != None: info["profile"] = profile try: with Client.from_config(profile=profile) as client: if solver == None: solver = client.default_solver else: solver = {"name": solver} sampler = DWaveSampler(profile=profile, solver=solver) info = { "solver_name": sampler.solver.name, "endpoint": client.endpoint } return sampler, info except Exception as err: self.qmasm.abend("Failed to construct a sampler (%s)" % str(err))
def solve_qa(self, verbose=True, num_reads=100): assert self.token is not None assert self.mode == "bqm" if self.qubo is None: self.pre_process() if verbose: print(f"Solving SMTI with: {SOLVER}") print(f"Optimal Solution: {-(len(self.encoding) * self.p2 + self.matching.size * self.p1)}") chain_strength = self.get_chain_stength() + 1 # max element in qubo matrix + epsilon solver_limit = len(self.encoding) # solver_limit => size of qubo matrix G = nx.complete_graph(solver_limit) dw_solver = DWaveSampler(solver=SOLVER, token=self.token, endpoint=ENDPOINT) embedding = minorminer.find_embedding(G.edges, dw_solver.edgelist) fixed_embedding = FixedEmbeddingComposite(dw_solver, embedding) result = fixed_embedding.sample(self.qubo, num_reads=num_reads, chain_strength=chain_strength) dw_solver.client.close() # clean up all the thread mess the client creates so it does not block my code if verbose: print(result) for index, (sample, energy, occ, chain) in enumerate(result.record): match_, _ = self.encode_qa(sample.tolist()) stable_, size_ = Solution(self.matching, match_).is_stable() print(f"{index}: ", match_, size_, stable_) samples = pd.DataFrame() for sample, energy, occ, chain in result.record: match, valid = self.encode_qa(sample.tolist()) stable, size = Solution(self.matching, match).is_stable() samples = samples.append({"match": match, "sample": sample.tolist(), "energy": energy, "occ": occ, "chain": chain, "valid": valid, "stable": stable, "size": size}, ignore_index=True) return samples
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 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 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 solve_dwave(Q, conf_file, **kwargs): import urllib3 urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning) from dwave.system import EmbeddingComposite from dwave.system import DWaveSampler sampler = DWaveSampler(config_file=conf_file, permissive_ssl=True) solver = EmbeddingComposite(sampler) logger.info(f'Using {sampler.solver} as the sub-QUBO solver.') return solve_qbsolv(Q, solver=solver, **kwargs)
def generate_embedding(size): qpusampler = DWaveSampler(solver='Advantage_system1.1') edges = qpusampler.structure.edgelist gen_graph = make_complete_graph(size) embeddings = find_embedding(gen_graph, edges) n_qb = count_physical_qubits(embeddings) print("Embedding on %d spin variables" %(n_qb)) return embeddings
def set_sampler(): ''' Returns D-Wave sampler being used for annealing Note: Currently defaults to D-Wave 2000Q_6 Returns: D-Wave sampler ''' return DWaveSampler(solver={'qpu': True})
def set_sampler(): '''Returns a dimod sampler''' token = get_token() sampler = EmbeddingComposite( DWaveSampler(endpoint='https://cloud.dwavesys.com/sapi/', token=token, solver={'qpu': True})) return sampler
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}
def __init__(self, hidlen, vislen, sampler="Test"): self.sep = 0 if sampler == "LeapHybridSampler": self.sampler = LeapHybridSampler() #accessing dwave self.sep = 1 if sampler == "DWaveSampler": self.sampler = AutoEmbeddingComposite(DWaveSampler()) if sampler == "Test": self.sampler = SimulatedAnnealingSampler() self.t_step = 1000 self.stepsize = 0.1 self.path = "" self.mute = True self.hidlen = hidlen #handling indexes self.vislen = vislen self.outlen = 10 self.hind = ['h' + str(i) for i in range(self.hidlen)] self.vind = ['v' + str(i) for i in range(self.vislen)] self.ind = self.hind + self.vind self.cmap = [] self.coef = np.zeros( (self.vislen + self.hidlen, self.vislen + self.hidlen), dtype=np.float_) #self.Q = {(i, j): self.coef[i][j] for i in self.ind for j in self.ind} self.bqm = dimod.BinaryQuadraticModel(self.coef, 'SPIN') self.response = 0 #response and data from it self.answerlen = 0 self.answer = [] self.index = [] for i in range(self.hidlen + self.vislen): self.index += [i] self.answer_occ = [] self.answern = 0 self.prob = [] self.top = [0] * 3 self.expected = 0 self.images = [] #images from dataset self.label = 0 self.labels = [] self.chosen_images = [] self.prob = [] self.chosen_prob = [] self.single_unfixed = [] self.double_unfixed = [] self.single_fixed = [] self.double_fixed = [] self.delta = [] self.mean_single = []
def test_problem_label_in_sampleset(self): """All data adapters should propagate problem label.""" # sample bqm -> sampleset qpu = DWaveSampler() sampler = FixedEmbeddingComposite(qpu, self.embedding) sampleset = sampler.sample(self.bqm, label=self.label, **self.params) # ensure `from_bqm_sampleset` adapter propagates label data = from_bqm_sampleset(self.bqm, sampleset, sampler, params=self.params) self.assertEqual(data['details']['label'], self.label)
def factor(P): bP = "{:06b}".format(P) csp = dbc.factories.multiplication_circuit(3) bqm = dbc.stitch(csp, min_classical_gap=.1) p_vars = ['p0', 'p1', 'p2', 'p3', 'p4', 'p5'] fixed_variables = dict(zip(reversed(p_vars), bP)) fixed_variables = {var: int(x) for (var, x) in fixed_variables.items()} for var, value in fixed_variables.items(): bqm.fix_variable(var, value) sampler = EmbeddingComposite(DWaveSampler(solver={'qpu': True})) sampleset = sampler.sample(bqm, num_reads=1000) a, b = to_base_ten(sampleset.first.sample) print("Given integer P={0}, found factors a={1} and b={2}".format(P, a, b)) return a, b
def optimize_advantage(self,count=False,Best=0,balancer=1.0): from pyqubo import Array,Constraint,Placeholder,UnaryEncInteger,Sum #LogEncInteger from dwave.system import EmbeddingComposite,DWaveSampler x = Array.create("x",shape=(self.num),vartype="BINARY") #y = LogEncInteger("y",lower=0,upper=5) y = UnaryEncInteger("y",lower=0,upper=5) #価値が最大になるように(符号を反転させる) #H1 = -sum([x[i]*self.p[i].get_value() for i in range(self.num)]) H1 = -Sum(0,self.num,lambda i :x[i]*self.p[i].get_value() ) #重さが目的の重量になるように #H2 = Constraint((self.limit_weight -sum([x[i]*p_i.get_weight() for i,p_i in enumerate(self.p)]) - y*10)**2,"Const Weight") H2 = Constraint((self.limit_weight -Sum(0,self.num,lambda i: x[i]*self.p[i].get_weight()) - y*10)**2,"Const Weight") #H2 = Constraint((self.limit_weight -Sum(0,self.num,lambda i: x[i]*self.p[i].get_weight()))**2,"Const Weight") H = H1 + H2*Placeholder("balancer") model = H.compile() balance_dict = {"balancer":balancer} bqm = model.to_dimod_bqm(feed_dict=balance_dict) sampler = EmbeddingComposite(DWaveSampler(solver="Advantage_system1.1")) #sampler = EmbeddingComposite(DWaveSampler(solver="DW_2000Q_6")) responses = sampler.sample(bqm,num_reads=1000) solutions = model.decode_dimod_response(responses,feed_dict=balance_dict) #Optuna用 バランス調査 if count == True: counter = 0 for idx,sol in enumerate(solutions): const_str = sol[1] val = sum(int(sol[0]['x'][i])*self.p[i].get_value() for i in range(self.num)) weight = sum(int(sol[0]['x'][i])*self.p[i].get_weight() for i in range(self.num)) #重量が制限以下、かつ価値が最適解の9割以上をカウント if len(const_str) == 0 and val > Best*0.9 and weight <= self.limit_weight: counter += responses.record[idx][2] del H1,H2,H,model,bqm,responses,solutions gc.collect() return counter if len(solutions[0][1]) == 0: print(f" y= { sum(2**i*y_i for i,y_i in enumerate(solutions[0][0]['y']))}") print("## Advantage Solver Optimized Result") self.print([int(solutions[0][0]['x'][i]) for i in range(self.num)]) else: print("## Advantage Solver Optimizing Failed")
def main(sampler_type, region, show, inspect): if sampler_type is None: print("No solver selected, defaulting to hybrid") sampler_type = 'hybrid' # get the appropriate signed social network G = global_signed_social_network(region=region) # choose solver and any tuning parameters needed if sampler_type == 'cpu': params = dict(num_reads=100) sampler = SimulatedAnnealingSampler() elif sampler_type == 'hybrid': params = dict() sampler = LeapHybridSampler() elif sampler_type == 'qpu': params = dict( num_reads=100, chain_strength=2.0, ) sampler = dimod.TrackingComposite(EmbeddingComposite(DWaveSampler())) else: raise RuntimeError("unknown solver type") # use the chosen sampler (passing in the parameters) edges, colors = dnx.structural_imbalance( G, sampler, label='Example - Structural Imbalance', **params) if inspect and sampler_type == 'qpu': dwave.inspector.show(sampler.output) print("Found", len(edges), 'violations out of', len(G.edges), 'edges') draw_social_network(G, colors) if show: plt.show() else: filename = 'structural imbalance {} {}.png'.format( sampler_type, region) plt.savefig(filename, facecolor='white') plt.clf()
def main(sampler_type, region, show): if sampler_type is None: print("No solver selected, defaulting to hybrid") sampler_type = 'hybrid' if region == 'global' and sampler_type == 'qpu': print("Given region is too large for the QPU, please choose another " "region or use hybrid.") # get the appropriate signed social network G = global_signed_social_network(region=region) # choose solver and any tuning parameters needed if sampler_type == 'cpu': params = dict(num_reads=100) sampler = SimulatedAnnealingSampler() elif sampler_type == 'hybrid': params = dict() sampler = LeapHybridSampler() elif sampler_type == 'qpu': params = dict( num_reads=100, chain_strength=2.0, ) sampler = EmbeddingComposite(DWaveSampler()) else: raise RuntimeError("unknown solver type") # use the chosen sampler (passing in the parameters) edges, colors = dnx.structural_imbalance(G, sampler, **params) print("Found", len(edges), 'violations out of', len(G.edges), 'edges') draw_social_network(G, colors) if show: plt.show() else: filename = 'stuctural imbalance {} {}.png'.format(sampler_type, region) plt.savefig(filename, facecolor='white', dpi=500) plt.clf()
def test_initial_state(self): sampler = EmbeddingComposite(DWaveSampler()) bqm = dimod.BinaryQuadraticModel.from_ising({ 'a': 2.0, 'b': -2.0 }, {('a', 'b'): -1}) kwargs = { 'initial_state': { 'a': 1, 'b': 1 }, 'anneal_schedule': [(0, 1), (55.0, 0.45), (155.0, 0.45), (210.0, 1)] } sampler.sample(bqm, **kwargs).resolve()
def dwave_physical_DW_2000Q_5(self): print("\nD-wave quantum annealer....") from dwave.system import DWaveSampler, FixedEmbeddingComposite from dwave.embedding.chimera import find_clique_embedding qpu = DWaveSampler(token=self.token, endpoint=self.endpoint, solver=dict(name='DW_2000Q_5'), auto_scale=False) self.title = "D-Wave Quantum Annealer" embedding = find_clique_embedding( self.bqm.variables, 16, 16, 4, # size of the chimera lattice target_edges=qpu.edgelist) qpu_sampler = FixedEmbeddingComposite(qpu, embedding) print("Maximum chain length for minor embedding is {}.".format( max(len(x) for x in embedding.values()))) from hybrid.reference.kerberos import KerberosSampler kerberos_sampler = KerberosSampler() selected_features = np.zeros((len(self.features), len(self.features))) for k in range(1, len(self.features) + 1): print("Submitting for k={}".format(k)) kbqm = dimod.generators.combinations(self.features, k, strength=6) kbqm.update(self.bqm) kbqm.normalize() best = kerberos_sampler.sample(kbqm, qpu_sampler=qpu_sampler, num_reads=10, max_iter=1).first.sample for fi, f in enumerate(self.features): selected_features[k - 1, fi] = best[f] if self.is_notebook: from helpers.draw import plot_feature_selection plot_feature_selection(self.features, selected_features)
def test_sampler_type_validation(self): """All data adapters should fail on non-StructuredSolvers.""" # sample qpu = DWaveSampler() sampler = FixedEmbeddingComposite(qpu, self.embedding) sampleset = sampler.sample(self.bqm, return_embedding=True, **self.params) # resolve it before we mangle with it sampleset.info['problem_id'] # change solver to unstructured to test solver validation sampler.child.solver = unstructured_solver_mock # ensure `from_bqm_sampleset` adapter fails on unstructured solver with self.assertRaises(TypeError): from_bqm_sampleset(self.bqm, sampleset, sampler, params=self.params)
def test_sampler_graph_validation(self): """All data adapters should fail on non-Chimera/Pegasus solvers.""" # sample qpu = DWaveSampler() sampler = FixedEmbeddingComposite(qpu, self.embedding) sampleset = sampler.sample(self.bqm, return_embedding=True, **self.params) # resolve it before we mangle with it sampleset.info['problem_id'] # change solver topology to non-chimera/pegasus to test solver validation sampler.child.solver.properties['topology']['type'] = 'unknown' # ensure `from_bqm_sampleset` adapter fails on unstructured solver with self.assertRaises(TypeError): from_bqm_sampleset(self.bqm, sampleset, sampler, params=self.params)
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 _test_from_bqm_sampleset(self, bqm): # sample qpu = DWaveSampler() sampler = FixedEmbeddingComposite(qpu, self.embedding) sampleset = sampler.sample(bqm, return_embedding=True, chain_strength=self.chain_strength, **self.params) # convert data = from_bqm_sampleset(bqm, sampleset, sampler, params=self.params) # construct (unembedded) response with chain breaks resolved # NOTE: for bqm/sampleset adapter, this is the best we can expect :( # inverse the embedding var_to_idx = {var: idx for idx, var in enumerate(sampleset.variables)} unembedding = { q: var_to_idx[v] for v, qs in self.embedding.items() for q in qs } # embed sampleset solutions_without_chain_breaks = [[ int(sample[unembedding[q]]) if q in unembedding else val for q, val in enumerate(solution) ] for solution, sample in zip(self.response['solutions'], sampleset.record.sample)] with mock.patch.dict(self.response._result, {'solutions': solutions_without_chain_breaks}): # validate data encoding self.verify_data_encoding(problem=self.problem, response=self.response, solver=self.solver, params=self.params, data=data, embedding_context=self.embedding_context)