使用igraph读取'ncol'格式,同时保留标签

时间:2015-01-29 15:49:50

标签: python igraph

我需要一种自动化的方式来阅读' ncol'格式(边缘列表) ,同时保留标签。

例如:

给出一个小图表。涂鸦师:

0 1 0.47
0 2 0.67
0 3 0.98
0 4 0.12
0 5 0.82
0 10 0.34
1 2 0.94
1 3 0.05
1 4 0.22
2 3 0.24
2 4 0.36
3 4 0.69
5 6 0.97
5 8 0.44
5 7 0.43
5 9 0.37
6 7 0.83
6 8 0.49
6 9 0.55
7 8 0.39
7 9 0.73
8 9 0.68
10 11 0.22
10 14 0.59
11 12 0.40
12 13 0.78
13 14 0.81

图表:

enter image description here

我试试:

import igraph
g = igraph.read("smallgraph.edgelist", format="ncol", directed=False, names=True)

但是这个功能不会保留标签!!!!

此函数生成的输出:

for edge in g.es():
    print edge.tuple[0], edge.tuple[1], edge["weight"]

0 1 0.47
0 2 0.67
0 3 0.98
0 4 0.12
0 5 0.82
0 6 0.34 -> e.g.: Considering the original labels here should be '0 10 0.34'
1 2 0.94
1 3 0.05
1 4 0.22
2 3 0.24
2 4 0.36
3 4 0.69
5 7 0.97
5 8 0.44
5 9 0.43
5 10 0.37
6 11 0.22
6 12 0.59
7 8 0.49
7 9 0.83
7 10 0.55
8 9 0.39
8 10 0.68
9 10 0.73
11 13 0.4
12 14 0.81
13 14 0.78

输出:

enter image description here

不保留输入文件(small-graph.edgelist)的标签。

我认为这样的事情可行:

g = igraph.Graph()
g.add_vertices(15)
g = igraph.read("input/small-graph.edgelist", format="ncol", directed=False, names=True)

但这不起作用,我不知道该怎么做。 有谁知道如何保留原始标签?

2 个答案:

答案 0 :(得分:2)

保留原始标签,但它们存储在name顶点属性中。像往常一样阅读图表后试试这个:

names = g.vs["name"]
for edge in g.es:
    print names[edge.tuple[0]], names[edge.tuple[1]], edge["weight"]

更新:如果您完全确定您的文件只包含连续数字ID,则为零(即如果您有 n 顶点,那么您的ID从零到 n -1),您可以执行以下操作:

edges, weights = [], []
for line in open("input_file.txt"):
    u, v, weight = line.split()
    edges.append((int(u), int(v)))
    weights.append(float(weight))
g = Graph(edges, edge_attrs={"weight": weights})

答案 1 :(得分:2)

在文件仅包含从零开始的连续数字ID的情况下,基于Tamás的更新答案进行了一些改进。这适用于有向图,并可以处理某些情况,例如从0到任何其他顶点可能没有边:

read_edges(num_vertices,input_graph):
   g = Graph(directed=True)
   g.add_vertices(list(range(0,num_vertices)))
   for line in open(input_graph):
      u, v= line.split()
      g.add_edge(int(u), int(v))
   return g