运用si感染模型感染导入的'football.edge'数据集,输出打印节点感染状态和邻居,之后设置观测节点,利用定位源的反向传播初始时间的方差来定位,输出结果并将最终结果可视化
时间: 2023-10-06 07:05:57 浏览: 118
以下是利用SI感染模型感染'football.edge'数据集的Python代码:
```python
import networkx as nx
import numpy as np
import random
# 读取数据集
G = nx.read_edgelist('football.edge')
# SI感染模型
def SI_model(G, beta):
# 初始化节点状态
nodes_status = {node: 'S' for node in G.nodes()}
# 随机选择一个节点作为感染源
source = random.choice(list(G.nodes()))
nodes_status[source] = 'I'
# 迭代更新节点状态
while True:
flag = True # 判断是否还有节点可以感染
for node in G.nodes():
if nodes_status[node] == 'S':
for neighbor in G.neighbors(node):
if nodes_status[neighbor] == 'I':
# 以概率beta感染该节点
if np.random.random() < beta:
nodes_status[node] = 'I'
flag = False
break
if not flag:
break
if flag:
break
return nodes_status
# 运行SI模型并输出节点状态和邻居
beta = 0.2
nodes_status = SI_model(G, beta)
for node in G.nodes():
print(f"Node {node} status: {nodes_status[node]}, neighbors: {list(G.neighbors(node))}")
```
设置观测节点并利用定位源的反向传播初始时间的方差来定位:
```python
# 设置观测节点
observed_nodes = [1, 4, 13, 14, 17, 22, 25, 29, 31, 33]
# 利用定位源的反向传播算法定位
def reverse_propagation(observed_nodes, nodes_status, beta, max_iter=1000, tol=1e-6):
# 初始化
N = len(nodes_status)
H = np.zeros((N, N))
for i in range(N):
for j in range(N):
if i == j:
H[i, j] = 1
else:
H[i, j] = -beta * int(j in G.neighbors(i))
Y = np.zeros((N, N))
for i in observed_nodes:
Y[i, i] = 1
t = np.zeros(N)
# 反向传播
for i in range(max_iter):
t_new = np.dot(np.linalg.inv(H), Y - np.exp(-beta*t))
if np.linalg.norm(t_new - t) < tol:
break
t = t_new
return t
# 运行定位算法
t = reverse_propagation(observed_nodes, nodes_status, beta)
# 输出结果
print("Estimated infection time:")
for node in G.nodes():
print(f"Node {node}: {t[node]}")
```
最后,将最终结果可视化:
```python
import matplotlib.pyplot as plt
# 可视化定位结果
pos = nx.spring_layout(G)
node_color = [t[node] for node in G.nodes()]
nx.draw_networkx(G, pos, node_size=50, node_color=node_color, cmap=plt.cm.Reds)
plt.title("Infection time estimation")
plt.colorbar()
plt.show()
```
阅读全文