def test_k_corona(self): # k=0 k_corona_subgraph = nx.k_corona(self.H, k=2) assert_equal(sorted(k_corona_subgraph.nodes()), [2, 4, 5, 6]) # k=1 k_corona_subgraph = nx.k_corona(self.H, k=1) assert_equal(sorted(k_corona_subgraph.nodes()), [1]) # k=2 k_corona_subgraph = nx.k_corona(self.H, k=0) assert_equal(sorted(k_corona_subgraph.nodes()), [0])
def test_k_corona(self): # k=0 k_corona_subgraph = nx.k_corona(self.H, k=2) assert sorted(k_corona_subgraph.nodes()) == [2, 4, 5, 6] # k=1 k_corona_subgraph = nx.k_corona(self.H, k=1) assert sorted(k_corona_subgraph.nodes()) == [1] # k=2 k_corona_subgraph = nx.k_corona(self.H, k=0) assert sorted(k_corona_subgraph.nodes()) == [0]
def generate_graph_features(glycan, libr=None): """compute graph features of glycan\n | Arguments: | :- | glycan (string): glycan in IUPAC-condensed format | libr (list): library of monosaccharides; if you have one use it, otherwise a comprehensive lib will be used\n | Returns: | :- | Returns a pandas dataframe with different graph features as columns and glycan as row """ if libr is None: libr = lib g = glycan_to_nxGraph(glycan, libr=libr) #nbr of different node features: nbr_node_types = len(set(nx.get_node_attributes(g, "labels"))) #adjacency matrix: A = nx.to_numpy_matrix(g) N = A.shape[0] diameter = nx.algorithms.distance_measures.diameter(g) deg = np.array([np.sum(A[i, :]) for i in range(N)]) dens = np.sum(deg) / 2 avgDeg = np.mean(deg) varDeg = np.var(deg) maxDeg = np.max(deg) nbrDeg4 = np.sum(deg > 3) branching = np.sum(deg > 2) nbrLeaves = np.sum(deg == 1) deg_to_leaves = np.array([np.sum(A[:, deg == 1]) for i in range(N)]) max_deg_leaves = np.max(deg_to_leaves) mean_deg_leaves = np.mean(deg_to_leaves) deg_assort = nx.degree_assortativity_coefficient(g) betweeness_centr = np.array( pd.DataFrame(nx.betweenness_centrality(g), index=[0]).iloc[0, :]) betweeness = np.mean(betweeness_centr) betwVar = np.var(betweeness_centr) betwMax = np.max(betweeness_centr) betwMin = np.min(betweeness_centr) eigen = np.array( pd.DataFrame(nx.katz_centrality_numpy(g), index=[0]).iloc[0, :]) eigenMax = np.max(eigen) eigenMin = np.min(eigen) eigenAvg = np.mean(eigen) eigenVar = np.var(eigen) close = np.array( pd.DataFrame(nx.closeness_centrality(g), index=[0]).iloc[0, :]) closeMax = np.max(close) closeMin = np.min(close) closeAvg = np.mean(close) closeVar = np.var(close) flow = np.array( pd.DataFrame(nx.current_flow_betweenness_centrality(g), index=[0]).iloc[0, :]) flowMax = np.max(flow) flowMin = np.min(flow) flowAvg = np.mean(flow) flowVar = np.var(flow) flow_edge = np.array( pd.DataFrame(nx.edge_current_flow_betweenness_centrality(g), index=[0]).iloc[0, :]) flow_edgeMax = np.max(flow_edge) flow_edgeMin = np.min(flow_edge) flow_edgeAvg = np.mean(flow_edge) flow_edgeVar = np.var(flow_edge) load = np.array(pd.DataFrame(nx.load_centrality(g), index=[0]).iloc[0, :]) loadMax = np.max(load) loadMin = np.min(load) loadAvg = np.mean(load) loadVar = np.var(load) harm = np.array( pd.DataFrame(nx.harmonic_centrality(g), index=[0]).iloc[0, :]) harmMax = np.max(harm) harmMin = np.min(harm) harmAvg = np.mean(harm) harmVar = np.var(harm) secorder = np.array( pd.DataFrame(nx.second_order_centrality(g), index=[0]).iloc[0, :]) secorderMax = np.max(secorder) secorderMin = np.min(secorder) secorderAvg = np.mean(secorder) secorderVar = np.var(secorder) x = np.array([len(nx.k_corona(g, k).nodes()) for k in range(N)]) size_corona = x[x > 0][-1] k_corona = np.where(x == x[x > 0][-1])[0][-1] x = np.array([len(nx.k_core(g, k).nodes()) for k in range(N)]) size_core = x[x > 0][-1] k_core = np.where(x == x[x > 0][-1])[0][-1] M = ((A + np.diag(np.ones(N))).T / (deg + 1)).T eigval, vec = eigsh(M, 2, which='LM') egap = 1 - eigval[0] distr = np.abs(vec[:, -1]) distr = distr / sum(distr) entropyStation = np.sum(distr * np.log(distr)) features = np.array([ diameter, branching, nbrLeaves, avgDeg, varDeg, maxDeg, nbrDeg4, max_deg_leaves, mean_deg_leaves, deg_assort, betweeness, betwVar, betwMax, eigenMax, eigenMin, eigenAvg, eigenVar, closeMax, closeMin, closeAvg, closeVar, flowMax, flowAvg, flowVar, flow_edgeMax, flow_edgeMin, flow_edgeAvg, flow_edgeVar, loadMax, loadAvg, loadVar, harmMax, harmMin, harmAvg, harmVar, secorderMax, secorderMin, secorderAvg, secorderVar, size_corona, size_core, nbr_node_types, egap, entropyStation, N, dens ]) col_names = [ 'diameter', 'branching', 'nbrLeaves', 'avgDeg', 'varDeg', 'maxDeg', 'nbrDeg4', 'max_deg_leaves', 'mean_deg_leaves', 'deg_assort', 'betweeness', 'betwVar', 'betwMax', 'eigenMax', 'eigenMin', 'eigenAvg', 'eigenVar', 'closeMax', 'closeMin', 'closeAvg', 'closeVar', 'flowMax', 'flowAvg', 'flowVar', 'flow_edgeMax', 'flow_edgeMin', 'flow_edgeAvg', 'flow_edgeVar', 'loadMax', 'loadAvg', 'loadVar', 'harmMax', 'harmMin', 'harmAvg', 'harmVar', 'secorderMax', 'secorderMin', 'secorderAvg', 'secorderVar', 'size_corona', 'size_core', 'nbr_node_types', 'egap', 'entropyStation', 'N', 'dens' ] feat_dic = {col_names[k]: features[k] for k in range(len(features))} return pd.DataFrame(feat_dic, index=[glycan])
nx.draw_networkx(F, pos, **dzcnapy.attrs) dzcnapy.set_extent(pos, plt) dzcnapy.plot("abcNwtwork") G = nx.Graph( (("Alpha", "Bravo"), ("Bravo", "Charlie"), ("Charlie", "Delta"), ("Charlie", "Echo"), ("Charlie", "Foxtrot"), ("Delta", "Echo"), ("Delta", "Foxtrot"), ("Echo", "Foxtrot"), ("Echo", "Golf"), ("Echo", "Hotel"), ("Foxtrot", "Golf"), ("Foxtrot", "Hotel"), ("Delta", "Hotel"), ("Golf", "Hotel"), ("Delta", "India"), ("Charlie", "India"), ("India", "Juliet"), ("Golf", "Kilo"), ("Alpha", "Kilo"), ("Bravo", "Lima"))) pos = graphviz_layout(G) core = nx.k_core(G) crust = nx.k_crust(G) corona3 = nx.k_corona(G, k=3).nodes() nx.draw_networkx(G, pos, nodelist=core, **dzcnapy.attrs) nx.draw_networkx_edges(G, pos, core.edges(), **dzcnapy.tick_attrs) nx.draw_networkx_edges(G, pos, crust.edges(), **dzcnapy.tick_attrs) nx.draw_networkx_nodes(G, pos, crust, node_shape='v', **dzcnapy.attrs) nx.draw_networkx_nodes(G, pos, corona3, node_shape='s', **dzcnapy.attrs) dzcnapy.set_extent(pos, plt) dzcnapy.plot("CoresAndCoronas") # Generate a 5-clique G = nx.complete_graph(5, nx.Graph()) nx.relabel_nodes(G, dict(enumerate(("Alpha", "Bravo", "Charlie", "Delta", "Echo"))), copy=False) # Attach a pigtail to it G.add_edges_from([("Echo", "Foxtrot"), ("Foxtrot", "Golf"), ("Foxtrot", "Hotel"),
def main(): #Reading in the graph G = nx.read_edgelist("GameOfThrones.txt", delimiter=",", data=(('strength', int), ('season', int))) #Displaying the graph pos = nx.spring_layout(G) plt.figure(figsize=(10, 10)) nx.draw_networkx(G, pos=pos, with_labels=True) plt.axis('off') plt.show() #Outputting info print(nx.info(G)) #Outputting highest degree node name & degree nodes = list(G.degree()) print("\nHighest degree node is:", nodes[0][0], "with degree", nodes[0][1]) #Outputting num of connected components print("\nNumber of connected components:", len(list(nx.connected_components(G)))) #Outputting the num of maximal cliques print("\nNumber of maximal cliques:", len(list(nx.find_cliques(G)))) #Outputting num of nodes in main core and k val core_num = list(nx.k_core(G).nodes()) for x in range(len(core_num)): if core_num == list(nx.k_core(G, k=x)): k_val = x print("\nNumber of nodes in main core:", len(core_num), "with k val:", k_val) #Outputting num of nodes in main crust print("\nNumber of nodes in main crust:", len(list(nx.k_crust(G).nodes()))) #Output num of nodes in the k corona print("\nNumber of nodes in k corona:", len(list(nx.k_corona(G, k=k_val).nodes()))) #Output num of nodes in main shell print("\nNumber of nodes in main shell:", len(list(nx.k_shell(G).nodes()))) #Display graph, main core - red, main crust - blue color_map = [] for node in G: if node in list(nx.k_core(G).nodes()): color_map.append('red') elif node in list(nx.k_crust(G).nodes()): color_map.append('blue') nx.draw_networkx(G, pos=pos, node_color=color_map, with_labels=False) plt.axis('off') plt.show() #Louvain Method, output num of communities, size or largest commnunity, size of smallest community, modularity of partition partition = community.best_partition(G) com_num = partition[max(partition, key=partition.get)] print("\nLouvain Method:") print("Number of communities:", com_num + 1) count = [] comm_list = list(partition.values()) for x in range(com_num): count.append(comm_list.count(x)) print("The largest community has count:", max(count)) print("The smallest community has count:", min(count)) print("The modularity of this partitioning:", community.modularity(partition, G)) #Display graph using Louvain, with nodes in diff colors per partition cmap = cm.get_cmap('viridis', max(partition.values()) + 1) nx.draw_networkx_nodes(G, pos, partition.keys(), node_size=40, cmap=cmap, node_color=list(partition.values())) nx.draw_networkx_edges(G, pos, alpha=0.5) plt.axis('off') plt.show() #Girvan-Newman Method, output num of communities, size or largest commnunity, size of smallest community, modularity of partition print("\nGirvan-Newman Method:") components = c.girvan_newman(G) i = 0 for row in components: if (i == 0): finalResult = row i = i + 1 partitions = dict() L = list(finalResult) p = 0 for comp in L: for entry in comp: partitions[entry] = p p = p + 1 com_num = partitions[max(partitions, key=partitions.get)] print("Number of communities:", com_num + 1) count = [] comm_list = list(partition.values()) for x in range(com_num): count.append(comm_list.count(x)) print("The largest community has count:", max(count)) print("The smallest community has count:", min(count)) print("The modularity of this partitioning:", community.modularity(partitions, G)) #Display graph using Girvan-Newman, with nodes in diff colors per partition cmap = cm.get_cmap('viridis', max(partitions.values()) + 1) nx.draw_networkx_nodes(G, pos, partitions.keys(), node_size=60, cmap=cmap, node_color=list(partitions.values())) plt.axis('off') plt.show()
ig.plot(g, target=fig_name, layout=layout, vertex_size=7, vertex_color='gray', vertex_label_size=10, vertex_label_dist=2, mark_groups=group_markers) #vertex_label=None print 'Ορισμός: Το k-στέμμα είναι ο υπογράφος των κόμβων του k-πυρήνα, οι οποίοι κόμβοι έχουν ακριβώς k γείτονες στον k-πυρήνα.' # print 'DEFINITION: The k-corona is the subgraph of nodes in the k-core which have exactly k neighbours in the k-core. στέμμα' print str(" ") kcoronas = [] for i in set(nx.core_number(G).values()): if len(nx.k_corona(G, k=i).nodes()) > 0: # print "i =", i kcnGi = nx.k_corona(G, k=i) print 'Οι κόμβοι του', str(i) + '-στέμματος:' # print 'The nodes of the', str(i)+'-shell:' print kcnGi.nodes() # print 'Οι ακμές του', str(i)+'-στέμματος:' # # print 'The edges of the k-shell of G are:' # print kcnGi.edges() # print 'Η ακολουθία βαθμών των κόμβων του', str(i)+'-στέμματος:' # # print 'The degree sequence of the nodes of the', str(i)+'-shell:' # print list(nx.degree(ksGi).values()) # # # print 'The order of the main k-shell of G is:' # # # print 'k =', min(list(nx.degree(ksGi).values())) print str(" ") kcoronas.append(kcnGi.nodes())
import networkx as nx import plot_multigraph import matplotlib.pylab as plt from matplotlib import pylab as plt n = 80 k = int(.2 * n) p = 10. / n G = nx.fast_gnp_random_graph(n, p, seed=42) def set_to_list(set_, G): return [1. * (k in set_) for k in G.nodes()] graph_colors = [ ("center", set_to_list(nx.center(G), G)), ("periphery", set_to_list(nx.periphery(G), G)), ("k_core", set_to_list(nx.k_core(G), G)), ("k_shell", set_to_list(nx.k_shell(G), G)), ("k_crust", set_to_list(nx.k_crust(G), G)), ("k_corona", set_to_list(nx.k_corona(G, k), G)), ] fig = plot_multigraph.plot_color_multigraph(G, graph_colors, 2, 3, node_size=50) plt.savefig('graphs/sets.png', facecolor=fig.get_facecolor())
color_to_set=(random.random(),random.random(),1) colors_lists.append(color_to_set) group_markers = [(kcrusts[i], colors_lists[i]) for i in range(len(kcrusts))] # ig.plot(g, mark_groups=group_markers) fig_name=os.path.join(file_dir_figs,str(G.name)+'_[k='+str(max(nx.core_number(G).values()))+']_k-crusts.png') ig.plot(g, target=fig_name, layout=layout, vertex_size=7, vertex_color='gray', vertex_label_size=10, vertex_label_dist=2, mark_groups=group_markers) #vertex_label=None print 'Ορισμός: Το k-στέμμα είναι ο υπογράφος των κόμβων του k-πυρήνα, οι οποίοι κόμβοι έχουν ακριβώς k γείτονες στον k-πυρήνα.' # print 'DEFINITION: The k-corona is the subgraph of nodes in the k-core which have exactly k neighbours in the k-core. στέμμα' print str(" ") kcoronas=[] for i in set(nx.core_number(G).values()): if len(nx.k_corona(G,k=i).nodes()) > 0: # print "i =", i kcnGi=nx.k_corona(G,k=i) print 'Οι κόμβοι του', str(i)+'-στέμματος:' # print 'The nodes of the', str(i)+'-shell:' print kcnGi.nodes() # print 'Οι ακμές του', str(i)+'-στέμματος:' # # print 'The edges of the k-shell of G are:' # print kcnGi.edges() # print 'Η ακολουθία βαθμών των κόμβων του', str(i)+'-στέμματος:' # # print 'The degree sequence of the nodes of the', str(i)+'-shell:' # print list(nx.degree(ksGi).values()) # # # print 'The order of the main k-shell of G is:' # # # print 'k =', min(list(nx.degree(ksGi).values())) print str(" ") kcoronas.append(kcnGi.nodes())
coreGraph.add_edge(edge[0], edge[1]) drawGraph(coreGraph) ''' ################################################ Step 4 output: a) Number of nodes in the main crust ##################################################''' print("\nNumber of nodes in the main crust: " + str(len(nx.k_crust(G).nodes()))) ''' ################################################ Step 5 output: a) Number of nodes in the k-corona where k is the max k-val (main core kval) ##################################################''' print("\nNumber of nodes in the k-corona: " + str(len(nx.k_corona(G, k=maxKValue).nodes()))) coronaGraph = nx.Graph() coronaEdges = nx.k_corona(G, k=maxKValue).edges() for edge in coronaEdges(): coronaGraph.add_edge(edge[0], edge[1]) drawGraph(coronaGraph) ''' ################################################ Step 6 output: a) Number of nodes in the main shell ##################################################''' mainShell = nx.k_shell(G).nodes() mainShellEdges = nx.k_shell(G).edges() print("\nNumber of nodes in main shell: " + str(len(mainShell)))