def plot_chimera_embedding(em, C): plt.ion() plt.figure(figsize=(20, 20)) dnx.draw_chimera_embedding(C, em, with_labels=True, unused_color=(1.0, 1.0, 1.0, 1.0))
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 draw_chimera_embedding(self, output_path): """Save the chimera embedding to a file. Parameters ---------- output_path Specifies the path to the file where to save the embedding """ dnx.draw_chimera_embedding(dnx.chimera_graph(16, 16, 4), emb=self.embedding, node_size=3, width=.3) plt.savefig(output_path)
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 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")
def test_draw_chimera_embedding(self): C = dnx.chimera_graph(4) G = nx.grid_graph([2, 3, 2]) emb = {(0, 0, 0): [80, 48], (0, 0, 1): [50, 52], (0, 1, 0): [85, 93], (0, 1, 1): [84, 82], (0, 2, 0): [89], (0, 2, 1): [92], (1, 0, 0): [49, 54], (1, 0, 1): [83, 51], (1, 1, 0): [81], (1, 1, 1): [86, 94], (1, 2, 0): [87, 95], (1, 2, 1): [91]} dnx.draw_chimera_embedding(C, emb) dnx.draw_chimera_embedding(C, emb, embedded_graph=G) dnx.draw_chimera_embedding(C, emb, interaction_edges=C.edges())
for i in range(N): for j in range(i + 1, N): H += (x[i] - x[j]) ** 2 chainstrength = 5 numruns = 100 # Compile the model, and turn it into a QUBO object model = H.compile() Q, offset = model.to_qubo() bqm = dimod.BinaryQuadraticModel.from_qubo(Q, offset=offset) # Need to relabel variables for the first figure bqm2 = bqm.relabel_variables({curr: v for v, curr in enumerate(bqm.variables)}, inplace=False) # Do the embedding dwave_sampler = DWaveSampler() A = dwave_sampler.edgelist embedding = find_embedding(Q, A) # Draw the QUBO as a networkx graph G = bqm2.to_networkx_graph() pos = nx.spring_layout(G) nx.draw_networkx(G, pos=pos, font_size=10, node_size=150) plt.show() # Draw the embedded graph G = dnx.chimera_graph(16, 16, 4) dnx.draw_chimera_embedding(G, embedding, embedded_graph=bqm.to_networkx_graph(), unused_color=None) plt.show()
# 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 sys import matplotlib.pyplot as plt import networkx as nx import dwave_networkx as dnx from minorminer.busclique import find_clique_embedding from dwave.system.samplers import DWaveSampler N = int(sys.argv[1]) G = nx.complete_graph(N) fig, axes = plt.subplots(nrows=1, ncols=2, figsize=(10, 6)) # Draw the QUBO as a networkx graph pos = nx.spring_layout(G) nx.draw_networkx(G, pos=pos, font_size=10, node_size=100, node_color='cyan', ax=axes[0]) # Draw the embedded graph dwave_sampler = DWaveSampler(solver={'topology__type__eq': 'chimera'}) A = dwave_sampler.edgelist chimera_graph = dnx.chimera_graph(16, edge_list=A) clique_embedding = find_clique_embedding(N, chimera_graph) dnx.draw_chimera_embedding(chimera_graph, clique_embedding, embedded_graph=G, unused_color=None, ax=axes[1]) plt.savefig('clique_embedding_chimera')
def test_draw_overlapped_chimera_embedding(self): C = dnx.chimera_graph(2) emb = {0: [1, 5], 1: [5, 9, 13], 2: [25, 29], 3: [17, 21]} dnx.draw_chimera_embedding(C, emb, overlapped_embedding=True) dnx.draw_chimera_embedding(C, emb, overlapped_embedding=True, show_labels=True)
anti_mill_constant = 2 H = nx.Graph() H.add_nodes_from(np.arange(num_spots)) H.add_edges_from([(0, 1), (1, 2), (3, 4), (4, 5), (6, 7), (7, 8), (9, 10), (10, 11), (12, 13), (13, 14), (15, 16), (16, 17), (18, 19), (19, 20), (21, 22), (22, 23), (0, 9), (9, 21), (3, 10), (10, 18), (6, 11), (11, 15), (1, 4), (4, 7), (16, 19), (19, 22), (8, 12), (12, 17), (5, 13), (13, 20), (2, 14), (14, 23)]) #pos=dnx.chimera_layout(H) plt.ion() connectivity_structure = dnx.chimera_graph(3, 3) embeded_graph = minorminer.find_embedding(H.edges(), connectivity_structure.edges()) dnx.draw_chimera_embedding(connectivity_structure, embeded_graph) #dnx.draw_chimera(G) #dnx.draw_chimera(H, node_color='b', node_shape='*', style='dashed', edge_color='b', width=3) plt.savefig('plot.png', dpi=200) plt.close() nx.draw_networkx(H, with_labels=False) plt.savefig('nx_plot.png', dpi=200) sys.exit() b = Board() # FOR BOARD MARKERS: # OURS IS 1 # ENEMY IS 2 # FREE IS 0 stopped = False while not stopped:
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 chimera_graph = dnx.chimera_graph(16, 16, 4) dnx.draw_chimera_embedding(chimera_graph, embedding, embedded_graph=G, chain_color=chain_color_list, unused_color=None, ax=axes[1]) plt.savefig('embedding_clique_chimera')
# limitations under the License. import minorminer import networkx as nx import dwave_networkx as dnx import matplotlib.pyplot as plt K3 = nx.Graph([('A', 'B'), ('B', 'C'), ('C', 'A')]) plt.subplot(2, 2, 1) nx.draw(K3, with_labels=True) C = dnx.chimera_graph(1, 2, coordinates=False) plt.subplot(2, 2, 2) dnx.draw_chimera(C, with_labels=True) # Example with one blob for one node. Source node will use at least one. blob = [4, 5, 12, 13] suspend_chains = {'A': [blob]} embedding = minorminer.find_embedding(K3, C, suspend_chains=suspend_chains) plt.subplot(2, 2, 3) dnx.draw_chimera_embedding(C, embedding, with_labels=True) # Example with one blob for one node, and two blobs for another. # Second source node is forced to use at least one in each blob. blob_A0 = [4, 5] blob_A1 = [12, 13] blob_C0 = [6, 7, 14, 15] suspend_chains = {'A': [blob_A0, blob_A1], 'C': [blob_C0]} embedding = minorminer.find_embedding(K3, C, suspend_chains=suspend_chains) plt.subplot(2, 2, 4) dnx.draw_chimera_embedding(C, embedding, show_labels=True)
pos=pos, font_size=10, 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) embedding_chimera = find_embedding(B, chimera_graph) # Draw the graph embedded on Chimera dnx.draw_chimera_embedding(chimera_graph, embedding_chimera, embedded_graph=B, 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) embedding_pegasus = find_embedding(B, pegasus_graph) # Draw the graph embedded on Pegasus dnx.draw_pegasus_embedding(pegasus_graph, embedding_pegasus, embedded_graph=B, unused_color=None, ax=axes[2])
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
def draw_chimera_graph(embedding): plt.ion() G = dnx.chimera_graph(16,16,4) dnx.draw_chimera_embedding(G, embedding, show_labels=True) plt.show()
#prepare tile graph chimera_size = 16 tile_graph, choices = chimeratiles(chimera_size, chimera_size) #initialize and run heuristic heuristic = ParallelPlacementHeuristic(constraints, tile_graph, choices) pool = Pool() success = heuristic.par_run(pool, stop_first=True) #success = heuristic.run(stop_first=False) #print results if success: print("Success") # constraint_placement is a map from constraint to tile for c, t in heuristic.constraint_placement.items(): print(c.tile, t) print("Expanding chains") # heuristic.chains maps from variable to tile, expand to a map variable->qubit chains = expand_solution(tile_graph, heuristic.chains, dwnx.chimera_graph(chimera_size)) print_repr(chains)) from matplotlib import pyplot as plt dwnx.draw_chimera_embedding(dwnx.chimera_graph(chimera_size), chains, node_size=50) plt.savefig('result.png') else: print("Failure")