题目:生成N=1000,连边概率p=0.05的随机网络,计算最大连通子图的规
模。求最大连通子图的平均路径长度,平均聚类系数,统计度分布。
# -*- coding: utf-8 -*-
import networkx as nx
import matplotlib.pyplot as plt
①引用networkx、matplotlib模块分别用于生成网络和绘图
print('Number of node in ER random network is 100,The probability of connection is 0.05')
NETWORK_SIZE = 100
p = 0.05
G = nx.erdos_renyi_graph(n = NETWORK_SIZE,p = p)
ps = nx.spring_layout(G)
nx.draw(G,ps,width=0.6,node_size=10)
plt.savefig('fig.png',bbox_inches='tight')
②节点数与连边概率赋值,并用networkx生成网络
max_len = 0
sum_path_len = 0
for i in sorted(nx.connected_components(G), key = len, reverse = True):
if (len(i) >= max_len):
max_len = len(i)
else:
max_len = max_len
print("The degree of giant component:" + str(max_len))
③给网络中连通节点度排序并输出最大连通子图的节点数
if (max_len >= NETWORK_SIZE):
aspl = nx.average_shortest_path_length(G)
print("Average path length:" + str(aspl))
else:
connected = [n for n, d in G.degree() if d > 0]
Gcc = sorted(nx.connected_components(G), key=len, reverse=True)
G = G.subgraph(Gcc[0])
④判断:if(所有节点连通)- 计算平均路径长度
else(存在孤立点) - 遍历有连边的节点并排序,并将largest connected components(Gcc[0])赋给G
print("Average clustering coefficient:" + str(nx.degree_histogram(G)))
print("Degree distribution of giant component:" + str(nx.degree_histogram(G)))
⑤计算聚类系数和最大连通子图的度分布
degree = nx.degree_histogram(G)
x = range(len(degree))
y = [z / float(sum(degree)) for z in degree]
plt.loglog(x, y, color="red", linewidth=2)
plt.savefig('fig.png',bbox_inches='tight')
plt.show()
⑥输出图形
参考代码:https://networkx.org/documentation/latest/auto_examples/drawing/plot_giant_component.html