SI模型代码
时间: 2023-08-30 07:04:06 浏览: 64
以下是一个简单的SI模型的 Python 代码实现:
```python
import networkx as nx
import matplotlib.pyplot as plt
import random
def initialize_graph(n, p):
"""初始化图"""
graph = nx.Graph()
nodes = range(n)
for i in nodes:
for j in nodes:
if i < j and random.random() < p:
graph.add_edge(i, j)
return graph
def initialize_states(n):
"""初始化节点状态"""
return [1 if random.random() < 0.5 else 0 for i in range(n)]
def update(graph, states, beta):
"""更新节点状态"""
new_states = states[:]
for node in graph.nodes():
neighbors = list(graph.neighbors(node))
infected_neighbors = sum([states[n] for n in neighbors])
if states[node] == 0 and infected_neighbors > 0 and random.random() < beta:
new_states[node] = 1
elif states[node] == 1 and infected_neighbors == 0:
new_states[node] = 0
return new_states
def simulate(graph, beta, num_iterations):
"""模拟SI模型"""
states = initialize_states(len(graph.nodes()))
for i in range(num_iterations):
states = update(graph, states, beta)
return states
# 示例应用
graph = initialize_graph(50, 0.2)
states = simulate(graph, 0.5, 10)
nx.draw(graph, node_color=states, cmap='RdYlGn', with_labels=True)
plt.show()
```
这个代码实现了一个简单的SI模型,在每个节点上随机初始化状态(0或1),在每轮迭代中根据邻居节点的状态进行更新,最后返回最终的节点状态。可以通过调整参数来探索不同情况下的模型行为。