def double_plot(S, T, emb, filename, params): fig = plt.figure(figsize=(40, 20)) axes = fig.subplots(nrows=1, ncols=2) n = len(S) colors = {v: color(i, n) for i, v in enumerate(S)} node_colors = list(colors[v] for v in S) if params[0].get('pos') is None: params[0]['pos'] = nx.kamada_kawai_layout(S) nx.draw(S, node_color=node_colors, ax=axes[0], **params[0]) dnx.draw_pegasus_embedding(T, emb, S, crosses=True, chain_color=colors, ax=axes[1], **params[1]) fig.tight_layout() plt.savefig(filename) plt.close()
def test_draw_overlapped_chimera_embedding(self): C = dnx.pegasus_graph(2) emb = {0: [12, 35], 1: [12, 31], 2: [32], 3: [14]} dnx.draw_pegasus_embedding(C, emb, overlapped_embedding=True) dnx.draw_pegasus_embedding(C, emb, overlapped_embedding=True, show_labels=True)
def printQubitGraph(): #name = str(numOfClusters) + "V" + str(len(trackList)) + "T_" + computer plt.figure(figsize=(40, 40)) dnx.draw_pegasus_embedding(hardware_graph, emb=embedding, node_size=100, width=2, unused_color=(0, 0, 0, .25)) plt.savefig(embedding_filename + ".png") plt.close()
def draw_pegasus_embedding(self, output_path): """Save the pegasus embedding to a file. Parameters ---------- output_path Specifies the path to the file where to save the embedding """ dnx.draw_pegasus_embedding(dnx.pegasus_graph(11), emb=self.embedding, node_size=3, width=.3) plt.savefig(output_path)
def test_draw_pegasus_embedding(self): P = dnx.pegasus_graph(2) G = nx.grid_graph([3, 3, 2]) emb = { (0, 0, 0): [35], (0, 0, 1): [12], (0, 0, 2): [31], (0, 1, 0): [16], (0, 1, 1): [36], (0, 1, 2): [11], (0, 2, 0): [39], (0, 2, 1): [6], (0, 2, 2): [41], (1, 0, 0): [34], (1, 0, 1): [13], (1, 0, 2): [30], (1, 1, 0): [17], (1, 1, 1): [37], (1, 1, 2): [10], (1, 2, 0): [38], (1, 2, 1): [7], (1, 2, 2): [40] } dnx.draw_pegasus_embedding(P, emb) dnx.draw_pegasus_embedding(P, emb, embedded_graph=G) dnx.draw_pegasus_embedding(P, emb, interaction_edges=P.edges()) dnx.draw_pegasus_embedding(P, emb, crosses=True)
def draw_architecture_embedding(target_graph, *args, **kwargs): """ Draws an embedding onto the target graph G, according to G's family layout. """ family = target_graph.graph.get('family') if family == 'chimera': dnx.draw_chimera_embedding(target_graph, *args, **kwargs) elif family == 'pegasus': dnx.draw_pegasus_embedding(target_graph, *args, **kwargs) else: layout = nx.spring_layout(target_graph) dnx.drawing.qubit_layout.draw_embedding(target_graph, layout, *args, **kwargs) warnings.warn( "Graph family not available. Using NetworkX spring layout")
qubits = 0 for chain in embedding.values(): qubits += len(chain) print("\nEmbedding for", N, "clique found using", qubits, "qubits.") fig, axes = plt.subplots(nrows=1, ncols=2, figsize=(10, 6)) node_color_list = [(random(), random(), random()) for i in range(N)] chain_color_list = {i: node_color_list[i] for i in range(N)} # Draw the QUBO as a networkx graph pos = nx.spring_layout(G) nx.draw_networkx(G, pos=pos, font_size=10, node_size=300, node_color=node_color_list, edge_color='gray', ax=axes[0]) # Draw the embedded graph pegasus_graph = dnx.pegasus_graph(16) dnx.draw_pegasus_embedding(pegasus_graph, embedding, embedded_graph=G, chain_color=chain_color_list, unused_color=None, ax=axes[1]) plt.savefig('embedding_clique_pegasus')
# Copyright 2020 D-Wave Systems Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # 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. from pegasus_graph import P16 from matplotlib import pyplot as plt import networkx as nx, dwave_networkx as dnx from minorminer import busclique clique_cache = busclique.busgraph_cache(P16) clique_embedding = clique_cache.largest_clique() K = nx.complete_graph(len(clique_embedding)) dnx.draw_pegasus_embedding(P16, clique_embedding, K)
# Copyright 2020 D-Wave Systems Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # 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. from pegasus_graph import P6 from matplotlib import pyplot as plt, colors as mpl_color import networkx as nx, dwave_networkx as dnx, minorminer nodes = 80 edge_probability = 0.1 G = nx.gnp_random_graph(nodes, edge_probability, seed=0) nx.draw(G) emb = minorminer.find_embedding(G, P6, random_seed=1) dnx.draw_pegasus_embedding(P6, emb, G)
node_size=100, node_color='cyan', ax=axes[0]) # Embed the graph on Chimera dwave_sampler_chimera = DWaveSampler(solver={'topology__type': 'chimera'}) chimera_edges = dwave_sampler_chimera.edgelist chimera_graph = dnx.chimera_graph(16, edge_list=chimera_edges) clique_embedding_chimera = find_clique_embedding(N, chimera_graph) # Draw the graph embedded on Chimera dnx.draw_chimera_embedding(chimera_graph, clique_embedding_chimera, embedded_graph=G, unused_color=None, ax=axes[1]) # Embed the graph on Pegasus dwave_sampler_pegasus = DWaveSampler(solver={'topology__type': 'pegasus'}) pegasus_edges = dwave_sampler_pegasus.edgelist pegasus_graph = dnx.pegasus_graph(16, edge_list=pegasus_edges) clique_embedding_pegasus = find_clique_embedding(N, pegasus_graph) # Draw the graph embedded on Pegasus dnx.draw_pegasus_embedding(pegasus_graph, clique_embedding_pegasus, embedded_graph=G, unused_color=None, ax=axes[2]) plt.savefig('clique_embedding')
def run_qca_minimal(E_k=1, qpu_arch='pegasus', use_classical=False, num_reads=10, show_inspector=False, plot_emb_path=None, h_array=[-1, 0], J_matrix=[[0, 1], [1, 0]]): ''' Minimal 1 Driver 2 Cell QCA Problem (introduced in the Leap slide deck). Params: E_k : kink energy in eV. qpu_arch : QPU architecture to use. Either 'pegasus' (that is the newer architecture) or 'chimera' (the old one). use_classical : set to True to use D-Wave's classical Ising solver such that you don't have to use up your D-Wave Leap minutes for testing. num_reads : count of samples to request from the D-Wave QPU or classical sampler. Don't use too high of a value on the QPU as that might use up your Leap minutes very quickly. show_inspector : set to True to show problem inspector in the end. plot_emb_path : supply a string path to plot the embedding ''' import matplotlib.pyplot as plt # general dwave dependencies import dwave import dwave.embedding import dwave.inspector from dwave.system import DWaveSampler, EmbeddingComposite from dwave.cloud import Client from dwave.cloud.exceptions import SolverNotFoundError import dimod from dimod.reference.samplers import ExactSolver from minorminer import find_embedding import neal # dependencies for plotting connectivity graph import networkx as nx import dwave_networkx as dnx # general math and Python dependencies import math import numpy as np import itertools # define self bias (h) and coupling strengths (J) h = -E_k * np.array(h_array) J = -E_k * np.array(J_matrix) N = len(h) # create edgelist (note that {} initializes Python dicts) linear = {} # qubit self-bias quadratic = {} # inter-qubit bias for i in range(N): linear[i] = h[i] for j in range(i + 1, N): if J[i][j] != 0: quadratic[(i, j)] = J[i][j] # construct a bqm containing the provided self-biases (linear) and couplings # (quadratic). Specify the problem as SPIN (Ising). print('Constructing BQM...') bqm = dimod.BinaryQuadraticModel(linear, quadratic, 0, dimod.SPIN) # get DWave sampler and target mapping edgelist print('Choosing solver...') client = Client.from_config() solver = None try: if qpu_arch == 'pegasus': solver = client.get_solver('Advantage_system1.1').id elif qpu_arch == 'chimera': solver = client.get_solver('DW_2000Q_6').id else: raise ValueError('Specified QPU architecture is not supported.') except SolverNotFoundError: print(f'The pre-programmed D-Wave solver name for architecture ' '\'{qpu_arch}\' is not available. Find the latest available ' 'solvers by:\n' 'from dwave.cloud import Client\nclient = Client.from_config()\n' 'client.get_solvers()\nAnd update this script.') raise # get the specified QPU dwave_sampler = DWaveSampler(solver=solver) # run the problem sampler = None response = None if use_classical: print('Choosing classical sampler...') sampler = neal.SimulatedAnnealingSampler() else: print('Choosing D-Wave QPU as sampler...') sampler = EmbeddingComposite(dwave_sampler) response = sampler.sample(bqm, num_reads=num_reads) # print(response) print('Problem completed from selected sampler.') # plot the embedding if specified if not use_classical and plot_emb_path != None: print(f'Plotting embedding to {plot_emb_path}...') embedding = response.info['embedding_context']['embedding'] plt.figure(figsize=(16, 16)) T_nodelist, T_edgelist, T_adjacency = dwave_sampler.structure if qpu_arch == 'pegasus': G = dnx.pegasus_graph(16, node_list=T_nodelist) dnx.draw_pegasus_embedding(G, embedding, node_size=8, cmap='rainbow') elif qpu_arch == 'chimera': G = dnx.chimera_graph(16, node_list=T_nodelist) dnx.draw_chimera_embedding(G, embedding, node_size=8, cmap='rainbow') plt.savefig(plot_emb_path) # take first result from response use_result = [*response.first.sample.values()] # NOTE that response.record contains all returned results and some # statistics. You can inspect what's inside by using pdb or reading the # dimod.SampleSet documentation. # show dwave web inspector if specified if show_inspector and not use_classical: print('\nOpening problem inspector on your browser.') dwave.inspector.show(response) return response
emb, (layout_C, layout_P) = mml.find_embedding(C, P6, random_seed=1, return_layouts=True, threads=3) plt.figure(figsize=(20, 20)) nx.draw(C) plt.savefig("sparse_graph.png") plt.close() plt.figure(figsize=(20, 20)) dnx.draw_pegasus_embedding(P6, emb, C) plt.savefig("sparse_embedded.png") plt.close() # Draw a large P16 graph (this will take a while!) if False: n = 850 C = nx.random_regular_graph(3, n) emb, (layout_C, layout_P) = mml.find_embedding(C, P16, random_seed=2, return_layouts=True, layout=(None, None), threads=3,