WS小世界网络模型python代码
时间: 2023-09-24 13:14:01 浏览: 91
以下是使用 Python 实现 WS 小世界网络模型的代码:
```python
import networkx as nx
import random
def create_ws_graph(n, k, p):
"""
n: 节点数
k: 每个节点的度数,即每个节点与其相邻的节点数
p: 重连边的概率
"""
G = nx.Graph()
nodes = [i for i in range(n)]
G.add_nodes_from(nodes)
for i in range(1, k // 2 + 1):
targets = nodes[i:] + nodes[0:i] # 相邻节点
G.add_edges_from(zip(nodes, targets))
for i in range(1, k // 2 + 1):
targets = nodes[i:] + nodes[0:i] # 相邻节点
for j, target in enumerate(targets):
if random.random() < p:
# 重连边
new_target = random.choice(nodes)
while new_target == target or G.has_edge(target, new_target):
new_target = random.choice(nodes)
G.remove_edge(nodes[j], target)
G.add_edge(nodes[j], new_target)
return G
```
代码中使用了 NetworkX 库来创建和操作图,其中 `n` 表示节点数,`k` 表示每个节点的度数,`p` 表示重连边的概率。首先将所有节点连接成一个环,然后对于每个节点,将它与它相邻的 $k/2$ 个节点相连。最后,对每条边以概率 $p$ 进行重连,即将一端的节点随机连接到另一个节点。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![docx](https://img-home.csdnimg.cn/images/20210720083331.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)