def draw_tiling(sampler, t=4): """Draw Chimera graph of sampler with colored tiles. Args: sampler (:class:`dwave_micro_client_dimod.TilingComposite`): A tiled dimod sampler to be drawn. t (int): The size of the shore within each Chimera cell. Uses `dwave_networkx.draw_chimera` (see draw_chimera_). Linear biases are overloaded to color the graph according to which tile each Chimera cell belongs to. .. _draw_chimera: http://dwave-networkx.readthedocs.io/en/latest/reference/generated/dwave_networkx.drawing.chimera_layout.draw_chimera.html """ child = sampler.child nodes_per_cell = t * 2 m = n = int( ceil(sqrt(ceil(len(child.structure.nodelist) / nodes_per_cell)))) # assume square lattice shape system = dnx.chimera_graph(m, n, t, node_list=child.structure.nodelist, edge_list=child.structure.edgelist) labels = {node: -len(sampler.embeddings) for node in system.nodes} # unused cells are blue labels.update({ node: i for i, embedding in enumerate(sampler.embeddings) for s in embedding.values() for node in s }) dnx.draw_chimera(system, linear_biases=labels)
def plotBipartite(self, left=[], right=[]): G = dnx.chimera_graph( 1, 1, max(max([i for i, j in left]), max([i for i, j in right]))) dnx.draw_chimera(G, width=4.6, edge_color="purple", node_size=480) answer = [] labelDict = {} for i in range(len(left)): answer.append((0, 0, 0, i)) labelDict[(0, 0, 0, i)] = "{}".format(left[i][1]) for i in range(len(right)): answer.append((0, 0, 1, i)) labelDict[(0, 0, 1, i)] = "{}".format(right[i][1]) x = dnx.generators.chimera_graph(1, 1, max(max([i for i, j in left]), max([i for i, j in right])), node_list=answer, coordinates=True) dnx.draw_chimera(x, node_color="red", labels=labelDict, node_size=480, width=5, with_labels=True, edge_color="red", font_weight="bold", font_size="medium") plt.show()
def plotChimera(self, l, m, n, *, biPartite=None): assert (biPartite != None and len(biPartite) >= 2 ), "A bipartite graph w/ >= 2 nodes must be provided." if len(self.theGraph) == 0: raise emptyGraphException() H = nx.Graph() H.add_nodes_from([x for x, y in biPartite] + [y for x, y in biPartite]) H.add_edges_from(biPartite) # need to find correct dimensions # first need L and R sizes # assuming this bipartite set is the one provided in the args LSet, RSet, OCTSet = self.greedyBipartiteSets(getOCT=True) left, right, OCT = len(LSet), len(RSet), len(OCTSet) G = dnx.chimera_graph(l, m, n) dnx.draw_chimera(G, width=3, edge_color="purple") # abstracting built in exceptions try: dnx.draw_chimera(H, node_color='r', style='dashed', edge_color='r', width=3, with_labels=True, font_weight="bold") except: print("QEmbed Error: provided graph is not bi-partite. Exiting...") return plt.show()
def test_draw_pegasus_biases(self): G = dnx.chimera_graph(8) h = {v: v % 12 for v in G} J = {(u, v) if u % 2 else (v, u): (u + v) % 24 for u, v in G.edges()} for v in G: J[v, v] = .1 dnx.draw_chimera(G, linear_biases=h, quadratic_biases=J)
def draw_architecture(target_graph, **kwargs): """ Draws graph G according to G's family layout. """ family = target_graph.graph['family'] if family == 'chimera': dnx.draw_chimera(target_graph, **kwargs) elif family == 'pegasus': dnx.draw_pegasus(target_graph, **kwargs) else: nx.draw_spring(target_graph) warnings.warn( "Graph family not available. Using NetworkX spring layout")
def draw_tiling(sampler, t=4): """Draw Chimera graph of sampler with colored tiles. Args: sampler (:class:`dwave_micro_client_dimod.TilingComposite`): A tiled dimod sampler to be drawn. t (int): The size of the shore within each :std:doc:`Chimera <system:reference/intro>` cell. Uses :std:doc:`dwave_networkx.draw_chimera <networkx:index>`. Linear biases are overloaded to color the graph according to which tile each Chimera cell belongs to. See `Ocean Glossary <https://docs.ocean.dwavesys.com/en/latest/glossary.html>`_ for explanations of technical terms in descriptions of Ocean tools. """ child = sampler.child nodes_per_cell = t * 2 m = n = int( ceil(sqrt(ceil(len(child.structure.nodelist) / nodes_per_cell)))) # assume square lattice shape system = dnx.chimera_graph(m, n, t, node_list=child.structure.nodelist, edge_list=child.structure.edgelist) labels = {node: -len(sampler.embeddings) for node in system.nodes} # unused cells are blue labels.update({ node: i for i, embedding in enumerate(sampler.embeddings) for s in embedding.values() for node in s }) dnx.draw_chimera(system, linear_biases=labels)
def draw_chimera_bqm(bqm, width=None, height=None): """Draws a Chimera Graph representation of a Binary Quadratic Model. If cell width and height not provided assumes square cell dimensions. Throws an error if drawing onto a Chimera graph of the given dimensions fails. Args: bqm (:obj:`dimod.BinaryQuadraticModel`): Should be equivalent to a Chimera graph or a subgraph of a Chimera graph produced by dnx.chimera_graph. The nodes and edges should have integer variables as in the dnx.chimera_graph. width (int, optional): An integer representing the number of cells of the Chimera graph will be in width. height (int, optional): An integer representing the number of cells of the Chimera graph will be in height. Examples: >>> from dwave.embedding.drawing import draw_chimera_bqm >>> from dimod import BinaryQuadraticModel >>> Q={(0, 0): 2, (1, 1): 1, (2, 2): 0, (3, 3): -1, (4, 4): -2, (5, 5): -2, (6, 6): -2, (7, 7): -2, ... (0, 4): 2, (0, 4): -1, (1, 7): 1, (1, 5): 0, (2, 5): -2, (2, 6): -2, (3, 4): -2, (3, 7): -2} >>> draw_chimera_bqm(BinaryQuadraticModel.from_qubo(Q), width=1, height=1) """ linear = bqm.linear.keys() quadratic = bqm.quadratic.keys() if width is None and height is None: # Create a graph large enough to fit the input networkx graph. graph_size = ceil(sqrt((max(linear) + 1) / 8.0)) width = graph_size height = graph_size if not width or not height: raise Exception("Both dimensions must be defined, not just one.") # A background image of the same size is created to show the complete graph. G0 = chimera_graph(height, width, 4) G = chimera_graph(height, width, 4) # Check if input graph is chimera graph shaped, by making sure that no edges are invalid. # Invalid edges can also appear if the size of the chimera graph is incompatible with the input graph in cell dimensions. non_chimera_nodes = [] non_chimera_edges = [] for node in linear: if not node in G.nodes: non_chimera_nodes.append(node) for edge in quadratic: if not edge in G.edges: non_chimera_edges.append(edge) linear_set = set(linear) g_node_set = set(G.nodes) quadratic_set = set(map(frozenset, quadratic)) g_edge_set = set(map(frozenset, G.edges)) non_chimera_nodes = linear_set - g_node_set non_chimera_edges = quadratic_set - g_edge_set if non_chimera_nodes or non_chimera_edges: raise Exception("Input graph is not a chimera graph: Nodes: %s Edges: %s" % (non_chimera_nodes, non_chimera_edges)) # Get lists of nodes and edges to remove from the complete graph to turn the complete graph into your graph. remove_nodes = list(g_node_set - linear_set) remove_edges = list(g_edge_set - quadratic_set) # Remove the nodes and edges from the graph. for edge in remove_edges: G.remove_edge(*edge) for node in remove_nodes: G.remove_node(node) node_size = 100 # Draw the complete chimera graph as the background. draw_chimera(G0, node_size=node_size*0.5, node_color='black', edge_color='black') # Draw your graph over the complete graph to show the connectivity. draw_chimera(G, node_size=node_size, linear_biases=bqm.linear, quadratic_biases=bqm.quadratic, width=3) return
# Copyright 2018 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. # # ================================================================================================ import matplotlib.pyplot as plt import dwave_networkx as dnx import networkx as nx G = dnx.chimera_graph(2, 2, 4) dnx.draw_chimera(G) plt.show()
def plotChimeraFromBipartite(self, showMappings=False, L=2, M=2, N=2, *, left=[], right=[], isBipartite=False): assert (left != None and right != None), "Must provide non-empty left and right sets." assert (L >= 1 and M >= 1 and N >= 1), "Chimera L,M,N topologies must be at least 1." if (left == [] or right == []): print("Warning: empty left or right sets.") answer = [] labelDict = {} if isBipartite == True: for i in range(len(left)): answer.append((0, 0, 0, i)) labelDict[(0, 0, 0, i)] = "v{}".format(left[i][1]) for i in range(len(right)): answer.append((0, 0, 1, i)) labelDict[(0, 0, 1, i)] = "h{}".format(left[i][1]) # Mapping bipartite sets. First left set else: for i, end in left: for j in range(1, L + 1): t = (j, math.ceil((i) / N), 1, ((i) % N)) if ((i) % N) > 0 else (j, math.ceil( (i) / N), 1, N) answer.append(tuple(k - 1 for k in t)) if (showMappings == True): print("Mapping v{} to {}.".format( end, tuple(k - 1 for k in t))) labelDict[tuple(k - 1 for k in t)] = "h{}".format(end) for i, end in right: for j in range(1, M + 1): t = (math.ceil((i) / N), j, 2, ((i) % N)) if ((i) % N) > 0 else (math.ceil( (i) / N), j, 2, N) answer.append(tuple(k - 1 for k in t)) if (showMappings == True): print("Mapping h{} to {}.".format( end, tuple(k - 1 for k in t))) labelDict[tuple(k - 1 for k in t)] = "v{}".format(end) G = dnx.chimera_graph(L, M, N) dnx.draw_chimera(G, width=4.6, edge_color="purple", node_size=480) x = dnx.generators.chimera_graph(L, M, N, node_list=answer, coordinates=True) dnx.draw_chimera(x, node_color="red", labels=labelDict, node_size=480, width=5, with_labels=True, edge_color="red", font_weight="bold", font_size="medium") plt.show()
# 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 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)
# Look at a minor embedding problem. It's still NP-hard # Usually need probablistic heuristics to find an embedding # D-Wave has unit cells containing K4,4 bipartite fully connected graph # with two remote connections from each qubit going to qubits in neighbouring unit cells. A unit # cell is with its local and remote connections including indicated # Chimera graph, largest hardware has 2048 qubits consisting of 16 by 16 unit cells of 8 qubits # Chimera graph is available as a networkx graph in the package dwave_networkx # draw a smaller one of 2 by 2 cells import matplotlib.pyplot as plt import dwave_networkx as dnx connectivity_structure = dnx.chimera_graph(2, 2) dnx.draw_chimera(connectivity_structure) plt.show() # Now create a graph that does not fit the connectivity structure. The complete Kn on nine nodes import networkx as nx G = nx.complete_graph(9) plt.axis('off') nx.draw_networkx(G, with_labels=False) import minorminer embedded_graph = minorminer.find_embedding(G.edges(), connectivity_structure.edges()) dnx.draw_chimera_embedding(connectivity_structure, embedded_graph) plt.show()
classical_sampler = neal.SimulatedAnnealingSampler() sampler = dimod.StructureComposite(classical_sampler, P6.nodes, P6.edges) # %% # Working With Embeddings # 全結合の40ノードを作りたい num_variables = 40 embedding = dwave.embedding.chimera.find_clique_embedding(num_variables, 16) max(len(chain) for chain in embedding.values()) # チェーン数は11 # %% # 680 node Pegasus num_variables = 40 embedding = dwave.embedding.pegasus.find_clique_embedding(num_variables, 6) max(len(chain) for chain in embedding.values()) # チェーン数は6 # %% # https://qiita.com/YuichiroMinato/items/dbc142ecb1efbebd6adf chimera = dnx.chimera_graph(2, 2, 4) dnx.draw_chimera(chimera) plt.show() # %% P3 = dnx.pegasus_graph(2) dnx.draw_pegasus(P3) plt.show() # %%