networkx_to_metis

存储networkx生成的图的方法参考networkx手册:
https://networkx.github.io/documentation/stable/reference/readwrite/index.html
Adjacency List经过适当处理可以转换成metis可识别的格式。

先看graph的Adjacency List

import networkx as nx
import metis
import numpy as np
import matplotlib.pyplot as plt

#用random_graphs.barabasi_albert_graph(n, m)方法生成一个含有n个节点、每次加入m条边的BA无标度网络
BA = nx.random_graphs.barabasi_albert_graph(20, 1)
pos = nx.spring_layout(BA)  # 图形的布局样式,这里是中心放射状
nx.draw(BA, pos, with_labels=True, node_size=30, node_color='red')
plt.show()

在这里插入图片描述

for line in nx.generate_adjlist(BA):
    print(line)

0 1 2 4 18
1 3 5
2
3
4
5 6 7 8 9 10 13 14 15 17
6
7 11 12 19
8
9
10
11
12 16
13
14
15
16
17
18
19

#BA.nodes
#BA.edges
#nx.number_of_nodes(BA) #20
#nx.number_of_edges(BA) #19
nx.write_adjlist(BA,"BA.adjlist")

Adjacency List将每条边只记一次,而metis的输入格式要求将每条边记录两次;Adjacency List的每一行第一个数表示该顶点,而metis默认行数为顶点;Adjacency List的顶点编号从0开始,metis的顶点编号从1开始。

node_num = nx.number_of_nodes(BA)
f=open('file','w')
for i in range(node_num):
    it = nx.neighbors(BA, i)
    li = list()
    while 1:
        try:
            li.append(next(it)+1)
#         print(li)
        except StopIteration:
            break
    f.write(str(li)+'\n\r') #换行windows \r\n linux \n mac \r
    print(li)

[2, 3, 5, 19]
[1, 4, 6]
[1]
[2]
[1]
[2, 7, 8, 9, 10, 11, 14, 15, 16, 18]
[6]
[6, 12, 13, 20]
[6]
[6]
[6]
[8]
[8, 17]
[6]
[6]
[6]
[13]
[6]
[1]
[8]

在生成的file文件中将中括号和逗号去掉,然后在第一行添加节点数和边数,保存即可。

最后metis可用的格式长这样:
在这里插入图片描述

方法比较笨,欢迎补充~

猜你喜欢

转载自blog.csdn.net/yaochuyi/article/details/87649138