def test_directed(self): """Tests for creating a directed hexagonal lattice.""" G = nx.hexagonal_lattice_graph(3, 5, create_using=nx.Graph()) H = nx.hexagonal_lattice_graph(3, 5, create_using=nx.DiGraph()) assert_true(H.is_directed()) pos = nx.get_node_attributes(H, 'pos') for u, v in H.edges(): assert_true(pos[v][1] >= pos[u][1]) if pos[v][1] == pos[u][1]: assert_true(pos[v][0] > pos[u][0])
def test_directed(self): """Tests for creating a directed hexagonal lattice.""" G = nx.hexagonal_lattice_graph(3, 5, create_using=nx.Graph()) H = nx.hexagonal_lattice_graph(3, 5, create_using=nx.DiGraph()) assert H.is_directed() pos = nx.get_node_attributes(H, "pos") for u, v in H.edges(): assert pos[v][1] >= pos[u][1] if pos[v][1] == pos[u][1]: assert pos[v][0] > pos[u][0]
def test_periodic(self): G = nx.hexagonal_lattice_graph(4, 6, periodic=True) assert_equal(len(G), 48) assert_equal(G.size(), 72) # all degrees are 3 assert_equal(len([n for n, d in G.degree() if d != 3]), 0) G = nx.hexagonal_lattice_graph(5, 8, periodic=True) HLG = nx.hexagonal_lattice_graph assert_raises(nx.NetworkXError, HLG, 2, 7, periodic=True) assert_raises(nx.NetworkXError, HLG, 1, 4, periodic=True) assert_raises(nx.NetworkXError, HLG, 2, 1, periodic=True)
def test_periodic(self): G = nx.hexagonal_lattice_graph(4, 6, periodic=True) assert_equal(len(G), 48) assert_equal(G.size(), 72) # all degrees are 3 assert_equal(len([n for n, d in G.degree() if d != 3]), 0) G = nx.hexagonal_lattice_graph(5, 8, periodic=True) HLG = nx.hexagonal_lattice_graph assert_raises(nx.NetworkXError, HLG, 2, 7, periodic=True) assert_raises(nx.NetworkXError, HLG, 1, 4, periodic=True) assert_raises(nx.NetworkXError, HLG, 2, 1, periodic=True)
def test_periodic(self): G = nx.hexagonal_lattice_graph(4, 6, periodic=True) assert len(G) == 48 assert G.size() == 72 # all degrees are 3 assert len([n for n, d in G.degree() if d != 3]) == 0 G = nx.hexagonal_lattice_graph(5, 8, periodic=True) HLG = nx.hexagonal_lattice_graph pytest.raises(nx.NetworkXError, HLG, 2, 7, periodic=True) pytest.raises(nx.NetworkXError, HLG, 1, 4, periodic=True) pytest.raises(nx.NetworkXError, HLG, 2, 1, periodic=True)
def hexagonal_lattice(m, n, with_boundaries=False, with_lattice_components=False, with_faces=True, **kwargs) -> nx.Graph: ''' Sanitize networkx properties for Bokeh consumption ''' if 'periodic' in kwargs: kwargs['with_positions'] = False G = nx.hexagonal_lattice_graph(m, n, **kwargs) nx.set_node_attributes(G, None, 'contraction') return G else: G = nx.hexagonal_lattice_graph(m, n, **kwargs) if with_faces: G.faces, _ = embedded_faces(G) if with_lattice_components: horiz = nx.Graph() for i in range(m + 1): sub = G.subgraph([(j, i) for j in range(n)]) horiz = nx.compose(horiz, sub.copy()) diag_l = G.copy() for i in range(m + 1): remove_edges(diag_l, [((j, i), (j + 1, i)) for j in range(n)]) diag_r = diag_l.copy() for i in range(m + 1): if i % 2 == 0: remove_edges(diag_l, [((j, i), (j + 1, i)) for j in range(n)]) remove_edges(diag_r, [((j, i), (j + 1, i - 1)) for j in range(n)]) else: remove_edges(diag_l, [((j, i), (j + 1, i + 1)) for j in range(n)]) remove_edges(diag_r, [((j, i), (j, i + 1)) for j in range(n)]) G.lattice_components = { 'diag_l': diag_l, 'diag_r': diag_r, 'horiz': horiz } if with_boundaries: l = G.subgraph([(0, i) for i in range(m * 2 + 2)]) r = G.subgraph([(n, i) for i in range(m * 2 + 2)]) t = G.subgraph([(j, m * 2) for j in range(n + 1)] + [(j, m * 2 + 1) for j in range(n + 1)]) b = G.subgraph([(j, 0) for j in range(n + 1)] + [(j, 1) for j in range(n + 1)]) return G, (l.copy(), r.copy(), t.copy(), b.copy()) else: return G
def hexagonal(size, periodic=False): """ Construct a hexagonal lattice, a lattice whose nodes and edges are the hexagonal tiling of the plane. Parameters ---------- size : int, or tuple (m, n) of ints size of the lattice (mxn) periodic : bool Whether boundaries are periodic. Returns ------- G : networkx.Graph The lattice represented as a networkx.Graph The graph has the node attribute 'pos' with the given point coordinates, and the edge attribute 'length', which is the Euclidean distance between nodes. """ if np.ndim(size) == 0: m = size n = size elif np.ndim(size) == 1: m, n = size G = nx.hexagonal_lattice_graph(m, n, periodic=periodic) # pos = nx.get_node_attributes(G, 'pos') # factor = 2 * 3**(-0.75) # pos_scaled = {k: factor*np.array(v) for k, v in pos.items()} # nx.set_node_attributes(G, pos_scaled, 'pos') distances = {(e1, e2): 1 for e1, e2 in G.edges()} nx.set_edge_attributes(G, distances, 'length') return nx.convert_node_labels_to_integers(G)
def __init__(self, xdim=10, ydim=10, grid_type='2d', flora_system=1, colorize=True, edges=True, slow_burn=False): self.xdim = xdim self.ydim = ydim self.grid_type = grid_type if grid_type == '2d': self.space = nx.grid_2d_graph(self.xdim, ydim) elif grid_type == 'hex': self.space = nx.hexagonal_lattice_graph(self.xdim, ydim) elif grid_type == 'tri': self.space = nx.triangular_lattice_graph(self.xdim, ydim) else: # TODO: raise exception? default to 2d? self.space = nx.grid_2d_graph(self.xdim, ydim) for node in self.space.nodes: self.space.node[node]['locale'] = Locale(flora_system=flora_system, location=node, region=self) self.nodes = set([node for node in self.space.nodes]) if edges: self._add_border_nodes() self.conversion_rates = {0: 0.2, 1: 0.1, 2: 0.15, 3: 0.05, 4: 0.1, 5: 0} self.time = 0 self.colorize = colorize self.slow_burn = slow_burn self.constants = STATE_CONSTANTS self.verbose = False self.basins_current=False
def __init__(self, xdim=10, ydim=10, grid_type='2d', colorize=True): self.xdim = xdim self.ydim = ydim self.grid_type = grid_type if grid_type == '2d': self.space = nx.grid_2d_graph(xdim, ydim) elif grid_type == 'hex': self.space = nx.hexagonal_lattice_graph(xdim, ydim) elif grid_type == 'tri': self.space = nx.triangular_lattice_graph(xdim, ydim) else: # TODO: raise exception? default to 2d? self.space = nx.grid_2d_graph(xdim, ydim) for node in self.space.nodes: self.space.node[node]['locale'] = Locale() self.conversion_rates = { 0: 0.2, 1: 0.1, 2: 0.15, 3: 0.05, 4: 0.1, 5: 0 } self.time = 0 self.colorize = colorize
def __init__(self,n,m,conf): self.G = nx.hexagonal_lattice_graph(n,m) self.pos = nx.get_node_attributes(self.G, 'pos') self.home_node = (0,0) self.current_node = (0,0) self.last_node = (0,0) self.dora = dora.DoRA(self.G, conf) self.is_first_node = True
def generate_graph(m, n): G = nx.hexagonal_lattice_graph(m, n) A = nx.to_numpy_matrix(G) G = nx.from_numpy_matrix(A) data = json_graph.node_link_data(G) with open('./Working/graph.json', 'w') as f: json.dump(data, f) with open('./Working/graph_flag', mode='w', encoding='utf-8') as fh: fh.write("i look at you")
def HexLattice(HexX, HexY, gamma=1.0): G = nx.hexagonal_lattice_graph(HexY, HexX) nodes = G.number_of_nodes() pos = dict( (n, n) for n in G.nodes()) # this gives positions on a square lattice coords = [] for i, j in G.nodes(): coords.append((i, j)) coordVal = [] for k in range(nodes): coordVal.append(k) # shift positions to make graph look like a hexagonal lattice for coord in range(len(coords)): if ((coords[coord][0] % 2 == 0) and (coords[coord][1] % 2 != 0)): coords[coord] = ((float(coords[coord][0]) - 0.15), coords[coord][1]) elif ((coords[coord][0] % 2 != 0) and (coords[coord][1] % 2 != 0)): coords[coord] = ((float(coords[coord][0]) + 0.15), coords[coord][1]) elif ((coords[coord][0] % 2 == 0) and (coords[coord][1] % 2 == 0)): coords[coord] = ((float(coords[coord][0]) + 0.15), coords[coord][1]) elif ((coords[coord][0] % 2 != 0) and (coords[coord][1] % 2 == 0)): coords[coord] = ((float(coords[coord][0]) - 0.15), coords[coord][1]) # adjacency matrix Adj = nx.adjacency_matrix( G ) # positions are labelled from lower left corner up, every column starts at the bottom Adj = Adj.todense() pos = dict(zip(coordVal, coords)) LabelDict = dict(zip(G.nodes(), coordVal)) # rename nodes from 0 to nodes G = nx.relabel_nodes(G, LabelDict) TotNodes = G.number_of_nodes() Deg = np.zeros((TotNodes, TotNodes)) for i in range(TotNodes): Deg[i, i] = np.sum(Adj[i, :]) H = np.zeros((TotNodes, TotNodes), dtype=complex) H += gamma * (Deg - Adj) return G, H, pos
def __init__(self, network_type, size, **kwargs): if network_type == '2D_lattice': tiling = kwargs['tiling'] per = kwargs['periodic'] if tiling == 3: self.graph = nx.triangular_lattice_graph(size, size, periodic = per, with_positions = True) self.pos = nx.get_node_attributes(self.graph,'pos') self.M = len(self.graph.edges()) self.N = len(self.graph.nodes()) elif tiling == 4: self.graph = nx.grid_2d_graph(size, size, periodic = per) self.pos = dict( (n, n) for n in self.graph.nodes() ) self.labels = dict( ((i, j), i * size + j) for i, j in self.graph.nodes() ) self.M = len(self.graph.edges()) self.N = len(self.graph.nodes()) elif tiling == 6: self.graph = nx.hexagonal_lattice_graph(size, size, periodic = per, with_positions = True) self.pos = nx.get_node_attributes(self.graph,'pos') self.M = len(self.graph.edges()) self.N = len(self.graph.nodes()) elif network_type == 'ring_lattice':# TODO: banding for every node self.graph = nx.cycle_graph(size) theta = (2*np.pi)/size self.pos = dict((i,(np.sin(theta*i),np.cos(theta*i))) for i in range(size)) self.M = len(self.graph.edges()) self.N = len(self.graph.nodes()) self.text = 'Ring Lattice' if kwargs['banded']: if kwargs['band_length'] >= int(self.N/2)-1: raise ValueError('Band length cannot exceed the half of the size of the network') if kwargs['band_length'] <2: raise ValueError('Band length should be a positive integer greater 1 since the closest neighbors are already connected') for u in range(self.N): for i in range(2,kwargs['band_length']+1): # ranges from 2 to k+2 to avoid the closest node and start ## banding from the second closest node if u + i >= self.N: v = u + i - self.N else: v = u + i self.graph.add_edge(u, v) if u - i < 0: v = self.N + u - i else: v = u - i self.graph.add_edge(u, v) self.text = self.text + ' w/ bandlength %d'%kwargs['band_length'] else:self.text = self.text + ' w/ bandlength 0' else: raise ValueError('network type can be a lattice or a ring') self.A = nx.adjacency_matrix(self.graph)
def HexCluster(Clusters,ClusterX,ClusterY,orientation): '''generate random graph of unconnected clusters, each with same fixed number of nodes and edges''' ClusterList = [] PosDictList = [] for cluster in range(Clusters): G = nx.hexagonal_lattice_graph(ClusterY,ClusterX) coords = [] if orientation == 'horizontal': Cdist = ClusterX + 1 # distance between clusters, for drawing for i,j in G.nodes(): coords.append((i+((ClusterX+1)*cluster),j)) # clusters are 1 hexagon apart if orientation == 'vertical': Cdist = ClusterY*2+2 for i,j in G.nodes(): coords.append((i,j+((ClusterY*2+2)*cluster))) # shift positions to make graph look like a hexagonal lattice for coord in range(len(coords)): if (((coords[coord][0]-(Cdist*cluster))%2 == 0) and (coords[coord][1]%2 != 0)): coords[coord] = ((float(coords[coord][0]) - 0.15), coords[coord][1]) elif (((coords[coord][0]-(Cdist*cluster))%2 != 0) and (coords[coord][1]%2 != 0)): coords[coord] = ((float(coords[coord][0]) + 0.15), coords[coord][1]) elif (((coords[coord][0]-(Cdist*cluster))%2 == 0) and (coords[coord][1]%2 == 0)): coords[coord] = ((float(coords[coord][0]) + 0.15), coords[coord][1]) elif (((coords[coord][0]-(Cdist*cluster))%2 != 0) and (coords[coord][1]%2 == 0)): coords[coord] = ((float(coords[coord][0]) - 0.15), coords[coord][1]) NewLabels = [n for n in range(G.number_of_nodes())] LabelDict = dict(zip(G.nodes(),(np.array(NewLabels)+(G.number_of_nodes())*cluster))) # rename nodes from 0 to Clusters*ClusterNodes G = nx.relabel_nodes(G,LabelDict) ClusterList.append(G) PosDict = dict(zip((np.array(NewLabels)+(G.number_of_nodes())*cluster),coords)) PosDictList.append(PosDict) PosDictAll = {} for c in range(0,Clusters): PosDictAll.update(PosDictList[c]) G = ClusterList[0] for i in range(Clusters-1): G = nx.union(G,ClusterList[i+1]) return G, PosDictAll
def hexagonal_lattice(m, n, periodic, directed, weighted): #Generate Network: hexagonal_lattice = nx.hexagonal_lattice_graph(m, n, periodic=periodic) #Give the nodes an initial position: node_position = position_nodes(hexagonal_lattice) #If the network is weighted, add edge weights: #if weighted: # weight_edges(hexagonal_lattice) return hexagonal_lattice, node_position
def generate_graph(m, n): G = nx.hexagonal_lattice_graph(m, n) A = nx.to_numpy_matrix(G) G = nx.from_numpy_matrix(A) node_data = [] for i in nx.nodes(G): node_data.append(i) node_data = pd.DataFrame(node_data) node_data.to_csv("./Resources/Output/Working/node.csv") print('[Python]' + 'Generate Node') edge_data = nx.to_pandas_edgelist(G) edge_data.to_csv("./Resources/Output/Working/edge.csv") print('[Python]' + 'Generate Edge') with open('./Resources/Output/Working/flag', mode = 'w', encoding = 'utf-8') as fh: fh.write("i look at you")
def test_lattice_points(self): """Tests that the graph is really a hexagonal lattice.""" for m, n in [(4, 5), (4, 4), (4, 3), (3, 2), (3, 3), (3, 5)]: G = nx.hexagonal_lattice_graph(m, n) assert_equal(len(G), 2 * (m + 1) * (n + 1) - 2) C_6 = nx.cycle_graph(6) hexagons = [ [(0, 0), (0, 1), (0, 2), (1, 0), (1, 1), (1, 2)], [(0, 2), (0, 3), (0, 4), (1, 2), (1, 3), (1, 4)], [(1, 1), (1, 2), (1, 3), (2, 1), (2, 2), (2, 3)], [(2, 0), (2, 1), (2, 2), (3, 0), (3, 1), (3, 2)], [(2, 2), (2, 3), (2, 4), (3, 2), (3, 3), (3, 4)], ] for hexagon in hexagons: assert_true(nx.is_isomorphic(G.subgraph(hexagon), C_6))
def test_lattice_points(self): """Tests that the graph is really a hexagonal lattice.""" for m, n in [(4, 5), (4, 4), (4, 3), (3, 2), (3, 3), (3, 5)]: G = nx.hexagonal_lattice_graph(m, n) assert len(G) == 2 * (m + 1) * (n + 1) - 2 C_6 = nx.cycle_graph(6) hexagons = [ [(0, 0), (0, 1), (0, 2), (1, 0), (1, 1), (1, 2)], [(0, 2), (0, 3), (0, 4), (1, 2), (1, 3), (1, 4)], [(1, 1), (1, 2), (1, 3), (2, 1), (2, 2), (2, 3)], [(2, 0), (2, 1), (2, 2), (3, 0), (3, 1), (3, 2)], [(2, 2), (2, 3), (2, 4), (3, 2), (3, 3), (3, 4)], ] for hexagon in hexagons: assert nx.is_isomorphic(G.subgraph(hexagon), C_6)
import numpy as np import networkx as nx import pdb import random import colorcet as cc import gds def swift_hohenberg(G: nx.graph, a: float, b: float, c: float, gam0: float, gam2: float) -> gds.node_gds: assert c > 0, 'Unstable' amplitude = gds.node_gds(G) amplitude.set_evolution( dydt=lambda t, y: -a*y - b*(y**2) - c*(y**3) + gam0*amplitude.laplacian(y) - gam2*amplitude.bilaplacian(y) ) # amplitude.set_initial(y0=lambda _: np.random.uniform()) amplitude.set_initial(y0=lambda x: x[0]+x[1]) return amplitude def stripes(G): return swift_hohenberg(G, 0.7, 0, 1, -2, 1) def spots(G): return swift_hohenberg(G, 1-1e-2, -1, 1, -2, 1) def spirals(G): return swift_hohenberg(G, 0.3, -1, 1, -2, 1) if __name__ == '__main__': G = nx.hexagonal_lattice_graph(22, 23) eq = spirals(G) gds.render(eq, node_size=0.035, plot_width=800, node_palette=cc.bgy, dynamic_ranges=True, title='Pattern formation on a hexagonal lattice')
def test_multigraph(self): """Tests for creating a hexagonal lattice multigraph.""" G = nx.hexagonal_lattice_graph(3, 5, create_using=nx.Graph()) H = nx.hexagonal_lattice_graph(3, 5, create_using=nx.MultiGraph()) assert list(H.edges()) == list(G.edges())
def HexTube(HexX, HexY, ChiralShift): G = nx.hexagonal_lattice_graph(HexY, HexX) nodes = G.number_of_nodes() print(nodes) pos = dict( (n, n) for n in G.nodes()) # this gives positions on a square lattice # label dictionary for debugging and to make cylinder (see adjacency matrix) coords = [] for i, j in G.nodes(): coords.append((i, j)) coordVal = [] for k in range(nodes): coordVal.append(k) labels = dict(zip(coords, coordVal)) # shift positions to make graph look like a hexagonal lattice for coord in range(len(coords)): if ((coords[coord][0] % 2 == 0) and (coords[coord][1] % 2 != 0)): coords[coord] = ((float(coords[coord][0]) - 0.15), coords[coord][1]) elif ((coords[coord][0] % 2 != 0) and (coords[coord][1] % 2 != 0)): coords[coord] = ((float(coords[coord][0]) + 0.15), coords[coord][1]) elif ((coords[coord][0] % 2 == 0) and (coords[coord][1] % 2 == 0)): coords[coord] = ((float(coords[coord][0]) + 0.15), coords[coord][1]) elif ((coords[coord][0] % 2 != 0) and (coords[coord][1] % 2 == 0)): coords[coord] = ((float(coords[coord][0]) - 0.15), coords[coord][1]) # adjacency matrix Adj = nx.adjacency_matrix( G ) # positions are labelled from lower left corner up, every column starts at the bottom Adj = Adj.todense() if HexX > HexY: # join top and bottom edge (horizontal cylinder) if ChiralShift != 0: for key, value in labels.items(): if (key[1] == 0 or key[1] == 1): for k, v in labels.items(): if (k[1] == key[1] + (2 * HexY)) and (k[0] == key[0] + (2 * ChiralShift)): Adj[v, value] = 1 Adj[value, v] = 1 else: for key, value in labels.items(): if (key[1] == 0 or ((key[1] == 1) and (key[0] != 0))): Adj[value + (2 * HexY), value] = 1 Adj[value, value + (2 * HexY)] = 1 if HexX < HexY: # join left and right sides of the cylinder (vertical tube) for key, value in labels.items(): if (key[0] == 0 and (key[1] != 0 and key[1] != (2 * HexY + 1))): for key1, value1 in labels.items(): if (key1[1] == key[1] and (key1[0] == (key[0] + HexY))): Adj[value, value1] = 1 Adj[value1, value] = 1 pos = dict(zip(coordVal, coords)) LabelDict = dict(zip(G.nodes(), coordVal)) # rename nodes from 0 to nodes G = nx.relabel_nodes(G, LabelDict) return G, Adj, pos
plt.title('grid_2d_graph') plt.axis('on') plt.xticks([]) plt.yticks([]) #n维网格图 grid_graph = nx.grid_graph(dim=[2, 4, 4]) plt.subplot(2, 3, 2) nx.draw(grid_graph, with_labels=True) plt.title('grid_graph') plt.axis('on') plt.xticks([]) plt.yticks([]) #m×n的六角形格子图。 G = nx.hexagonal_lattice_graph(3, 3) plt.subplot(2, 3, 3) nx.draw(G, with_labels=True) plt.title('hexagonal_lattice_graph') plt.axis('on') plt.xticks([]) plt.yticks([]) #n维超立方体图形。 G = nx.hypercube_graph(3) plt.subplot(2, 3, 4) nx.draw(G, with_labels=True) plt.title('hypercube_graph') plt.axis('on') plt.xticks([]) plt.yticks([])
def test_multigraph(self): """Tests for creating a hexagonal lattice multigraph.""" G = nx.hexagonal_lattice_graph(3, 5, create_using=nx.Graph()) H = nx.hexagonal_lattice_graph(3, 5, create_using=nx.MultiGraph()) assert_equal(list(H.edges()), list(G.edges()))
def hexagonal(m, n, periodic=False, dist_function=None): G = nx.hexagonal_lattice_graph(m, n, periodic=periodic) return G
import matplotlib.pyplot as plt import matplotlib.gridspec as gridspec import numpy as np import scipy.linalg from tqdm import tqdm # M and N are number of HEXAGONS (not lattice points) in x and y N = 1 # y M = 6 # x - cylinder only works if this is even gamma = 1.0 steps = 7 InitialPosn1 = 5 #13 InitialPosn2 = 20 #20 G = nx.hexagonal_lattice_graph(N, M) nodes = G.number_of_nodes() print('number of nodes: ', nodes) edges = G.number_of_edges() pos = dict( (n, n) for n in G.nodes()) # this gives positions on a square lattice # label dictionary for debugging and to make cylinder (see adjacency matrix) coords = [] for i, j in G.nodes(): coords.append((i, j)) coordVal = [] for k in range(nodes):
def get_connectivity_graph(qubits, topology='grid', param=None): attempt = 0 while attempt < 10: if topology == 'grid': # assume square grid side = int(np.sqrt(qubits)) G = nx.grid_2d_graph(side, side) elif topology == 'erdosrenyi': if param == None: print("Erdos Renyi graph needs parameter p.") G = nx.fast_gnp_random_graph(qubits, param) elif topology == 'turan': if param == None: print("Turan graph needs parameter r.") G = nx.turan_graph(qubits, param) elif topology == 'regular': if param == None: print("d-regular graph needs parameter d.") G = nx.random_regular_graph(param, qubits) elif topology == 'cycle': G = nx.cycle_graph(qubits) elif topology == 'wheel': G = nx.wheel_graph(qubits) elif topology == 'complete': G = nx.complete_graph(qubits) elif topology == 'hexagonal': # assume square hexagonal grid, node = 2(m+1)**2-2 side = int(np.sqrt((qubits + 2) / 2)) - 1 G = nx.hexagonal_lattice_graph(side, side) elif topology == 'path': G = nx.path_graph(qubits) elif topology == 'ibm_falcon': # https://www.ibm.com/blogs/research/2020/07/qv32-performance/ # 27 qubits G = nx.empty_graph(27) G.name = "ibm_falcon" G.add_edges_from([(0, 1), (1, 2), (2, 3), (3, 4), (3, 5), (5, 6), (6, 7), (7, 8), (8, 9), (8, 10), (10, 11), (1, 12), (6, 13), (11, 14), (12, 15), (15, 16), (16, 17), (17, 18), (17, 19), (19, 20), (13, 20), (20, 21), (21, 22), (22, 23), (22, 24), (24, 25), (14, 25), (25, 26)]) elif topology == 'ibm_penguin': # 20 qubits G = nx.empty_graph(20) G.name = "ibm_penguin" G.add_edges_from([(0, 1), (1, 2), (2, 3), (3, 4), (0, 5), (5, 6), (6, 7), (7, 8), (8, 9), (4, 9), (5, 10), (10, 11), (11, 12), (7, 12), (12, 13), (13, 14), (9, 14), (10, 15), (15, 16), (16, 17), (17, 18), (18, 19), (14, 19)]) elif topology == '1express': # path with express channels G = nx.convert_node_labels_to_integers(nx.path_graph(qubits)) G.add_edges_from([(s, s + param) for s in range(0, qubits - param, param // 2)]) elif topology == '2express': # grid with express channels side = int(np.sqrt(qubits)) G = nx.convert_node_labels_to_integers(nx.grid_2d_graph( side, side)) G.add_edges_from([ (s, s + param) for x in range(side) for s in range(x * side, x * side + side - param, param // 2) ]) # rows G.add_edges_from([ (s, s + param * side) for y in range(side) for s in range(y, y + side * (side - param), param // 2 * side) ]) # cols else: print("Topology %s not recognized; use empty graph instead." % topology) G = nx.empty_graph(qubits) if nx.is_connected(G) or nx.is_empty(G): break else: attempt += 1 return nx.convert_node_labels_to_integers(G)