import networkx as nx import random # 读入edge文件,构建图结构 graph = {} with open("./edge/football.edge", "r") as f: for line in f: u, v = line.strip().split() if u not in graph: graph[u] = [] if v not in graph: graph[v] = [] graph[u].append(v) graph[v].append(u) # 随机选择一个节点作为感染源 infected = random.choice(list(graph.keys())) print("Infected node:", infected) # 初始化每个节点的感染状态 status = {} for node in graph: status[node] = "S" status[infected] = "I" # SI模型参数 p = 0.5 # 感染过程 while True: changed = False for node in graph: if status[node] == "I": for neighbor in graph[node]: if status[neighbor] == "S" and random.random() < p: status[neighbor] = "I" changed = True if not changed: break # 输出每个节点的感染状态和邻居 for node in graph: print(node, status[node], graph[node])之后续写一个加入观测节点的溯源代码并可视化
时间: 2023-11-22 07:52:20 浏览: 71
import networkx as nx
import random
import matplotlib.pyplot as plt
# 读入edge文件,构建图结构
graph = {}
with open("./edge/football.edge", "r") as f:
for line in f:
u, v = line.strip().split()
if u not in graph:
graph[u] = []
if v not in graph:
graph[v] = []
graph[u].append(v)
graph[v].append(u)
# 随机选择一个节点作为感染源
infected = random.choice(list(graph.keys()))
print("Infected node:", infected)
# 初始化每个节点的感染状态
status = {}
for node in graph:
status[node] = "S"
status[infected] = "I"
# SI模型参数
p = 0.5
# 感染过程
while True:
changed = False
for node in graph:
if status[node] == "I":
for neighbor in graph[node]:
if status[neighbor] == "S" and random.random() < p:
status[neighbor] = "I"
changed = True
if not changed:
break
# 输出每个节点的感染状态和邻居
for node in graph:
print(node, status[node], graph[node])
# 添加观测节点
observed = random.choice(list(graph.keys()))
print("Observed node:", observed)
# 溯源过程
path = [observed]
while path[-1] != infected:
for neighbor in graph[path[-1]]:
if status[neighbor] == "I" and neighbor not in path:
path.append(neighbor)
break
# 可视化
colors = []
for node in graph:
if node == infected:
colors.append("red")
elif node == observed:
colors.append("green")
elif node in path:
colors.append("blue")
else:
colors.append("gray")
nx.draw(nx.Graph(graph), with_labels=True, node_color=colors)
plt.show()
阅读全文