def AlmostTree(n,m): t=m-n+1 vertices_in_triangles=3*t edges_in_triangles=3*t if vertices_in_triangles<=n: G=nx.star_graph(n-2*t-1) vertex_index=n-2*t for triangle_index in range(t): G.add_edge((triangle_index+1)%(n-2*t),vertex_index) G.add_edge((triangle_index+1)%(n-2*t),vertex_index+1) G.add_edge(vertex_index,vertex_index+1) vertex_index=vertex_index+2 return G if vertices_in_triangles>n: g=3*t-n+1 #Number of merged triangles f=t-g #Number of free triangles G=nx.star_graph(f+2*g) star_index=0 for merged_index in range(g): star_index=star_index+2 G.add_edge(star_index,star_index-1) vertex_index=f+2*g+1 for triangle_index in range(f): star_index=star_index+1 G.add_edge(star_index,vertex_index) G.add_edge(star_index,vertex_index+1) G.add_edge(vertex_index,vertex_index+1) vertex_index=vertex_index+2 return G
def test_star(): G = nx.star_graph(3) _check_augmentations(G) G = nx.star_graph(5) _check_augmentations(G) G = nx.star_graph(10) _check_augmentations(G)
def instance7_2000(): """ Returns a 3-element tuple (G,T,leaves) where G is the graph T is the optimal solution and leaves is the number of leaves in the optimal solution. The graph is constructed by creating 4 stars with 90 nodes and adding 10 random nodes. """ #create a star of 4 stars starList = [] starList.append(nx.star_graph(22)) starList.append(nx.star_graph(21)) starList.append(nx.star_graph(21)) starList.append(nx.star_graph(21)) T = nx.Graph() for star in starList: T = nx.disjoint_union(T,star) T.add_node(89) T.add_edges_from([(89,0),(89,23),(89,67),(89,45)]) #add 10 more nodes with random edges T.add_nodes_from(range(90,101)) for i in range(90,101): x = int(random()*5371)%90 T.add_edge(i,x) #count the number of leaves leaves = list(T.degree(T.nodes()).values()).count(1) #randomize the label of nodes for n in T.nodes(): new = n + int(random()*2000) while(new in T.nodes()): new = n + int(random()*2000) T = nx.relabel_nodes(T,{n:new}) G = nx.Graph() G.add_nodes_from(T.nodes()) G.add_edges_from(T.edges()) #code for 2000 edges #add random edges while(G.number_of_edges() < 2000): x = int(random()*15897)%100 y = int(random()*17691)%100 G.add_edge(G.nodes()[x],G.nodes()[y]) T = one_edge_swap(G) return (G,T)
def test_ego(self): G=nx.star_graph(3) H=nx.ego_graph(G,0) assert_true(nx.is_isomorphic(G,H)) G.add_edge(1,11) G.add_edge(2,22) G.add_edge(3,33) H=nx.ego_graph(G,0) assert_true(nx.is_isomorphic(nx.star_graph(3),H)) G=nx.path_graph(3) H=nx.ego_graph(G,0) assert_equal(H.edges(), [(0, 1)])
def test_star_like(self): # star-like G=nx.star_graph(2) G.add_edge(1,2) assert_almost_equal(sb(G),0.843,places=3) G=nx.star_graph(3) G.add_edge(1,2) assert_almost_equal(sb(G),0.871,places=3) G=nx.star_graph(4) G.add_edge(1,2) assert_almost_equal(sb(G),0.890,places=3)
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 test_non_neighbors(self): graph = nx.complete_graph(100) pop = random.sample(list(graph), 1) nbors = list(nx.non_neighbors(graph, pop[0])) # should be all the other vertices in the graph assert_equal(len(nbors), 0) graph = nx.path_graph(100) node = random.sample(list(graph), 1)[0] nbors = list(nx.non_neighbors(graph, node)) # should be all the other vertices in the graph if node != 0 and node != 99: assert_equal(len(nbors), 97) else: assert_equal(len(nbors), 98) # create a star graph with 99 outer nodes graph = nx.star_graph(99) nbors = list(nx.non_neighbors(graph, 0)) assert_equal(len(nbors), 0) # disconnected graph graph = nx.Graph() graph.add_nodes_from(range(10)) nbors = list(nx.non_neighbors(graph, 0)) assert_equal(len(nbors), 9)
def test_non_edges(self): # All possible edges exist graph = nx.complete_graph(5) nedges = list(nx.non_edges(graph)) assert_equal(len(nedges), 0) graph = nx.path_graph(4) expected = [(0, 2), (0, 3), (1, 3)] nedges = list(nx.non_edges(graph)) for (u, v) in expected: assert_true((u, v) in nedges or (v, u) in nedges) graph = nx.star_graph(4) expected = [(1, 2), (1, 3), (1, 4), (2, 3), (2, 4), (3, 4)] nedges = list(nx.non_edges(graph)) for (u, v) in expected: assert_true((u, v) in nedges or (v, u) in nedges) # Directed graphs graph = nx.DiGraph() graph.add_edges_from([(0, 2), (2, 0), (2, 1)]) expected = [(0, 1), (1, 0), (1, 2)] nedges = list(nx.non_edges(graph)) for e in expected: assert_true(e in nedges)
def MinImpedanceGraphFinder(number_of_vertices,number_of_edges): if number_of_edges<number_of_vertices-1: print 'Too few edges. The graph will be disconnected. Exiting...' return -1 if number_of_edges>(number_of_vertices-1)*number_of_vertices/2.0: print 'Too many edges. Such a graph cannot exist. Exiting...' return -1 G=nx.star_graph(number_of_vertices-1) remaining_edges=number_of_edges-number_of_vertices+1 for current_vertex in range(2,number_of_vertices): if remaining_edges<=0:break G.add_edge(1,current_vertex) remaining_edges-=1 while remaining_edges>0: for first_vertex in range(2,number_of_vertices): if remaining_edges<=0:break for second_vertex in range(first_vertex+1,number_of_vertices): if remaining_edges<=0:break if second_vertex not in G.neighbors(first_vertex): G.add_edge(first_vertex,second_vertex) remaining_edges-=1 return G
def test_ego(self): G = nx.star_graph(3) H = nx.ego_graph(G, 0) assert_true(nx.is_isomorphic(G, H)) G.add_edge(1, 11) G.add_edge(2, 22) G.add_edge(3, 33) H = nx.ego_graph(G, 0) assert_true(nx.is_isomorphic(nx.star_graph(3), H)) G = nx.path_graph(3) H = nx.ego_graph(G, 0) assert_edges_equal(H.edges(), [(0, 1)]) H = nx.ego_graph(G, 0, undirected=True) assert_edges_equal(H.edges(), [(0, 1)]) H = nx.ego_graph(G, 0, center=False) assert_edges_equal(H.edges(), [])
def star_topology(n): """ Return a star (a.k.a hub-and-spoke) topology of :math:`n+1` nodes The root (hub) node has id 0 while all leaf (spoke) nodes have id :math:`(1, n+1)`. Each node has the attribute type which can either be *root* (for node 0) or *leaf* for all other nodes Parameters ---------- n : int The number of leaf nodes Returns ------- topology : A Topology object """ if not isinstance(n, int): raise TypeError('n argument must be of int type') if n < 1: raise ValueError('n argument must be a positive integer') G = Topology(nx.star_graph(n)) G.name = "star_topology(%d)" % (n) G.graph['type'] = 'star' G.node[0]['type'] = 'root' for v in range(1, n + 1): G.node[v]['type'] = 'leaf' 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
def tuning(hemi='rh', roi='sts', cluster=4): df = pandas.read_csv('../analyses/tuning_curves_sts.csv') df = df[df.cluster==cluster] np.random.seed(0) for g, genre in enumerate(df.genre.unique()): sel = df[df.genre==genre] G = nx.star_graph(len(sel)) pos = nx.spring_layout(G) colors = np.sign(sel.weight).astype(int).tolist() node_size = 2000*np.abs(sel.weight) node_size = [np.mean(node_size)] + node_size.tolist() cmap = sns.color_palette('Set2', 2) cond = [np.mean(sel.weight)] + sel.weight.tolist() colors = [cmap[0] if c<0 else cmap[1] for c in cond] labels = dict([(k+1,v) for k,v in enumerate(sel.style)]) labels[0] = genre sns.plt.subplot(2,3,g+1) nx.draw(G, pos, node_color=colors, edge_color='gray', width=1, with_labels=True, node_size=node_size, labels=labels) sns.plt.savefig('../images/%s_%s_%s.svg' % (hemi, roi, cluster)) sns.plt.show()
def MinDistanceGraphFinder(number_of_vertices,number_of_edges): if number_of_edges<number_of_vertices-1: print 'Too few edges. The graph will be disconnected. Exiting...' return -1 if number_of_edges>(number_of_vertices-1)*number_of_vertices/2.0: print 'Too many edges. Such a graph cannot exist. Exiting...' return -1 if number_of_edges>(number_of_vertices-2)*(number_of_vertices-1)/2.0: OutputGraph=nx.gnm_random_graph(number_of_vertices,number_of_edges) return OutputGraph G=nx.star_graph(number_of_vertices-1) VertexList=G.nodes() remaining_edges=number_of_edges-number_of_vertices+1 while remaining_edges>0: first_vertex=random.choice(VertexList) second_vertex=random.choice(VertexList) if first_vertex==second_vertex:continue if (first_vertex,second_vertex) in G.edges():continue if (second_vertex,first_vertex) in G.edges():continue G.add_edge(first_vertex,second_vertex) remaining_edges-=1 OutputGraph=G.copy() return OutputGraph
def test_unweighted_undirected(self): # create a simple star graph size = 50 sg = nx.star_graph(size) cover = min_weighted_vertex_cover(sg) assert_equals(2, len(cover)) ok_(is_cover(sg, cover))
def test_min_vertex_cover(self): # create a simple star graph size = 50 sg = nx.star_graph(size) cover = a.min_weighted_vertex_cover(sg) assert_equals(2, len(cover)) for u, v in sg.edges(): ok_((u in cover or v in cover), "Node node covered!") wg = nx.Graph() wg.add_node(0, weight=10) wg.add_node(1, weight=1) wg.add_node(2, weight=1) wg.add_node(3, weight=1) wg.add_node(4, weight=1) wg.add_edge(0, 1) wg.add_edge(0, 2) wg.add_edge(0, 3) wg.add_edge(0, 4) wg.add_edge(1,2) wg.add_edge(2,3) wg.add_edge(3,4) wg.add_edge(4,1) cover = a.min_weighted_vertex_cover(wg, weight="weight") csum = sum(wg.node[node]["weight"] for node in cover) assert_equals(4, csum) for u, v in wg.edges(): ok_((u in cover or v in cover), "Node node covered!")
def get_graph(objects, properties): graph_type = properties['graph_type'] n = len(objects)-1 if 'num_nodes_to_attach' in properties.keys(): k = properties['num_nodes_to_attach'] else: k = 3 r = properties['connection_probability'] tries = 0 while(True): if graph_type == 'random': x = nx.fast_gnp_random_graph(n,r) elif graph_type == 'erdos_renyi_graph': x = nx.erdos_renyi_graph(n,r) elif graph_type == 'watts_strogatz_graph': x = nx.watts_strogatz_graph(n, k, r) elif graph_type == 'newman_watts_strogatz_graph': x = nx.newman_watts_strogatz_graph(n, k, r) elif graph_type == 'barabasi_albert_graph': x = nx.barabasi_albert_graph(n, k, r) elif graph_type == 'powerlaw_cluster_graph': x = nx.powerlaw_cluster_graph(n, k, r) elif graph_type == 'cycle_graph': x = nx.cycle_graph(n) else: ##Star by default x = nx.star_graph(len(objects)-1) tries += 1 cc_conn = nx.connected_components(x) if len(cc_conn) == 1 or tries > 5: ##best effort to create a connected graph! break return x, cc_conn
def test_star_graph(): G = nx.star_graph(3) # all modes are the same answer = {0: 0, 1: 1, 2: 1, 3: 1} assert_equal(bipartite.clustering(G, mode='dot'), answer) assert_equal(bipartite.clustering(G, mode='min'), answer) assert_equal(bipartite.clustering(G, mode='max'), answer)
def test_star_graph(): G = nx.star_graph(3) # all modes are the same answer = {0: 0, 1: 1, 2: 1, 3: 1} assert_equal(nx.bipartite_clustering(G, mode="dot"), answer) assert_equal(nx.bipartite_clustering(G, mode="min"), answer) assert_equal(nx.bipartite_clustering(G, mode="max"), answer)
def calc_star_uptime(self, n, link_fail): '''Calc star uptime. NOTE: n is the number of nodes.''' # Correct for NetworkX, which adds one to n. g = nx.star_graph(n - 1) # Node 0 is the center of the star. edges = g.number_of_edges() nodes = g.number_of_nodes() paths = nx.single_source_shortest_path(g, g.nodes()[1]) used = flatten(paths) sssp_edges = used.number_of_edges() if sssp_edges != g.number_of_edges(): raise Exception("edge not on sssp for star graph") # consider those times when a link failed: # first, consider failure on outside of graph exp_uptime_outer = link_fail * edges * ((float(edges - 1) / edges) * float(edges) / nodes + \ (float(1) / edges) * float(1) / nodes) exp_uptime_outer += (1.0 - (link_fail * sssp_edges)) * 1.0 # consider only the hub as a controller: exp_uptime_inner = link_fail * edges * ((float(edges) / edges) * float(edges) / nodes) exp_uptime_inner += (1.0 - (link_fail * edges)) * 1.0 # merge: exp_uptime_weighted = float(edges * exp_uptime_outer + 1 * exp_uptime_inner) / nodes return exp_uptime_weighted
def colormap(): G=nx.star_graph(20) pos=nx.spring_layout(G) colors=range(20) nx.draw(G,pos,node_color='#A0CBE2',edge_color=colors,width=4,edge_cmap=plt.cm.Blues,with_labels=False) #plt.savefig("edge_colormap.png") # save as png plt.show() # display
def test_degree_barrat(self): G=nx.star_graph(5) G.add_edges_from([(5,6),(5,7),(5,8),(5,9)]) G[0][5]['weight']=5 nd = nx.average_neighbor_degree(G)[5] assert_equal(nd,1.8) nd = nx.average_neighbor_degree(G,weight='weight')[5] assert_almost_equal(nd,3.222222,places=5)
def test_S4(self): G = nx.star_graph(4) G.nodes[0]['community'] = 1 G.nodes[1]['community'] = 1 G.nodes[2]['community'] = 1 G.nodes[3]['community'] = 0 G.nodes[4]['community'] = 0 self.test(G, [(1, 2)], [(1, 2, 1 / self.delta)])
def test_S4(self): G = nx.star_graph(4) G.node[0]['community'] = 1 G.node[1]['community'] = 1 G.node[2]['community'] = 1 G.node[3]['community'] = 0 G.node[4]['community'] = 0 self.test(G, 1, 2, 2)
def run_star_test(self, n, link_fail, node_fail, max_fail, hard_coded_uptime = None): # Return the Star graph with n nodes g = nx.star_graph(n - 1) exp_uptime = self.calc_star_uptime(n, link_fail) node_fail = 0 # if hard-coded "test bootstrap uptime" defined, verify w/eqn. if hard_coded_uptime: self.assertAlmostEqual(exp_uptime, hard_coded_uptime) self.run_test(g, link_fail, node_fail, max_fail, sssp_conn, exp_uptime)
def instance1_1000(): #make a star of 4 24-node stars A = nx.star_graph(24) B = nx.star_graph(24) C = nx.star_graph(24) D = nx.star_graph(23) T = nx.disjoint_union(A,B) T = nx.disjoint_union(T,C) T = nx.disjoint_union(T,D) T.add_node(99) T.add_edges_from([(0,99),(25,99),(50,99),(75,99)]) #randomize the labels of nodes # for n in T.nodes(): # new = n + int(random()*10000) # while(new in T.nodes()): # new = n + int(random()*10000) n = range(100) new = range(100) r.shuffle(new) T = nx.relabel_nodes(T,dict(zip(n,new))) # T is optimal solution # G is the graph G = nx.Graph() G.add_nodes_from(T.nodes()) G.add_edges_from(T.edges()) # add random edges for i in range(1000): x = int(random()*15897)%100 y = int(random()*17691)%100 G.add_edge(G.nodes()[x],G.nodes()[y]) for e in G.edges(): if e[0] == e[1]: G.remove_edge(e[0],e[1]) return (G,T)
def test_star(self): graph=nx.star_graph(10) F = TseitinFormula(graph) self.assertEquals(len(list(F.variables())),10) self.assertEquals(len(list(F.clauses())),2**9+10) self.assertEquals(len([C for C in F.clauses() if len(C)==10]),2**9) self.assertEquals(len([C for C in F.clauses() if len(C)==1]),10) for C in F.clauses(): if len(C)==1: self.assertFalse(C[0][0])
def test_degree_barrat(self): G=nx.star_graph(5) G.add_edges_from([(5,6),(5,7),(5,8),(5,9)]) G[0][5]['weight']=5 nd = nx.average_degree_connectivity(G)[5] assert_equal(nd,1.8) nd = nx.average_degree_connectivity(G,weighted=True)[5] assert_almost_equal(nd,3.222222,places=5) nd = nx.k_nearest_neighbors(G,weighted=True)[5] assert_almost_equal(nd,3.222222,places=5)
def main(): graphs = { 'star_graph': nx.star_graph(1000), 'ba_graph': nx.barabasi_albert_graph(1000, 2), 'watts_strogatz': nx.watts_strogatz_graph(1000, 4, p=0.3), 'random_regular': nx.random_regular_graph(4, 1000), } folder = 'resources/' for name, graph in graphs.iteritems(): create_graph_file(graph, folder + name)
def instance3(): lst = [] count = 0 size = [] leaves = 0 while(count < 100): x = int(random()*100)%10 if(count + x + 1 > 100): break lst.append(nx.star_graph(x)) count = count + x + 1 r = 100 - 1 - count lst.append(nx.star_graph(r-1)) L = nx.Graph() for item in lst: leaves += nx.number_of_nodes(item)-1 size.append(nx.number_of_nodes(item)) L = nx.disjoint_union(L,item) L.add_node(99) totaling = 0 for item in size: L.add_edge(99, totaling) totaling += item for i in range(1500): x = int(random()*100) y = int(random()*100) L.add_edge(x,y) for n in L.nodes(): new = n + 100 + int(random()*1000) while(new in L.nodes()): new = n + 100 + int(random()*1000) L = nx.relabel_nodes(L,{n:new}) print("Number of nodes in each star: " + str(size)) print("Total num of leaves: " + str(leaves)) print("Total num of edges: " + str(L.number_of_edges())) print("ratio of leaves/edges: " + str(float(leaves)/L.number_of_edges())) return L
def test_S4(self): G = nx.star_graph(4) self.test(G, [(1, 2)], [(1, 2, 0.25)])
def mindrevolihalisod(n): return nx.star_graph(n - 1)
def test_S4(self): G = nx.star_graph(4) self.test(G, [(1, 2)], [(1, 2, 1.75)], alpha=0.5)
def test_result_star_graph_50(self): assert (calc_and_compare(NX.star_graph(50)))
def test_charge_odd(self): graph = nx.star_graph(10) F = TseitinFormula(graph, [1] * 11) for C in F: if len(C) == 1: self.assertTrue(C[0][0])
def test_charge_first(self): graph = nx.star_graph(10) F = TseitinFormula(graph, [1]) G = TseitinFormula(graph) self.assertCnfEqual(F, G)
def test_is_separating_set(): for i in [5, 10, 15]: G = nx.star_graph(i) max_degree_node = max(G, key=G.degree) assert _is_separating_set(G, {max_degree_node})
import maxcutpy.graphcut as gc import maxcutpy.graphtest as gt import pdb __license__ = "GPL" if __name__ == '__main__': seed = 123 # most used graphs G1 = nx.erdos_renyi_graph(n=24, p=0.3, seed=seed) # some cool graphs G2 = nx.star_graph(20) G3 = nx.path_graph(30) G4 = nx.petersen_graph() G5 = nx.dodecahedral_graph() G6 = nx.house_graph() G7 = nx.moebius_kantor_graph() G8 = nx.barabasi_albert_graph(5, 4) G9 = nx.heawood_graph() G10 = nx.icosahedral_graph() G11 = nx.sedgewick_maze_graph() G12 = nx.havel_hakimi_graph([1, 1]) G13 = nx.complete_graph(20) G14 = nx.bull_graph() G = G1 # choose a graph from the list
def test_metadata_json_load_logic(): qubits = cirq.LineQubit.range(4) graph = nx.star_graph(3) metadata = cirq.DeviceMetadata(qubits, graph) str_rep = cirq.to_json(metadata) assert metadata == cirq.read_json(json_text=str_rep)
import networkx as nx import plotly.graph_objs as go G = nx.star_graph(100, create_using=None) nx.set_node_attributes(G, 'a', 'TimeClass') H = nx.star_graph(100, create_using=None) nx.set_node_attributes(H, 'b', 'TimeClass') def mapping(x): return x+101 H = nx.relabel_nodes(H, mapping) G = nx.compose(G, H) p = nx.spring_layout(G, dim=2) for key in p: G.node[key]['pos'] = p[key] edge_trace = go.Scatter( x=[], y=[], line=dict(width=0.5, color= '#888'), hoverinfo='none', mode='lines') for edge in G.edges(): x0, y0 = G.node[edge[0]]['pos'] x1, y1 = G.node[edge[1]]['pos'] edge_trace['x'] += tuple([x0, x1, None]) edge_trace['y'] += tuple([y0, y1, None]) # node traces node_trace = go.Scatter( x=[],
def degree_centrality(G): centrality = {} # empty dictionary n=len(G)-1.0 # forces floating point for n for v in G: centrality[v]=G.degree(v)/n return centrality if __name__=='__main__': import networkx as nx G=nx.star_graph(3) for v,c in degree_centrality(G).items(): print v,c
def test_single_edge_matching(self): # In the star graph, any maximal matching has just one edge. G = nx.star_graph(5) matching = nx.maximal_matching(G) assert 1 == len(matching) assert nx.is_maximal_matching(G, matching)
def generate_edges(self, topology): ## Prepare RNG seed for edge generation algorithms if 'seed' in self._properties: SEED = self._properties['seed'] else: SEED = None topology = self._properties['topology'] self._log('Generating edges from [ %s ]' % topology) ## Initialize networkx graph based on user's preference of directed/not if self._properties['directed']: self._graph = nx.DiGraph() else: self._graph = nx.Graph() self._log('Setting directed=%s' % self._properties['directed']) ## Generate nodes self._graph.add_nodes_from(range(self._properties['n'])) self._log('Created %d nodes.' % self._properties['n']) ## Case for blank graph. if topology == '': return ## Generate a set of edges based on the topology requested if topology == 'random': self._log('Constructing Erdos Renyi random graph.') edges = nx.erdos_renyi_graph(self._graph.number_of_nodes(), self._properties['saturation'], directed=self._properties['directed'], seed=SEED).edges() elif topology == 'scale free': self._log('Constructing scale free graph.') edges = nx.scale_free_graph(self._graph.number_of_nodes(), seed=SEED).edges() elif topology == 'small world': self._log('Constructing small world graph.') n = self._graph.number_of_nodes() sat = self._properties['saturation'] edges = nx.watts_strogatz_graph(n, int(sat * n), self._properties['rewire'], seed=SEED).edges() elif topology == 'star': self._log('Constructing star graph.') n = self._graph.number_of_nodes() edges = nx.star_graph(n).edges() elif topology == 'complete': self._log('Constructing complete graph.') n = self._graph.number_of_nodes() edges = nx.complete_graph(n).edges() elif topology == 'cycle': self._log('Constructing complete graph.') n = self._graph.number_of_nodes() edges = nx.cycle_graph(n).edges() ## Add generated edges to graph structure for e in edges: self._graph.add_edge(e[0], e[1]) ## Add opposite edges if network should be symmetric if self._properties['symmetric']: self._graph.add_edge(e[1], e[0])
def test_S4(self): G = nx.star_graph(4) self.test(G, [(0, 2)], [(0, 2, 4)])
def test_metadata(): qubits = cirq.LineQubit.range(4) graph = nx.star_graph(3) metadata = cirq.DeviceMetadata(qubits, graph) assert metadata.qubit_set == frozenset(qubits) assert metadata.nx_graph == graph
def main(): global action_history, shock_history, mean_weight_history, \ percent_change_history argv = sys.argv argc = len(argv) #just give the num_nodes value--nd # num_nodes = int(60) # prob_of_initial = float(0.3) # If the user has specified parameters using command line variables, parse # them if (argc == 3): num_nodes, prob_of_initial = list(map(float, argv[1:])) num_nodes = int(num_nodes) # If the user has provided a YAML file, read it. elif (argc == 2): file_name = argv[1] try: with open(file_name, "r") as yml_file: try: config_file = yaml.load(yml_file) num_nodes = int(config_file["num_nodes"]) #test--nd print("imhere") prob_of_initial = config_file["prob_of_initial"] except KeyError as e: raise KeyError( ("Expected variable {} in config file {}, " + "but it wasn't found.").format(e, config_file)) except Exception as error: print("Reading error: {}".format(error)) quit() else: print("Error: Invalid number of arguments. Correct ordering is:") print("catastrophe_game.py <config.file>") print("or") print("catastrophe_game.py <num_nodes> <prob_of_initial>") quit() print("[GAME SETTINGS]") print("Number of nodes: {}".format(num_nodes)) print("Probability of initial adopters: {}".format(prob_of_initial)) # generate the random networks erdos_renyi_graph = nx.erdos_renyi_graph(num_nodes, BARABASI_EDGE_FACTOR / num_nodes).to_directed() barabasi_albert_graph = nx.barabasi_albert_graph( num_nodes, BARABASI_EDGE_FACTOR).to_directed() watts_strogatz_graph = nx.watts_strogatz_graph(num_nodes, BARABASI_EDGE_FACTOR, 0).to_directed() star_graph = nx.star_graph(num_nodes - 1).to_directed() graphs = [ erdos_renyi_graph, barabasi_albert_graph, watts_strogatz_graph, star_graph ] # graphs = [star_graph, watts_strogatz_graph] # generate the weights for graph_index, graph in enumerate(graphs): for node in range(num_nodes): in_degree = graph.in_degree(node) if not in_degree: continue total_weight = np.random.uniform(0, 1, 1) edge_weights = np.random.uniform(0, 1, in_degree) edge_weights_sum = sum(edge_weights) # print("Total weight: {}".format(total_weight)) # print("Edge_weights: {}".format(edge_weights)) # print("Edge_weights_sum: {}".format(edge_weights_sum)) # for weights in edge_weights: # weights = weights/edge_weights_sum*total_weight edge_weights = edge_weights / edge_weights_sum * total_weight # print("Normalized edge_weights: {}".format(edge_weights)) # print("Normaliezd edge_weights_sum: {}".format(sum(edge_weights))) # print("\n\n\n\n\n") # create random weights # dirichlet: random numbers with a given sum # edge_weights = np.random.dirichlet(np.ones(in_degree)) # edge_weights[-1] = np.random.uniform(0, edge_weights[-1]) # assign weight to each incoming edge for i, neighbor in enumerate(graph.predecessors(node)): graph[node][neighbor]["weight"] = edge_weights[i] print("Number of edges for {}: {}".format( GRAPH_TOPOLOGY_NAME[graph_index], len(graph.edges()))) print("[SUMMARY]") # Create an initial state by randomly assigning actions to each player. init_state = list(np.random.binomial(1, prob_of_initial, num_nodes)) print("Number of initial adopters for both graphs: {}".format( init_state.count(1))) # my attempt to make the code work -- Sally[1] # thresholds is a [list] of doubles taken from a uniform distribution [0,1) thresholds = np.random.uniform(0, 1, num_nodes) for i in range(0, len(init_state)): if (init_state[i] == 1): thresholds[i] = -10 # should we fix shock to both graphs, as well as its effect thresholds_array = [] new_thresholds = list(thresholds) shock_history.append(0) # pre-generate a shock value list and its effect on thresholds for all the # networks for i in range(MAX_ITERATION): new_thresholds = shock_effect(new_thresholds) thresholds_array.append(new_thresholds) # print("The new threshold generated is: ") # print(new_thresholds) # print() #print("the thresholds after the shock are:", thresholds_array) print("\n\n\nShock History:\n") print(shock_history) # run the experiment on all of the networks for i, graph in enumerate(graphs): curr_time = 0 reset_data() prev_state = [] curr_state = list(init_state) # init data action_history.append(curr_state) mean_weight_history.append(compute_mean_weight(curr_state, graph)) percent_change_history.append(0) # no change at initial state while (curr_time < MAX_ITERATION): prev_state = list(curr_state) curr_state = find_equilibrium(curr_state, graph, thresholds) percent_change_history.append( calculate_proportion_change(prev_state, curr_state)) # update time curr_time += 1 # introduce the shock, by setting the threshold to the pre-computed # values -- this makes sure that all networks are experiencing the # same shock if (curr_time < MAX_ITERATION): thresholds = thresholds_array[curr_time] print("Number of final adopters for {} graph: {}".format(\ GRAPH_TOPOLOGY_NAME[i], curr_state.count(1))) iteration_history.append(0) save_records(i) #print the percentage of adopters--nd #print("Percentage of final adopters for {} graph: {}".format(\ # GRAPH_TOPOLOGY_NAME[i], (curr_state.count(1)-num_nodes*0.1)\ # /(num_nodes*0.9)) #) print("Percentage of final adopters for {} graph: {}".format(\ GRAPH_TOPOLOGY_NAME[i], (curr_state.count(1)/num_nodes))) print("thresholds after shock:", thresholds_array[len(thresholds_array) - 1]) out_range = 0 import matplotlib.pyplot as plt #plt.scatter(thresholds, curr_state) plt.plot(thresholds, curr_state) plt.xlabel("threshold values") plt.ylabel("final state") plt.show()
def test_complete_bipartite_graph(self): G = complete_bipartite_graph(0, 0) assert nx.is_isomorphic(G, nx.null_graph()) for i in [1, 5]: G = complete_bipartite_graph(i, 0) assert nx.is_isomorphic(G, nx.empty_graph(i)) G = complete_bipartite_graph(0, i) assert nx.is_isomorphic(G, nx.empty_graph(i)) G = complete_bipartite_graph(2, 2) assert nx.is_isomorphic(G, nx.cycle_graph(4)) G = complete_bipartite_graph(1, 5) assert nx.is_isomorphic(G, nx.star_graph(5)) G = complete_bipartite_graph(5, 1) assert nx.is_isomorphic(G, nx.star_graph(5)) # complete_bipartite_graph(m1,m2) is a connected graph with # m1+m2 nodes and m1*m2 edges for m1, m2 in [(5, 11), (7, 3)]: G = complete_bipartite_graph(m1, m2) assert nx.number_of_nodes(G) == m1 + m2 assert nx.number_of_edges(G) == m1 * m2 pytest.raises(nx.NetworkXError, complete_bipartite_graph, 7, 3, create_using=nx.DiGraph) pytest.raises(nx.NetworkXError, complete_bipartite_graph, 7, 3, create_using=nx.DiGraph) pytest.raises(nx.NetworkXError, complete_bipartite_graph, 7, 3, create_using=nx.MultiDiGraph) mG = complete_bipartite_graph(7, 3, create_using=nx.MultiGraph) assert mG.is_multigraph() assert sorted(mG.edges()) == sorted(G.edges()) mG = complete_bipartite_graph(7, 3, create_using=nx.MultiGraph) assert mG.is_multigraph() assert sorted(mG.edges()) == sorted(G.edges()) mG = complete_bipartite_graph(7, 3) # default to Graph assert sorted(mG.edges()) == sorted(G.edges()) assert not mG.is_multigraph() assert not mG.is_directed() # specify nodes rather than number of nodes G = complete_bipartite_graph([1, 2], ['a', 'b']) has_edges = G.has_edge(1, 'a') & G.has_edge(1, 'b') &\ G.has_edge(2, 'a') & G.has_edge(2, 'b') assert has_edges assert G.size() == 4
def test_undirected_unweighted_star(self): G = nx.star_graph(2) grc = nx.local_reaching_centrality assert grc(G, 1, weight=None, normalized=False) == 0.75
def starGraph(no_node): return nx.star_graph(no_node)
print("doing ring100") G = nx.cycle_graph(101) pickle_path = '../data/ring_100.pkl' simulate_different_request_rates(G, pickle_path, network_type='ring') print("done ring100") # Generate data for 100 node line print("doing line100") G = nx.grid_graph((100, )) pickle_path = '../data/line_100.pkl' simulate_different_request_rates(G, pickle_path, network_type='line') print("done line100") # Generate data for 100 node star print("doing star100") G = nx.star_graph(n=100) pickle_path = '../data/star_100.pkl' simulate_different_request_rates(G, pickle_path, network_type='star') print("done star100") # Generate data for 100 node grid print("doing grid100") G = nx.grid_2d_graph(10, 10) pickle_path = '../data/grid_10.pkl' simulate_different_request_rates(G, pickle_path, network_type='grid') print("done grid100") # generate data for 13x13 trigrid print("doing trigrid13") G = nx.lattice.triangular_lattice_graph(13, 13) pickle_path = '../data/trigrid_13.pkl'
################################################################################################################################################ ################################################################################################################################################ ################################################################################################################################################ def EfficiencyComputation(InputGraph): G=InputGraph.copy() N=G.order() vertexlist=G.nodes() EfficiencySum=0.0 for current_vertex in vertexlist: print 'current_vertex:',current_vertex CurrentVertexDistanceList=list(nx.single_source_shortest_path_length(G,current_vertex).values()) print 'CurrentVertexDistanceList:',CurrentVertexDistanceList InverseDistanceList=ElementwiseInvertList(CurrentVertexDistanceList) print 'InverseDistanceList:',InverseDistanceList EfficiencySum+=sum(InverseDistanceList) print 'EfficiencySum:',EfficiencySum print '------------------------' AverageEfficiency=(1.0*EfficiencySum)/(N*(N-1)) return AverageEfficiency ################################################################################################################################################ ################################################################################################################################################ ################################################################################################################################################ G=nx.star_graph(5) R=EfficiencyComputation(G) print R
# # 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 netket import legacy as nk import networkx as nx # defining a custom graph # here we use networkx to generate a star graph # and pass its edges list to NetKet custom graph gnx = nx.star_graph(10) g = nk.graph.CustomGraph(list(gnx.edges)) # Hilbert space of spins on the graph hi = nk.hilbert.Spin(s=1 / 2, N=g.n_nodes) # Ising spin hamiltonian ha = nk.operator.Ising(hilbert=hi, graph=g, h=1.0) # RBM Spin Machine ma = nk.machine.RbmSpin(alpha=1, hilbert=hi) ma.init_random_parameters(seed=1234, sigma=0.01) # Metropolis Local Sampling sa = nk.sampler.MetropolisLocal(machine=ma)
def test_S4(self): G = nx.star_graph(4) self.test(G, [(1, 2)], [(1, 2, 1 / math.log(4))])
def test_charge_even(self): graph = nx.star_graph(10) F = TseitinFormula(graph, [0] * 11) for C in F: if len(C) == 1: self.assertFalse(C[0][0])