我有 4 个函数用于复杂网络分析中的一些统计计算。
import networkx as nx
import numpy as np
import math
from astropy.io import fits
图的度数分布:
def degree_distribution(G):
vk = dict(G.degree())
vk = list(vk.values()) # we get only the degree values
maxk = np.max(vk)
mink = np.min(min)
kvalues= np.arange(0,maxk+1) # possible values of k
Pk = np.zeros(maxk+1) # P(k)
for k in vk:
Pk[k] = Pk[k] + 1
Pk = Pk/sum(Pk) # the sum of the elements of P(k) must to be equal to one
return kvalues,Pk
图的社区检测:
def calculate_community_modularity(graph):
communities = greedy_modularity_communities(graph) # algorithm
modularity_dict = {} # Create a blank dictionary
for i,c in enumerate(communities): # Loop through the list of communities, keeping track of the number for the community
for name in c: # Loop through each neuron in a community
modularity_dict[name] = i # Create an entry in the dictionary for the neuron, where the value is which group they belong to.
nx.set_node_attributes(graph, modularity_dict, 'modularity')
print (graph_name)
for i,c in enumerate(communities): # Loop through the list of communities
#if len(c) > 2: # Filter out modularity classes with 2 or fewer nodes
print('Class '+str(i)+':', len(c)) # Print out the classes and their member numbers
return modularity_dict
图的模块化分数:
def modularity_score(graph):
return nx_comm.modularity(graph, nx_comm.label_propagation_communities(graph))
最后是图熵:
def shannon_entropy(G):
k,Pk = degree_distribution(G)
H = 0
for p in Pk:
if(p > 0):
H = H - p*math.log(p, 2)
return H
问题
我现在想要实现的是找到每个社区的局部熵(变成一个子图),并保留边缘信息。
这可能吗?怎么会这样?
编辑
正在使用的矩阵在此链接中:
with fits.open('mind_dataset/matrix_CEREBELLUM_large.fits') as data:
matrix = pd.DataFrame(data[0].data.byteswap().newbyteorder())
然后将邻接矩阵变成一个图,“图”或“G”,如下所示:
def matrix_to_graph(matrix):
from_matrix = matrix.copy()
to_numpy = from_matrix.to_numpy()
G = nx.from_numpy_matrix(to_numpy)
return G
编辑 2
根据下面提出的答案,我创建了另一个函数:
def community_entropy(modularity_dict):
communities = {}
#create communities as lists of nodes
for node, community in modularity_dict.items():
if community not in communities.keys():
communities[community] = [node]
else:
communities[community].append(node)
print(communities)
#transform lists of nodes to actual subgraphs
for subgraph, community in communities.items():
communities[community] = nx.Graph.subgraph(subgraph)
local_entropy = {}
for subgraph, community in communities.items():
local_entropy[community] = shannon_entropy(subgraph)
return local_entropy
和:
cerebellum_graph = matrix_to_graph(matrix)
modularity_dict_cereb = calculate_community_modularity(cerebellum_graph)
community_entropy_cereb = community_entropy(modularity_dict_cereb)
但它会抛出错误:
类型错误:subgraph() 缺少 1 个必需的位置参数:'nodes'