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 19:52:32 浏览: 58
python调试文件时发生import requests报错.doc
5星 · 资源好评率100%
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
# 记录观测节点和感染源之间的路径
paths = {}
# 感染过程
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"
paths[neighbor] = node # 记录路径
changed = True
if not changed:
break
# 输出每个节点的感染状态和邻居
for node in graph:
print(node, status[node], graph[node])
# 可视化
plt.figure(figsize=(10, 10))
pos = nx.spring_layout(graph)
colors = []
for node in graph:
if status[node] == "S":
colors.append("green")
else:
colors.append("red")
nx.draw_networkx_nodes(graph, pos, node_color=colors, node_size=500)
nx.draw_networkx_edges(graph, pos)
nx.draw_networkx_labels(graph, pos, font_size=12, font_family="sans-serif")
nx.draw_networkx_edges(graph, pos, edgelist=[(infected, paths[node]) for node in paths], edge_color="blue", width=2)
plt.axis("off")
plt.show()
阅读全文