def solve_ising_dwave(hii, Jij): config_file = '/media/sf_QWorld/QWorld/QA_DeNovoAsb/dwcloud.conf' client = Client.from_config(config_file, profile='aritra') solver = client.get_solver( ) # Available QPUs: DW_2000Q_2_1 (2038 qubits), DW_2000Q_5 (2030 qubits) dwsampler = DWaveSampler(config_file=config_file) edgelist = solver.edges adjdict = edgelist_to_adjacency(edgelist) embed = minorminer.find_embedding(Jij.keys(), edgelist) [h_qpu, j_qpu] = embed_ising(hii, Jij, embed, adjdict) response_qpt = dwsampler.sample_ising(h_qpu, j_qpu, num_reads=solver.max_num_reads()) client.close() bqm = dimod.BinaryQuadraticModel.from_ising(hii, Jij) unembedded = unembed_sampleset(response_qpt, embed, bqm, chain_break_method=majority_vote) print("Maximum Sampled Configurations from D-Wave\t===>") solnsMaxSample = sorted(unembedded.record, key=lambda x: -x[2]) for i in range(0, 10): print(solnsMaxSample[i]) print("Minimum Energy Configurations from D-Wave\t===>") solnsMinEnergy = sorted(unembedded.record, key=lambda x: +x[1]) for i in range(0, 10): print(solnsMinEnergy[i])
def solve_qubo_dwave(Q, num_reads=1000): # Create the solver (connecting to D-Wave) and the Sampler config_file = '../dwave.conf' client = Client.from_config(config_file, profile='ocete') solver = client.get_solver( ) # Available QPUs: DW_2000Q_2_1 (2038 qubits), DW_2000Q_5 (2030 qubits) dwsampler = DWaveSampler(config_file=config_file) # We need to embed Q into a valid graph for the D-Wave architecture edgelist = solver.edges adjdict = edgelist_to_adjacency(edgelist) embed = minorminer.find_embedding(Q, edgelist) Q_embeded = embed_qubo(Q, embed, adjdict) # Obtain the response from the solver. This is the actual D-Wave execution! start = time.time() response_qpt = dwsampler.sample_qubo(Q_embeded, num_reads=num_reads) qpu_time = time.time() - start client.close() # Transform the response from the embeded graph to our original architecture bqm = dimod.BinaryQuadraticModel.from_qubo(Q) unembedded = unembed_sampleset(response_qpt, embed, bqm, chain_break_method=majority_vote) # Order the solutions by lower energy return unembedded, qpu_time
def try_embedding(n_reads, solver, print_embedding=True): start_total = time.time() # Create test start_test = time.time() _, reads = create_test(num_reads=n_reads) test_creation_time = time.time() - start_test # Prepare the data tspAdjM = reads_to_tspAdjM(reads) quboAdjM = tspAdjM_to_quboAdjM(tspAdjM, -1.6, 1.6, 1.6) Q = quboAdjM_to_quboDict(quboAdjM) # Try to embed Q into a valid graph for the pegasus topology start_embedding = time.time() edgelist = solver.edges adjdict = edgelist_to_adjacency(edgelist) embed = minorminer.find_embedding(Q, edgelist) Q_embeded = embed_qubo(Q, embed, adjdict) embedding_time = time.time() - start_embedding total_time = time.time() - start_total print('Successful: {} reads, {} nodes graph, {:.6f}s test creation time, {:.6f}s embedding time, {:.6f}s total time'.format( len(reads), len(reads)*len(reads), test_creation_time, embedding_time, total_time))
def get_embedding(): embedding = [] if path.exists(f'_data/embedding/{embedding_kind}_{U}_{Grids}_{Slack}.json' ) == False: print(f"Finding {embedding_kind} Embedding") if embedding_kind == "regular": embedding = find_embedding( nx.complete_graph(scope).edges(), sampler.edgelist) elif embedding_kind == "clique": embedding = find_clique_embedding( scope, target_graph=sampler.to_networkx_graph()) #print(embedding) with open(f'_data/embedding/{embedding_kind}_{U}_{Grids}_{Slack}.json', "w") as ff: json.dump(embedding, ff) else: print(f"Importing saved {embedding_kind} Embedding") f = open(f'_data/embedding/{embedding_kind}_{U}_{Grids}_{Slack}.json') embedding = json.load(f) #dnx.draw_pegasus_embedding(sampler.to_networkx_graph(), embedding, unused_color=None) #plt.savefig(f'images/embedding_{embedding_type}N{N}q{q:.2f}B{B}P{P:.3f}.png') return embedding
def get_embedding_with_short_chain(J: dict, tries: int = 5, processor: list = None, verbose=False) -> dict: '''Try a few probabilistic embeddings and return the one with the shortest chain length :param J: Couplings :param tries: Number of probabilistic embeddings :param verbose: Whether to print out diagnostic information :return: Returns the minor embedding ''' if processor is None: # The hardware topology: 16 by 16 pieces of K_4,4 unit cells processor = dnx.chimera_graph(16, 16, 4).edges() # Try a few embeddings best_chain_length = sys.maxsize source = list(J.keys()) for _ in range(tries): try: emb = minorminer.find_embedding(source, processor) #chain_length = max_chain_length(emb) chain_length = max(len(chain) for chain in emb.values()) if chain_length > 0 and chain_length < best_chain_length: embedding = emb best_chain_length = chain_length except ValueError: pass if verbose: print(best_chain_length, max_chain_length(embedding)) if best_chain_length == sys.maxsize: raise Exception("Cannot find embedding") return embedding
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 sample_qubo(self, Q, num_samps=100): """ Sample from the QUBO problem :param qubo: QUBO problem :type qubo: numpy dictionary :return: samples, energy, num_occurrences """ self.num_samps = num_samps if not hasattr(self, 'sampler'): bqm = BinaryQuadraticModel.from_qubo(Q) # apply the embedding to the given problem to map it to the child sampler __, target_edgelist, target_adjacency = self.child.structure # add self-loops to edgelist to handle singleton variables source_edgelist = list(bqm.quadratic) + [(v, v) for v in bqm.linear] # get the embedding embedding = minorminer.find_embedding(source_edgelist, target_edgelist) if bqm and not embedding: raise ValueError("no embedding found") self.sampler = FixedEmbeddingComposite(self.child, embedding) response = self.sampler.sample_qubo(Q, chain_strength=self.chainstrength, num_reads=self.num_samps) return np.array(response.__dict__['_samples_matrix'].tolist()), response.__dict__['_data_vectors']["energy"], \ response.__dict__['_data_vectors']["num_occurrences"]
def retry_embedding( sampler, qubo_dict, qpu_graph, graph_tag, target_min=-0.1, target_range=0.12, n_tries=100, ): def get_embed_min_max_offset(sampler, embedding): embed = FixedEmbeddingComposite(sampler, embedding) embedding_idx = [ idx for embed_list in embedding.values() for idx in embed_list ] anneal_offset_ranges = np.array( embed.properties["child_properties"]["anneal_offset_ranges"]) min_offset = max( [offsets[0] for offsets in anneal_offset_ranges[embedding_idx]]) max_offset = min( [offsets[1] for offsets in anneal_offset_ranges[embedding_idx]]) return embed, min_offset, max_offset try: with open( f"../qlp/mds/embeddings/{graph_tag}_{target_min}_{target_range}_v6.yaml", "r") as file: embedding = yaml.safe_load(file) embed, min_offset, max_offset = get_embed_min_max_offset( sampler, embedding) embedding_set = {k: set(embedding[k]) for k in embedding} return embed, embedding, min_offset, max_offset except Exception as e: print(e) pass for i in range(n_tries): try: embedding = find_embedding(qubo_dict, qpu_graph) embed, min_offset, max_offset = get_embed_min_max_offset( sampler, embedding) if (target_range > max_offset - target_min) or (min_offset > target_min): raise ValueError( f"\n{target_range} > {max_offset - target_min}: Not enough offset range for inhomogeneous driving." f"\n{min_offset} > {target_min}: min_offset needs to be lower." "Try another embedding.") else: with open( f"../qlp/mds/embeddings/{graph_tag}_{target_min}_{target_range}_v6.yaml", "w", ) as file: safe_embed = { int(k): list(embedding[k]) for k in embedding } yaml.safe_dump(safe_embed, file) return embed, embedding, min_offset, max_offset except Exception as e: # print(e) continue
def sample(self, bqm, chain_strength=1.0, chain_break_fraction=True, **parameters): """Sample the binary quadratic model. Note: At the initial sample(..) call, it will find a suitable embedding and initialize the remaining attributes before sampling the bqm. All following sample(..) calls will reuse that initial embedding. Args: bqm (:obj:`dimod.BinaryQuadraticModel`): Binary quadratic model to be sampled from. chain_strength (float, optional, default=1.0): Magnitude of the quadratic bias (in SPIN-space) applied between variables to create chains. Note that the energy penalty of chain breaks is 2 * `chain_strength`. chain_break_fraction (bool, optional, default=True): If True, a ‘chain_break_fraction’ field is added to the unembedded response which report what fraction of the chains were broken before unembedding. **parameters: Parameters for the sampling method, specified by the child sampler. Returns: :class:`dimod.SampleSet` """ if self.embedding is None: # Find embedding child = self.child # Solve the problem on the child system __, target_edgelist, target_adjacency = child.structure source_edgelist = list(bqm.quadratic) + [(v, v) for v in bqm.linear] # Add self-loops for single variables embedding = minorminer.find_embedding(source_edgelist, target_edgelist) # Initialize properties that need embedding super(LazyFixedEmbeddingComposite, self)._set_graph_related_init(embedding=embedding) return super(LazyFixedEmbeddingComposite, self).sample(bqm, chain_strength=chain_strength, chain_break_fraction=chain_break_fraction, **parameters)
def setUp(self): # Temporary DataBase self.db = EmberaDataBase("./TMP_DB") # Toy Problem self.bqm = dimod.BinaryQuadraticModel({ 'a': 2, 'A1.S': 2, '(0,1)': 2 }, { ('a', 'A1.S'): -1, ('A1.S', '(0,1)'): -1, ('(0,1)', 'a'): -1 }, 0.0, dimod.Vartype.SPIN) self.source_edgelist = [('a', 'A1.S'), ('A1.S', '(0,1)'), ('(0,1)', 'a')] self.target_edgelist = [(1, 2), (2, 3), (3, 4), (4, 1)] # Toy Entries self.embedding = minorminer.find_embedding(self.source_edgelist, self.target_edgelist) self.sampleset = dimod.SampleSet.from_samples([{ 1: -1, 2: 1, 3: -1, 4: -1 }, { 1: -1, 2: 1, 3: 1, 4: 1 }], 'SPIN', 0) self.report = {'emb1': {'a': 4, 'A1.S': 8, '(0,1)': 12}}
def _find_embedding(self, edges, adj, **kwargs): "Wrap minorminer.find_embedding with a version that intercepts its output." # Minorminer accepts the hardware adjacency as a list of # pairs, not a map from each node to its neighbors. mm_adj = [(u, v) for u in adj for v in adj[u]] # Given verbose=0, invoke minorminer directly. if "verbose" not in kwargs or kwargs["verbose"] == 0: # Convert all keys to integers for consistency. embedding = minorminer.find_embedding(edges, mm_adj, **kwargs) return {int(k): v for k, v in embedding.items()} # minorminer's find_embedding is hard-wired to write to stdout. # Trick it into writing into a pipe instead. sepLine = "=== EMBEDDING ===\n" r, w = os.pipe() pid = os.fork() if pid == 0: # Child -- perform the embedding. os.close(r) os.dup2(w, sys.stdout.fileno()) embedding = minorminer.find_embedding(edges, mm_adj, **kwargs) sys.stdout.flush() os.write(w, sepLine.encode()) os.write(w, (json.dumps(embedding) + "\n").encode()) os.close(w) os._exit(0) else: # Parent -- report the embedding's progress. os.close(w) pipe = os.fdopen(r, "r", 10000) while True: try: rstr = pipe.readline() if rstr == sepLine: break if rstr == "": self.qmasm.abend( "Embedder failed to terminate properly") sys.stderr.write(" %s" % rstr) except: pass # Receive the embedding from the child. Convert all keys to # integers for consistency. embedding = json.loads(pipe.readline()) return {int(k): v for k, v in embedding.items()}
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 test_simple(self): sampler = DWaveSampler(solver={'qpu': True}) embedding = minorminer.find_embedding([[0, 1], [1, 2], [0, 2]], sampler.edgelist) fbo1 = self.step1(sampler, embedding) fbo2 = self.step2(sampler, embedding) self.assertEqual(fbo1, fbo2)
def sample_ising(self, h, J, **parameters): """Sample from the provided unstructured Ising model. Args: h (list/dict): Linear terms of the model. J (dict of (int, int):float): Quadratic terms of the model. **parameters: Parameters for the sampling method, specified by the child sampler. Returns: :class:`dimod.Response` """ if isinstance(h, list): h = dict(enumerate(h)) # solve the problem on the child system child = self.child # apply the embedding to the given problem to map it to the child sampler __, target_edgelist, target_adjacency = child.structure # get the embedding embedding = minorminer.find_embedding(J, target_edgelist) if J and not embedding: raise ValueError("no embedding found") # this should change in later versions if isinstance(embedding, list): embedding = dict(enumerate(embedding)) h_emb, J_emb, J_chain = embutil.embed_ising(h, J, embedding, target_adjacency) J_emb.update(J_chain) response = child.sample_ising(h_emb, J_emb, **parameters) # unembed the problem and save to a new response object samples = embutil.unembed_samples( response, embedding, chain_break_method=embutil.minimize_energy, linear=h, quadratic=J) # needed by minimize_energy # source_response = dimod.Response(dimod.SPIN) data_vectors = response.data_vectors data_vectors['energy'] = [ dimod.ising_energy(sample, h, J) for sample in samples ] return dimod.Response.from_dicts(samples, data_vectors, info=response.info, vartype=dimod.SPIN)
def test_comparison(self): emb1 = self.embedding emb1_obj = Embedding(emb1) emb2 = minorminer.find_embedding(self.source_edgelist, self.target_edgelist) emb2_obj = Embedding(emb2) self.assertEqual(emb2_obj == emb1_obj, not emb1_obj != emb2_obj) self.assertFalse(emb2_obj > emb1_obj) self.assertFalse(emb2_obj < emb1_obj) self.assertTrue(emb2_obj >= emb1_obj) self.assertTrue(emb2_obj <= emb1_obj)
def find_embedding(self, Q): i = 0 max = 10 while None == self.embedding and i < max: i += 1 try: self.embedding = minorminer.find_embedding( Q, self.base_sampler.edgelist) except Exception as a: if i == max - 1: raise Exception( "No embedding found after {} tries.".format(max))
def reconnect(S, T, embedding, return_overlap=False): """ Perform a short run of minorminer to find a valid embedding """ # Assign current embedding to suspend_chains to preserve the layout suspend_chains = { k: [[q] for q in chain if q in T] for k, chain in embedding.items() } # Run minorminer as a short run without chainlength optimization miner_params = { 'suspend_chains': suspend_chains, 'return_overlap': return_overlap } return minorminer.find_embedding(S, T, **miner_params)
def embed_qubo_pegasus(Q_matrix, plotIt = False): connectivity_structure = dnx.pegasus_graph(15) # try to minimize G = nx.from_numpy_matrix(Q_matrix) max_chain_length = 0 while(max_chain_length == 0): embedded_graph = minorminer.find_embedding(G.edges(), connectivity_structure) for _, chain in embedded_graph.items(): if len(chain) > max_chain_length: max_chain_length = len(chain) print("max_chain_length", max_chain_length) # try to minimize if plotIt: dnx.draw_chimera_embedding(connectivity_structure, embedded_graph) plt.show()
def solve_qubo_dwave(Q, n_genome_reads, num_reads=100, label='', annealing_time=20): # Create the solver (connecting to D-Wave) and the Sampler config_file = '../dwave_adv.conf' client = Client.from_config(config_file, profile='ocete') solver = client.get_solver('Advantage_system1.1') dwsampler = DWaveSampler( solver={ 'qpu': True, 'topology__type': 'pegasus', 'annealing_time': annealing_time }, # Watch out, Leap doesn seem to take into account # this parameter, you have to give it as a paramater in the dwsampler.sample() call token=token, endpoint=endpoint) # We need to embed Q into a valid graph for the D-Wave architecture adjdict = edgelist_to_adjacency(solver.edges) embed = minorminer.find_embedding(Q, solver.edges) Q_embeded = embed_qubo(Q, embed, adjdict) # Obtain the response from the solver. This is the actual D-Wave execution! start = time.time() response_qpt = dwsampler.sample_qubo(Q_embeded, num_reads=num_reads, label=label, annealing_time=annealing_time) qpu_time = time.time() - start client.close() # Transform the response from the embeded graph to our original architecture bqm = dimod.BinaryQuadraticModel.from_qubo(Q) unembedded = unembed_sampleset(response_qpt, embed, bqm, chain_break_method=majority_vote) # Sort the solutions from lowest energy and format them to quboDict format unformated_solutions_list = sorted(unembedded.record, key=lambda x: +x[1]) solutions_list = [] for sol, energy, num_appereances in unformated_solutions_list: solutions_list.append([ rebuild_quboDict_from_vector(sol, n_genome_reads), energy, num_appereances ]) return solutions_list, qpu_time, get_max_chain_length(embed)
def mutate(self, ga, chromosome): """ Args: chromosome: target chromosome Returns: Mutated Genes """ genes = chromosome.genes.copy() embedding = find_embedding(ga._graph.edges, ga._target_graph.edges) mutated_genes = [(key, value[0]) for key, value in embedding.items()] if ga._fitness(mutated_genes) > chromosome.fitness: return mutated_genes return chromosome.genes
def embed_graph(self): """ Separate function as graph embedding can be reused so long as self.dim, self.k remain constant Embed graph maps the fully connected Ising model we have defined to the D-Wave Chimera topology """ source_edgelist = [(i, j) for i in range(int(self.nqubits)) for j in range(i, int(self.nqubits))] dws = DWaveSampler(qpu=True) # instantiate DWaveSampler dws_structure = dimod.child_structure_dfs(dws) target_edgelist = dws_structure.edgelist self.embedding = mm.find_embedding(source_edgelist, target_edgelist) physical_qubits = [] for qubit_list in self.embedding.values( ): # this loop just puts all the physical qubit indices into one list physical_qubits += qubit_list print("Number of physical qubits: ", len(physical_qubits))
def _init_chromosomes(self, max_chromosome_size, initial_gene_size): """ Initial chromosomes Args: max_chromosome_size: max size of genes can be loaded into chromosome initial_gene_size: size of chromosomes Returns: Generated chromosomes """ chromosomes = [] for i in range(max_chromosome_size): embedding = find_embedding(self._graph.edges, self._target_graph.edges) genes = [(key, value[0]) for key, value in embedding.items()] chromosomes.append(Chromosome(genes)) return chromosomes
def get_embedding(qubo_dict): # graph = dnx.chimera_graph(16, 16, 4) edges_array = np.genfromtxt("Dwave_2000Q_edges.csv", delimiter=',') edges = [] for item in edges_array: edges.append((item[0], item[1])) try: embedding = find_embedding(qubo_dict, edges) except Exception as e: print(e) return [np.nan, np.nan, np.nan] if len(embedding) == 0: return [np.nan, np.nan, np.nan] return embedding
def setUp(self): self.source_edgelist = [('a', 'A1.S'), ('A1.S', (0, 1)), ((0, 1), 'a')] self.target_edgelist = [(1, 2), (2, 3), (3, 4), (4, 1)] self.embedding = minorminer.find_embedding(self.source_edgelist, self.target_edgelist) self.sampleset = dimod.SampleSet.from_samples([{ 1: -1, 2: 1, 3: -1, 4: -1 }, { 1: -1, 2: 1, 3: 1, 4: 1 }], 'SPIN', 0)
def test_construction(self): child_sampler = DWaveSampler() # get an embedding K10_edges = list(itertools.combinations(range(10), 2)) embedding = minorminer.find_embedding(K10_edges, child_sampler.edgelist) sampler = VirtualGraphComposite(child_sampler, embedding) dtest.assert_sampler_api(sampler) h = {} J = {edge: -1 for edge in K10_edges} sampler.sample_ising(h, J) sampler.sample_ising(h, J, apply_flux_bias_offsets=False)
def embed_qubo_chimera(Q_matrix, plt_show = True, filename=''): connectivity_structure = dnx.chimera_graph(3,3) # try to minimize G = nx.from_numpy_matrix(Q_matrix) max_chain_length = 0 while(max_chain_length == 0): embedded_graph = minorminer.find_embedding(G.edges(), connectivity_structure) for _, chain in embedded_graph.items(): if len(chain) > max_chain_length: max_chain_length = len(chain) # print("max_chain_length",max_chain_length) # try to minimize dnx.draw_chimera_embedding(connectivity_structure, embedded_graph) if plt_show: plt.show() if filename != '': plt.savefig('../../thesis/figures/experiments/{}'.format(filename), bbox_inches='tight')
def find_embedding_minorminer(Q, A, num_tries=100, print_output_flag=False): best_embedding = None best_chain_len = np.inf step = int(np.ceil(num_tries / 10)) for i in range(num_tries): if print_output_flag and i % step == 0: print(f'try {i+1} / {num_tries}') e = minorminer.find_embedding(Q, A) if e: # to guarantee an embedding is produced chain_len = longest_chain_in_embed(e) if chain_len < best_chain_len: best_embedding = e best_chain_len = chain_len return best_embedding, best_chain_len
def sample_qubo(self, Q, num_samps=100): """ Sample from the QUBO problem :param qubo: QUBO problem :type qubo: numpy dictionary :return: samples, energy, num_occurrences """ #print(Q) self.num_samps = num_samps if not hasattr(self, 'sampler'): bqm = BinaryQuadraticModel.from_qubo(Q) # apply the embedding to the given problem to map it to the child sampler __, target_edgelist, target_adjacency = self.child.structure # add self-loops to edgelist to handle singleton variables source_edgelist = list(bqm.quadratic) + [(v, v) for v in bqm.linear] # get the embedding embedding = minorminer.find_embedding(source_edgelist, target_edgelist) if bqm and not embedding: raise ValueError("no embedding found") self.sampler = FixedEmbeddingComposite(self.child, embedding) response = EmbeddingComposite( DWaveSampler(token="DEV-db4d47e5313cf3c52cac31dace7c5080a5ffc46d") ).sample_qubo(Q, num_reads=1000) #response = self.sampler.sample_qubo(Q, chain_strength=self.chainstrength, num_reads=self.num_samps) #for sample, energy, num_occurrences, chain_break_fraction in list(response.data()): # print(sample, "Energy: ", energy, "Occurrences: ", num_occurrences) #print(response.samples()[0,[range(0,71)]]) #print(response._asdict()['vectors']['energy']) #print(response._asdict()['vectors']['num_occurrences']) saempeul = np.empty((0, 72)) for sample, in response.data(fields=['sample']): saempeul = np.append(saempeul, sample) #print(saempeul) return saempeul, response._asdict()['vectors']['energy']['data'], \ response._asdict()['vectors']['num_occurrences']['data']
def get_embedding_with_short_chain(S: dict, tries: int = 5, processor: list = None, verbose=True) -> dict: '''Try a few probabilistic embeddings and return the one with the shortest chain length :param S: Source couplings :param tries: Number of probabilistic embeddings :param verbose: Whether to print out diagnostic information :return: Returns the minor embedding ''' if processor is None: # The hardware topology: 16 by 16 pieces of K_4,4 unit cells processor = dnx.chimera_graph(16, 16, 4).edges() # Try a few embeddings embedding = None best_chain_length = sys.maxsize source = list(S.keys()) for itry in range(tries): # print(".", end=' ') try: emb = minorminer.find_embedding(source, processor, verbose=0) chain_length = max_chain_length(emb) if (chain_length > 0) and (chain_length < best_chain_length): embedding = emb best_chain_length = chain_length if verbose: print("DEBUG: found embedding at attempt", itry, "max length:", chain_length) except: pass if embedding == None: print("WARNING: could not find minor embedding") return embedding if verbose: max_length = max_chain_length(embedding) print("INFO: max chain length in best embedding:", max_length) print("INFO: best embedding:") print(embedding) if best_chain_length == sys.maxsize: raise Exception("Cannot find embedding") return embedding
def find_embedding(S, T, **kwargs): """Return an embedding for the edges S of the source and the edges T of the target. We use the function minorminer. :param S: an iterable of label pairs representing the edges in the source graph, or a NetworkX Graph :param T: an iterable of label pairs representing the edges in the target graph, or a NetworkX Graph :param kwargs: keyword arguments containing th random seed to be used in the embedding initialisation :return: an embedding """ t0 = time.time() embedding = minorminer.find_embedding(S, T, **kwargs) t1 = time.time() print(f"\nTime to get embedding: {t1-t0:.2f} s") return embedding