复杂网络随即网络生成与相关计算的python实现

题目:生成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

  • 7
    点赞
  • 43
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值