def test_wheel_graph(self): for n, G in [ (0, nx.null_graph()), (1, nx.empty_graph(1)), (2, nx.path_graph(2)), (3, nx.complete_graph(3)), (4, nx.complete_graph(4)), ]: g = nx.wheel_graph(n) assert is_isomorphic(g, G) g = nx.wheel_graph(10) assert sorted( d for n, d in g.degree()) == [3, 3, 3, 3, 3, 3, 3, 3, 3, 9] pytest.raises(nx.NetworkXError, nx.wheel_graph, 10, create_using=nx.DiGraph) mg = nx.wheel_graph(10, create_using=nx.MultiGraph()) assert_edges_equal(mg.edges(), g.edges()) G = nx.wheel_graph("abc") assert len(G) == 3 assert G.size() == 3
def generate_random_uniform(N, T, G_method, seed=1234): rng = np.random.RandomState(seed) N_ = 4 if N >= 5 else N - 1 switcher = { 'complete': nx.complete_graph(N), 'path': nx.path_graph(N), 'cycle': nx.cycle_graph(N), 'regular': nx.random_regular_graph(N_, N, seed=rng), 'wheel': nx.wheel_graph(N), 'tree': nx.random_tree(N, seed=rng), 'chordal': nx.Graph(nx.chordal_cycle_graph(N)), } G = switcher.get(G_method) player_list = [] for n in range(N): p = Player(x=rng.uniform(3, -3, T), sm=13.5, s0=0, ram=5, ec=0.9, ed=0.9) player_list.append(p) buying_price = np.ones(T) * 3.0 selling_price = np.ones(T) * 1.0 game = Game(player_list, buying_price, selling_price, G) game.graphtype = G_method game.seed = seed return game
def pagerank_example(): n = 7 g = nx.wheel_graph(n) pos = nx.spring_layout(g) g = nx.DiGraph() g.add_nodes_from(range(0,n)) g.add_edge(0,1) g.add_edge(0,6) g.add_edge(0,5) g.add_edge(1,2) g.add_edge(1,6) g.add_edge(2,0) g.add_edge(2,1) g.add_edge(2,3) g.add_edge(3,4) g.add_edge(4,5) g.add_edge(4,6) g.add_edge(5,0) g.add_edge(5,3) g.add_edge(5,4) ranks = nx.pagerank(g) for n in range(0,n): print 'node',n print ' rank:',ranks[n] print ' out edges:',g.neighbors(n) if g.neighbors(n): print ' per edge:',ranks[n]/len(g.neighbors(n)) else: print ' per edge: null' draw_with_centrality(g, layout=pos)
def pagerank_example(): n = 7 g = nx.wheel_graph(n) pos = nx.spring_layout(g) g = nx.DiGraph() g.add_nodes_from(range(0, n)) g.add_edge(0, 1) g.add_edge(0, 6) g.add_edge(0, 5) g.add_edge(1, 2) g.add_edge(1, 6) g.add_edge(2, 0) g.add_edge(2, 1) g.add_edge(2, 3) g.add_edge(3, 4) g.add_edge(4, 5) g.add_edge(4, 6) g.add_edge(5, 0) g.add_edge(5, 3) g.add_edge(5, 4) ranks = nx.pagerank(g) for n in range(0, n): print 'node', n print ' rank:', ranks[n] print ' out edges:', g.neighbors(n) if g.neighbors(n): print ' per edge:', ranks[n] / len(g.neighbors(n)) else: print ' per edge: null' draw_with_centrality(g, layout=pos)
def GenerateGraphs(size, base): dic=GenerateDic(size,base) for i in range(1,5): for j in range(10): G=AddEdges(nx.wheel_graph(size)) for k in range (5): nodes=RandNodes(size-1) for l in range(5): dic["Edmond"+str(size)+"wheel"].append(Edmond(G,nodes[0],nodes[1])) dic["Din"+str(size)+"wheel"].append(Din(G,nodes[0],nodes[1])) dic["Boyk"+str(size)+"wheel"].append(Boyk(G,nodes[0],nodes[1])) G=AddEdges(nx.circular_ladder_graph(size)) for k in range (5): nodes=RandNodes(size-1) for l in range(5): dic["Edmond"+str(size)+"circ"].append(Edmond(G,nodes[0],nodes[1])) dic["Din"+str(size)+"circ"].append(Din(G,nodes[0],nodes[1])) dic["Boyk"+str(size)+"circ"].append(Boyk(G,nodes[0],nodes[1])) G=AddEdges(nx.dense_gnm_random_graph(size,int(size*size*0.2 ))) for k in range (5): nodes=RandNodes(size-1) for l in range(5): dic["Edmond"+str(size)+"comp"].append(Edmond(G,nodes[0],nodes[1])) dic["Din"+str(size)+"comp"].append(Din(G,nodes[0],nodes[1])) dic["Boyk"+str(size)+"comp"].append(Boyk(G,nodes[0],nodes[1])) size*=base; df=pd.DataFrame(dic) df.to_csv("matrix.csv")
def simpleWheel(subset, center, direction=ut.Direction.OUTGOING): """ create a wheel graph on the input nodes subset with node i as the center """ n = len(subset) res = np.where(subset == center) if len(res[0]) == 0: raise NameError('node ' + str(center) + ' is not in the subset') centerIndex = res[0][0] D = dict(zip(np.array([i for i in range(n)]), subset)) D[0], D[centerIndex] = center, subset[0] G = nx.wheel_graph(n) G = nx.to_directed(G) G = nx.DiGraph(G) if direction == ut.Direction.OUTGOING: G.remove_edges_from([(i, 0) for i in range(n)]) elif direction == ut.Direction.INCOMING: G.remove_edges_from([(0, i) for i in range(n)]) else: raise NameError(str(direction) + ' is not a valid value for direction') G = nx.relabel_nodes(G, D) ut.normalizeGraph(G) return G
def generate_connection_graph(graph_type, params, count): lower_type = graph_type.lower() if lower_type == 'complete': assert (len(params) == 0) return networkx.complete_graph(count) elif lower_type == 'complete-bipartite': assert (len(params) == 2) assert (int(params[0]) > 0.0) assert (int(params[1]) > 0.0) n1 = int(round(count * float(params[0]) / float(params[1]))) n2 = int(round(count * float(params[1]) / float(params[0]))) n1 = 1 if n1 < 1 else n1 n2 = 1 if n2 < 1 else n2 return networkx.complete_bipartite_graph(n1, n2) elif lower_type == 'circular-ladder': assert (len(params) == 0) return networkx.circular_ladder_graph(count) elif lower_type == 'cycle': assert (len(params) == 0) return networkx.cycle_graph(count) elif lower_type == 'periodic-2grid': assert (len(params) == 2) assert (int(params[0]) > 0.0) assert (int(params[1]) > 0.0) width = int(round(math.sqrt(count * float(params[0]) / float(params[1])))) height = int(round(math.sqrt(count * float(params[1]) / float(params[0])))) width = 1 if width < 1 else width height = 1 if height < 1 else height return networkx.grid_2d_graph(width, height, True) elif lower_type == 'nonperiodic-2grid': assert (len(params) == 2) assert (int(params[0]) > 0.0) assert (int(params[1]) > 0.0) width = int(round(math.sqrt(count * float(params[0]) / float(params[1])))) height = int(round(math.sqrt(count * float(params[1]) / float(params[0])))) width = 1 if width < 1 else width height = 1 if height < 1 else height return networkx.grid_2d_graph(width, height, False) elif lower_type == 'hypercube': assert (len(params) == 0) return networkx.hypercube_graph(int(round(math.log(count, 2)))) elif lower_type == 'star': assert (len(params) == 0) return networkx.star_graph(count - 1) elif lower_type == 'wheel': assert (len(params) == 0) return networkx.wheel_graph(count) elif lower_type == 'erdos-reyni': assert (len(params) == 1) return networkx.erdos_renyi_graph(count, float(params[0])) elif lower_type == 'watts-strogatz': assert (len(params) == 2) if int(params[0]) >= count / 2: k = int(count / 2 - 1) else: k = int(params[0]) return networkx.connected_watts_strogatz_graph(count, k, int(params[1])) else: print "Unknown graph type {}".format(lower_type) assert False
class GraphType: BALANCED_TREE = ('Balanced tree', _balanced_tree) BARBELL = ('Barbell', lambda n: nx.barbell_graph(int(n*.4), int(n*.3))) CIRCULAR_LADDER = ('Circular ladder', lambda n: nx.circular_ladder_graph(int(n/2))) COMPLETE = ('Complete', lambda n: nx.complete_graph(int(n))) COMPLETE_BIPARTITE = ('Complete bipartite', lambda n: nx.complete_bipartite_graph(int(n*.6), int(n*.4))) CYCLE = ('Cycle', lambda n: nx.cycle_graph(int(n))) GRID = ('Grid', lambda n: nx.grid_graph([int(np.sqrt(n))]*2)) HYPERCUBE = ('Hypercube', _hypercube) LADDER = ('Ladder', lambda n: nx.ladder_graph(int(n/2))) LOBSTER = ('Lobster', lambda n: nx.random_lobster(int(n / (1 + .7 + .7*.5)), .7, .5)) LOLLIPOP = ('Lollipop', lambda n: nx.lollipop_graph(int(n/2), int(n/2))) PATH = ('Path', lambda n: nx.path_graph(int(n))) REGULAR = ('Regular', lambda n: nx.random_regular_graph(np.random.randint(10)*2, n)) SCALEFREE = ('Scale-free', lambda n: nx.scale_free_graph(int(n))) SHELL = ('Shell', lambda n: nx.random_shell_graph([(int(n*.1), int(n*.1), .2), (int(n*.3), int(n*.3), .8), (int(n*.6), int(n*.6), .5)])) STAR = ('Star', lambda n: nx.star_graph(int(n - 1))) WAXMAN = ('Waxman', lambda n: nx.waxman_graph(int(n))) WHEEL = ('Wheel', lambda n: nx.wheel_graph(int(n))) all = (BALANCED_TREE, BARBELL, CIRCULAR_LADDER, COMPLETE, COMPLETE_BIPARTITE, CYCLE, GRID, HYPERCUBE, LADDER, LOBSTER, LOLLIPOP, PATH, REGULAR, SCALEFREE, SHELL, STAR, WAXMAN, WHEEL)
def __init__(self, N): self.name = 'Wheel graph W_%i' % N self.N = N self.G = nx.wheel_graph(N-1) self.params = dict() self.state = None
def main(): args = parse_arguments() # Generate graph for given parameters if args.cycle: graph = networkx.cycle_graph(args.vertices) graph = networkx.path_graph(args.vertices) elif args.star: graph = networkx.star_graph(args.vertices) elif args.wheel: graph = networkx.wheel_graph(args.vertices) elif args.ladder: graph = networkx.ladder_graph(args.vertices) elif args.fill_rate: if args.fill_rate > 50.0: graph = networkx.gnp_random_graph(args.vertices, args.fill_rate / 100.0, None, args.directed) else: graph = networkx.fast_gnp_random_graph(args.vertices, args.fill_rate / 100.0, None, args.directed) else: graph = networkx.gnm_random_graph(args.vertices, args.edges, None, args.directed) # Print generated graph print("{} {}".format(graph.number_of_nodes(), graph.number_of_edges())) for edge in graph.edges(): print("{} {}".format(edge[0] + 1, edge[1] + 1)) # Export generated graph to .png if args.image_path: export_to_png(graph, args.image_path)
def classic_graphs(): print("Balanced Tree") BG = nx.balanced_tree(3, 2) draw_graph(BG) print("Barbell Graph") BBG = nx.barbell_graph(3, 2) draw_graph(BBG) print("Complete Graph") CG = nx.complete_graph(10) draw_graph(CG) print("Complete Multipartite Graph") CMG = nx.complete_multipartite_graph(1, 2, 10) print([CMG.node[u]['block'] for u in CMG]) print(CMG.edges(0)) print(CMG.edges(2)) print(CMG.edges(4)) draw_graph(CMG) print("Circular Ladder Graph") CLG = nx.circular_ladder_graph(5) draw_graph(CLG) print("Dorogovtsev Goltsev Mendes Graph") DGMG = nx.dorogovtsev_goltsev_mendes_graph(3) draw_graph(DGMG) print("Empty Graph") EG = nx.empty_graph(5, create_using=nx.DiGraph()) draw_graph(EG) print("Grid 2D Graph") G2DG = nx.grid_2d_graph(5, 6) draw_graph(G2DG) print("Grid Graph") GDG = nx.grid_graph(dim=[5, 2]) draw_graph(GDG) print("Hypercube Graph") HG = nx.hypercube_graph(3) draw_graph(HG) print("Ladder Graph") LG = nx.ladder_graph(8) draw_graph(LG) print("Ladder Graph") LG = nx.ladder_graph(8) draw_graph(LG) print("Lollipop Graph") LPG = nx.lollipop_graph(n=6, m=4) draw_graph(LPG) print("Null Graph") NG = nx.null_graph() draw_graph(NG) print("Path Graph") PG = nx.path_graph(16) draw_graph(PG) print("Star Graph") SG = nx.star_graph(16) draw_graph(SG) print("Trivial Graph") TG = nx.trivial_graph() draw_graph(TG) print("Wheel Graph") WG = nx.wheel_graph(n=18) draw_graph(WG)
def generate_struct_mask(struct, n_nodes, shuffle_nodes): # a horrible collection of ifs due to args in nx constructors if struct == "star": g = nx.star_graph(n_nodes) elif struct == "random_tree": g = nx.random_tree(n_nodes) elif struct == "powerlaw_tree": g = nx.powerlaw_tree(n_nodes, gamma=3, seed=None) elif struct == "binary_tree": raise NotImplementedError("Implement a binary tree.") elif struct == "path": g = nx.path_graph(n_nodes) elif struct == "cycle": g = nx.cycle_graph(n_nodes) elif struct == "ladder": g = nx.ladder_graph(n_nodes) elif struct == "grid": m = np.random.choice(range(1, n_nodes+1)) n = n_nodes // m g = nx.grid_2d_graph(m, n) elif struct == "circ_ladder": g = nx.circular_ladder_graph(n_nodes) elif struct == "barbell": assert n_nodes >= 4 m = np.random.choice(range(2, n_nodes-1)) blocks = (m, n_nodes-m) g = nx.barbell_graph(*blocks) elif struct == "loll": assert n_nodes >= 2 m = np.random.choice(range(2, n_nodes+1)) g = nx.lollipop_graph(m, n_nodes-m) elif struct == "wheel": g = nx.wheel_graph(n_nodes) elif struct == "bipart": m = np.random.choice(range(n_nodes)) blocks = (m, n_nodes-m) g = nx.complete_multipartite_graph(*blocks) elif struct == "tripart": # allowed to be zero m, M = np.random.choice(range(n_nodes), size=2) if m > M: m, M = M, m blocks = (m, M-m, n_nodes-M) g = nx.complete_multipartite_graph(*blocks) elif struct == "fc": g = nx.complete_graph(n_nodes) else: raise NotImplementedError("Structure {} not implemented yet.".format(struct)) node_order = list(range(n_nodes)) if shuffle_nodes: np.random.shuffle(node_order) # a weird subclass by default; raises a deprecation warning # with a new update of networkx, this should be updated to # nx.convert_matrix.to_numpy_array np_arr_g = nx.to_numpy_matrix(g, nodelist=node_order) return np_arr_g.astype(int)
def test_wheel_graph(self): g = nx.wheel_graph(10) nx.set_node_attributes(g, 'infected', {n: False for n in g.nodes()}) g.node[0]['infected'] = True g.node[1]['infected'] = True g.node[5]['infected'] = True sz = AlgorithmSZ() source_estimation = sz.run(g, v=1) print("Source of rumor is %s" % source_estimation)
def test_wheel_graph(self): g = nx.wheel_graph(10) nx.set_node_attributes(g, 'infected', {n: False for n in g.nodes()}) g.node[0]['infected'] = True g.node[1]['infected'] = True g.node[5]['infected'] = True sz = AlgorithmSZ() source_estimation = sz.run(g, g) print("Source of rumor is %s" % source_estimation)
def test_wheel_graph(self, dim): """Test that output is correct for a wheel graph, whose largest cliques have dimension 3. The cliques always include the central spoke and two consecutive nodes in the outer wheel.""" graph = nx.wheel_graph(dim) subgraph = graph.nodes() # subgraph is the entire graph clique = resize.clique_shrink(subgraph, graph) assert len(clique) == 3 assert clique[0] == 0 assert clique[1] + 1 == clique[2] or (clique[1] == 1 and clique[2] == dim - 1)
def test_bidirectional_shortest_path_restricted_wheel(): wheel = nx.wheel_graph(6) length, path = _bidirectional_shortest_path(wheel, 1, 3) assert_true(path in [[1, 0, 3], [1, 2, 3]]) length, path = _bidirectional_shortest_path(wheel, 1, 3, ignore_nodes=[0]) assert_equal(path, [1, 2, 3]) length, path = _bidirectional_shortest_path(wheel, 1, 3, ignore_nodes=[0, 2]) assert_equal(path, [1, 5, 4, 3]) length, path = _bidirectional_shortest_path(wheel, 1, 3, ignore_edges=[(1, 0), (5, 0), (2, 3)]) assert_true(path in [[1, 2, 0, 3], [1, 5, 4, 3]])
def demo_create_centrality_example(): g = nx.wheel_graph(6) #~ pos = nx.spring_layout(g) pos = None g = nx.Graph() g.add_edge(1,3, weight=1.0) g.add_edge(1,4, weight=1.0) g.add_edge(2,4, weight=3.0) g.add_edge(2,5, weight=1.0) g.add_edge(3,1, weight=1.0) g.add_edge(3,5, weight=1.0) draw_with_centrality(g, layout=pos)
def demo_create_centrality_example(): g = nx.wheel_graph(6) #~ pos = nx.spring_layout(g) pos = None g = nx.Graph() g.add_edge(1, 3, weight=1.0) g.add_edge(1, 4, weight=1.0) g.add_edge(2, 4, weight=3.0) g.add_edge(2, 5, weight=1.0) g.add_edge(3, 1, weight=1.0) g.add_edge(3, 5, weight=1.0) draw_with_centrality(g, layout=pos)
def _generate_wheel(self, label, min_v, max_v): feature_params = {'mean': 0.0, 'variance': 0.1, 'dim': 32} num_v = np.random.randint(self.min_num_v[label], self.max_num_v[label]) n_rows = np.random.randint(2, num_v // 2) n_cols = num_v // n_rows g = nx.wheel_graph(num_v) #g = nx.grid_graph([n_rows, n_cols]) #g = nx.convert_node_labels_to_integers(g) feat = np.random.normal(label, feature_params['variance'], (g.number_of_nodes(), feature_params['dim'])) self.graphs.append(g) self.labels.append(label) self.features.append(feat)
def demo_graph_generators(): g = nx.wheel_graph(6) #~ g = nx.cycle_graph(10) #~ g = nx.star_graph(4) #~ g = nx.balanced_tree(3,3) #~ g = nx.complete_graph(5) #~ g = nx.dorogovtsev_goltsev_mendes_graph(2) #~ g = nx.hypercube_graph(2) #~ g = nx.ladder_graph(10) #~ g = nx.lollipop_graph(5, 4) #~ g = nx.house_graph() #~ g = nx.house_x_graph() draw_with_centrality(g)
def create_graph(information): if information['style'] == 'simple': return nx.barabasi_albert_graph(information['num_nodes'], information['avg_degree']) elif information['style'] == 'star': return nx.star_graph(information['num_nodes']) elif information['style'] == 'wheel': return nx.wheel_graph(information['num_nodes']) elif information['style'] == 'lobster': return nx.random_lobster(information['num_nodes'], information['prob1'], information['prob2']) else: print("Invalid network style received. Aborting...") exit(1)
def get_test_graphs() -> List[nx.Graph]: # return nx.graph_atlas_g()[1:100] names = [ "Path graph (10)", "Complete graph (30)", "Balanced Tree (2, 3)", "Barbell graph (5, 1)", "Binomial tree (4)", "Circular ladder graph (5)", "Cycle graph (10)", "Star graph (10)", "Wheel graph (6)" ] optimal_colorings = [2, 30, 2, 5, 2, 3, 2, 2, 4] graphs = [ nx.path_graph(10), nx.complete_graph(30), nx.balanced_tree(2, 3), nx.barbell_graph(5, 1), nx.binomial_tree(4), nx.circular_ladder_graph(5), nx.cycle_graph(10), nx.star_graph(10), nx.wheel_graph(6) ] # load graph instances for file in os.listdir("./instances"): new_graph = nx.Graph() with open(os.path.join("instances", file), "r") as f: # data = f.read() edges = [] line = f.readline() line.strip() while line: if " " not in line: break # need indexes to be from 0 edges.append([int(x) - 1 for x in line.split(" ")]) line = f.readline() line.strip() # last line is the optimal coloring if line == '?': continue # ignore graphs for which we don't know the optimal coloring new_graph.add_edges_from(edges) if len(new_graph.nodes) > 200 or len(new_graph.edges) > 5000: continue names.append(file) optimal_colorings.append(line) graphs.append(new_graph) for i, g in enumerate(graphs): g.name = names[i] return graphs, optimal_colorings
def test_max_iterations(self, monkeypatch): """Test if function stops after 5 iterations despite not being in a dead end (i.e., when ``grow != swap``). This is achieved by monkeypatching the ``np.random.choice`` call in ``grow`` and ``swap`` so that for a 5-node wheel graph starting as a [0, 1] node clique, the algorithm simply oscillates between [0, 1, 2] and [0, 2, 3] for each iteration of growth & swap. For odd iterations, we get [0, 2, 3].""" graph = nx.wheel_graph(5) c = [0, 1] with monkeypatch.context() as m: p = functools.partial(patch_random_choice, element=0) m.setattr(np.random, "choice", p) result = clique.search(c, graph, iterations=5) assert result == [0, 2, 3]
def closeness_example(): n = 5 g = nx.wheel_graph(n) pos = nx.spring_layout(g) g = nx.DiGraph() g.add_nodes_from(range(0, n)) edge_list = [(1, 0), (2, 1), (0, 2), (0, 3), (3, 4)] for a, b in edge_list: g.add_edge(b, a, weight=1.0) cent = closeness(g) for n in range(0, n): print 'node', n print ' centrality:', cent[n] print ' out:', g.successors(n) print ' in:', g.predecessors(n) draw_with_centrality(g, layout=pos)
def closeness_example(): n = 5 g = nx.wheel_graph(n) pos = nx.spring_layout(g) g = nx.DiGraph() g.add_nodes_from(range(0,n)) edge_list = [(1,0),(2,1),(0,2),(0,3),(3,4)] for a,b in edge_list: g.add_edge(b,a,weight=1.0) cent = closeness(g) for n in range(0,n): print 'node',n print ' centrality:',cent[n] print ' out:',g.successors(n) print ' in:',g.predecessors(n) draw_with_centrality(g, layout=pos)
def wheelgraph(n): ''' this kind of graph has $n$ vertices, one of them a 'central' vertex. $n-1$ vertices form a ring, and the central vertex connects to each of the $n-1$ vertices to complete the spokes of the wheel. g = BaseGraph() for i in range(n): g.add_vertex(i) for a, b in zip(range(n), [n-1, *range(n-1)]): if a != b: g.make_edge(*sorted([a, b])) g.add_vertex(n) for i in range(n): if i != n: g.make_edge(i, n) return g ''' g = BaseGraph() g.load_from_nx(nx.wheel_graph(n)) return g
def make_graph(g_name, n): switcher = { "path": nx.path_graph(n), "complete": nx.complete_graph(n), "binomial tree": nx.binomial_tree(n), "circular ladder": nx.circular_ladder_graph(n), "cycle": nx.cycle_graph(n), "dorogovtsev": nx.dorogovtsev_goltsev_mendes_graph(n), "ladder": nx.ladder_graph(n), "star": nx.star_graph(n), "wheel": nx.wheel_graph(n), "margulis gabber galil": nx.margulis_gabber_galil_graph(n), "chordal cycle": nx.chordal_cycle_graph(n), "hypercube": nx.hypercube_graph(n), "mycielski": nx.mycielski_graph(n) } return switcher.get(g_name)
def test_dale_large(): """Test DALE on a larger matrix.""" size = 30 np.random.seed(777) a = np.random.randn(size, size) + np.eye(size, size) * 10.0 b = np.random.randn(size) x = np.linalg.solve(a, b) slices = standard_slices(size, 15, overlap=2) g = nx.wheel_graph(len(slices)) model = DaleModel(a, b, slices) network = StaticAgentsNetwork(model, g) model.attach_network(network) for _ in range(1500): model.step() for agent in model.schedule.agents: npt.assert_almost_equal(agent.sol, x)
def generate_graph(type, n): graph = nx.empty_graph() if GraphType.Path == type: graph = nx.path_graph(n) elif GraphType.Cycle == type: graph = nx.cycle_graph(n) elif GraphType.Star == type: graph = nx.star_graph(n) elif GraphType.Complete == type: graph = nx.complete_graph(n) elif GraphType.Hypercube == type: graph = nx.hypercube_graph(n) elif GraphType.Wheel == type: graph = nx.wheel_graph(n) elif GraphType.Random == type: graph = nx.fast_gnp_random_graph(n, 0.5) return graph
def demo_create_clustering_example(): g = nx.wheel_graph(6) pos = nx.spring_layout(g) g.add_edge(1, 3) #~ g.add_edge(1,4) g.add_edge(2, 4) #~ g.add_edge(2,5) #~ g.add_edge(3,1) #~ g.add_edge(3,5) g.remove_edge(4, 5) # remove node 0 edges #~ g.remove_edge(0,1) #~ g.remove_edge(0,2) #~ g.remove_edge(0,3) #~ g.remove_edge(0,4) #~ g.remove_edge(0,5) #~ print nx.clustering(g) #~ print nx.average_clustering(g) draw_with_centrality(g, layout=pos)
def demo_create_clustering_example(): g = nx.wheel_graph(6) pos = nx.spring_layout(g) g.add_edge(1,3) #~ g.add_edge(1,4) g.add_edge(2,4) #~ g.add_edge(2,5) #~ g.add_edge(3,1) #~ g.add_edge(3,5) g.remove_edge(4,5) # remove node 0 edges #~ g.remove_edge(0,1) #~ g.remove_edge(0,2) #~ g.remove_edge(0,3) #~ g.remove_edge(0,4) #~ g.remove_edge(0,5) #~ print nx.clustering(g) #~ print nx.average_clustering(g) draw_with_centrality(g, layout=pos)
def generate_custom_topologies(nbqbit: int) -> List[Topology]: """ Generates several custom topologies for a given number of qubits. Args: nbqbit (int): number of qubits in the topology Returns: List<Topology>: a list containing the topologies """ # We use NetworkX graph generator and the Topology class method from_nx to build topologies topology_list = [ Topology.from_nx(nx.path_graph(nbqbit)), Topology.from_nx(nx.complete_graph(nbqbit)), Topology.from_nx(nx.star_graph(nbqbit - 1)), Topology.from_nx(nx.wheel_graph(nbqbit)), Topology.from_nx(nx.cycle_graph(nbqbit)) ] return topology_list
def testJoin(self): # wheel test g = make_cycle(5) h = nx.Graph() h.add_node(0) f = join(g, h) expect = nx.wheel_graph(6) # expect a wheel self.assertEqual(expect.nodes(), f.nodes(), " Join: nodes failed on wheel test") self.assertEqual(nx.is_isomorphic(f, expect), True, " Join: edges failed on wheel test") # join of two trianges = K6 g = nx.complete_graph(3) h = nx.complete_graph(3) f = join(g, h) expect = nx.complete_graph(6) self.assertEqual(expect.nodes(), f.nodes(), "Join: nodes failed for K6 test") self.assertEqual(nx.is_isomorphic(f, expect), True, " Join: edges failed on wheel K6 test")
def test_complete_to_chordal_graph(self): fgrg = nx.fast_gnp_random_graph test_graphs = [ nx.barbell_graph(6, 2), nx.cycle_graph(15), nx.wheel_graph(20), nx.grid_graph([10, 4]), nx.ladder_graph(15), nx.star_graph(5), nx.bull_graph(), fgrg(20, 0.3, seed=1), ] for G in test_graphs: H, a = nx.complete_to_chordal_graph(G) assert nx.is_chordal(H) assert len(a) == H.number_of_nodes() if nx.is_chordal(G): assert G.number_of_edges() == H.number_of_edges() assert set(a.values()) == {0} else: assert len(set(a.values())) == H.number_of_nodes()
def test_wheel_graph_tie(self, dim, monkeypatch): """Test that output is correct for a wheel graph, whose largest cliques have dimension 3. The cliques always include the central spoke and two consecutive nodes in the outer wheel. Since the function uses randomness in node selection when there is a tie (which occurs in the case of the wheel graph), the resultant shrunk cliques are expected to be different each time ``clique_shrink`` is run. This function monkeypatches the ``np.random.shuffle`` call so that different nodes are removed during each run.""" graph = nx.wheel_graph(dim) subgraph = graph.nodes() # subgraph is the entire graph patch_random_shuffle_1 = functools.partial(patch_random_shuffle, reverse=False) patch_random_shuffle_2 = functools.partial(patch_random_shuffle, reverse=True) with monkeypatch.context() as m: m.setattr(np.random, "shuffle", patch_random_shuffle_1) c1 = resize.clique_shrink(subgraph, graph) with monkeypatch.context() as m: m.setattr(np.random, "shuffle", patch_random_shuffle_2) c2 = resize.clique_shrink(subgraph, graph) assert c1 != c2
def ___test_for_special_graphs(graphs, size): cycle = nx.cycle_graph(size) path = nx.path_graph(size) star = nx.star_graph(size) cycl_ladder = nx.circular_ladder_graph(size) ladder = nx.ladder_graph(size) wheel = nx.wheel_graph(size) cycle_found = False path_found = False star_found = False cycl_ladder_found = False ladder_found = False wheel_found = False # Check if we sampled on of this special graphs for g in graphs: if nx.is_isomorphic(g, cycle): cycle_found = True if nx.is_isomorphic(g, path): path_found = True if nx.is_isomorphic(g, star): star_found = True if nx.is_isomorphic(g, cycl_ladder): cycl_ladder_found = True if nx.is_isomorphic(g, ladder): ladder_found = True if nx.is_isomorphic(g, wheel): wheel_found = True print("Sampled cycle............................{}".format(cycle_found)) print("Sampled path.............................{}".format(path_found)) print("Sampled star.............................{}".format(star_found)) print("Sampled circular ladder..................{}".format( cycl_ladder_found)) print("Sampled ladder...........................{}".format(ladder_found)) print("Sampled wheel............................{}".format(wheel_found)) passed = cycle_found and path_found and star_found and cycl_ladder_found and ladder_found and wheel_found return passed
def create_graph(opts): n = int(opts[0]) return nx.wheel_graph(n)
import planarity import networkx as nx import matplotlib.pyplot as plt G=nx.wheel_graph(10) planarity.draw(G) plt.axis('off') plt.savefig('wheel.png')
nx.draw(a5, with_labels=True, front_weight='bold') # In[4]: #Solve the graph minimum vertex cover on the CPU from dimod.reference.samplers import ExactSolver import dwave_networkx as dnx sampler = ExactSolver() print(dnx.min_vertex_cover(a5, sampler)) # In[6]: #step 3 solve the graphs minimum vertex cover on the QPU from dwave.system.samplers import DWaveSampler from dwave.system.composites import EmbeddingComposite sampler = EmbeddingComposite(DWaveSampler()) print(dnx.min_vertex_cover(a5, sampler)) # In[7]: #Step 4 try with bigger graph w5 = nx.wheel_graph(5) plt.subplot(121) nx.draw(w5, with_labels=True, font_weights='bold') print(dnx.min_vertex_cover(w5, sampler))
n = 6 hypercube_n = 4 m = 6 r = 2 h = 3 dim = [2, 3] # left out dorogovtsev_goltsev_mendes_graph and null_graph graphs = [ ("balanced_tree", nx.balanced_tree(r, h)), ("barbell_graph", nx.barbell_graph(n, m)), ("complete_graph", nx.complete_graph(n)), ("complete_bipartite_graph", nx.complete_bipartite_graph(n, m)), ("circular_ladder_graph", nx.circular_ladder_graph(n)), ("cycle_graph", nx.cycle_graph(n)), ("empty_graph", nx.empty_graph(n)), ("grid_2d_graph", nx.grid_2d_graph(m, n)), ("grid_graph", nx.grid_graph(dim)), ("hypercube_graph", nx.hypercube_graph(hypercube_n)), ("ladder_graph", nx.ladder_graph(n)), ("lollipop_graph", nx.lollipop_graph(m, n)), ("path_graph", nx.path_graph(n)), ("star_graph", nx.star_graph(n)), ("trivial_graph", nx.trivial_graph()), ("wheel_graph", nx.wheel_graph(n)), ] plot_multigraph(graphs, 4, 4, node_size=50) plt.savefig("graphs/classic.png")
if not os.path.exists(args.output): os.makedirs(args.output) with open(args.output + '/output.csv', 'w') as output: helper(output, nx.balanced_tree(2, 5), "balanced_tree") # branching factor, height helper(output, nx.barbell_graph(50, 50), "barbell_graph") helper(output, nx.complete_graph(50), "complete_graph") helper(output, nx.complete_bipartite_graph(50, 50), "complete_bipartite_graph") helper(output, nx.circular_ladder_graph(50), "circular_ladder_graph") helper(output, nx.cycle_graph(50), "cycle_graph") helper(output, nx.dorogovtsev_goltsev_mendes_graph(5), "dorogovtsev_goltsev_mendes_graph") helper(output, nx.empty_graph(50), "empty_graph") helper(output, nx.grid_2d_graph(5, 20), "grid_2d_graph") helper(output, nx.grid_graph([2, 3]), "grid_graph") helper(output, nx.hypercube_graph(3), "hypercube_graph") helper(output, nx.ladder_graph(50), "ladder_graph") helper(output, nx.lollipop_graph(5, 20), "lollipop_graph") helper(output, nx.path_graph(50), "path_graph") helper(output, nx.star_graph(50), "star_graph") helper(output, nx.trivial_graph(), "trivial_graph") helper(output, nx.wheel_graph(50), "wheel_graph") helper(output, nx.random_regular_graph(1, 50, 678995), "random_regular_graph_1") helper(output, nx.random_regular_graph(3, 50, 683559), "random_regular_graph_3") helper(output, nx.random_regular_graph(5, 50, 515871), "random_regular_graph_5") helper(output, nx.random_regular_graph(8, 50, 243579), "random_regular_graph_8") helper(output, nx.random_regular_graph(13, 50, 568324), "random_regular_graph_13") helper(output, nx.diamond_graph(), "diamond_graph")
#Cycles from C10 to C100 for i in range(10,110,10): C = nx.cycle_graph(i) name = "C_"+str(i) printEdgeList(C,name) #Complete graphs K10 to K100 for i in range(10,110,10): K = nx.complete_graph(i) name = "K_"+str(i) printEdgeList(K,name) #Wheel graph W10 to W100 for i in range(10,110,10): W = nx.wheel_graph(i) name = "W_"+str(i) printEdgeList(W,name) #Random graphs of size 10 to 100, #generated with Erdos Renyi model G(n,p) #(https://en.wikipedia.org/wiki/Erd%C5%91s%E2%80%93R%C3%A9nyi_model) for p in [x/10.0 for x in range(2, 9)]: print(p) for i in range(10,110,10): R = nx.fast_gnp_random_graph(i,p) name = "R("+str(i)+", "+str(p)+")" printEdgeList(R,name)
import networkx G = networkx.wheel_graph(100)
def test131_wheel_graph(self): """ Large wheel graph. """ g = nx.wheel_graph(101) mate1 = mv.max_cardinality_matching( g ) mate2 = nx.max_weight_matching( g, True ) self.assertEqual( len(mate1), len(mate2) )