检验节点重要性的SIR模型PYTHON案例
时间: 2023-12-03 19:01:59 浏览: 105
下面是一个简单的Python代码示例,用于检验SIR模型中节点重要性的影响:
```python
import networkx as nx
import matplotlib.pyplot as plt
# 构建网络图
G = nx.karate_club_graph()
# 设置传染率和恢复率
beta = 0.2
gamma = 0.1
# 设置初始感染节点
initial_infected = [0]
# 定义SIR模型演化过程
def sir_model(G, beta, gamma, initial_infected, num_iterations):
infected = set(initial_infected)
susceptible = set(G.nodes()) - infected
recovered = set()
for t in range(num_iterations):
# 感染节点传播
newly_infected = set()
for i in infected:
for j in G.neighbors(i):
if j in susceptible and np.random.random() < beta:
newly_infected.add(j)
# 恢复节点
newly_recovered = set()
for i in infected:
if np.random.random() < gamma:
newly_recovered.add(i)
# 更新节点集合
infected |= newly_infected
recovered |= newly_recovered
susceptible = set(G.nodes()) - infected - recovered
return len(recovered)
# 计算每个节点的影响力评分
scores = {}
for node in G.nodes():
initial_infected = [node]
final_recovered = sir_model(G, beta, gamma, initial_infected, 10)
scores[node] = final_recovered
# 对节点按照影响力评分进行排序
rank = sorted(scores.items(), key=lambda x: x[1], reverse=True)
# 输出前十个影响力最大的节点
for i in range(10):
print(rank[i])
# 可视化网络图
pos = nx.spring_layout(G)
nx.draw_networkx_nodes(G, pos, node_color='lightblue')
nx.draw_networkx_edges(G, pos)
plt.axis('off')
plt.show()
```
该代码首先使用networkx库中的karate_club_graph()方法构建了一个社交网络图G,包括34个节点和78条边。然后,它定义了一个sir_model()函数,用于对指定节点进行SIR模型的演化过程,并返回最终恢复的节点数量。在接下来的代码中,它使用该函数计算了每个节点的影响力评分,并对节点按照评分进行排序,输出前十个影响力最大的节点。最后,它使用matplotlib库将网络图可视化,以便展示社交网络的结构。
阅读全文