graph_tool:重新索引顶点ID是连续整数



在给定图上应用顶点过滤器后,我想重新索引新的过滤图形,以使顶点ID是连续的整数。

例如:

from graph_tool import load_graph
g = load_graph("path-to-graph")   # assuming there are `n` nodes
vfilt = g.new_vertex_filter('bool')
# ...modify vfilt so that `k` nodes are filtered out 
g.set_vertex(filter)
new_g = reindex_vertices(g)  # is there such a function?
assert list(map(int, new_g.vertices())) == list(range(n-k))  # 1...n-k

graph_tool中的函数类似于reindex_vertices

更新

一个解决方案是:

n2i = {n: i for i, n in enumerate(g.vertices())}  # mapping from old node id to new node id
# then create a new graph and also reindex the edges
new_g = Graph()
new_g.add_edge_list([(n2i[e.source()], n2i[e.target()]) for e in g.edges()])

new_g = gt.Graph(new_g, prune = True)

现在new_g将具有连续的顶点索引。

您需要设置Graph()函数调用的vorder参数。它是类型的propertymap

N = int(g.num_vertices())
newindexes = graph.new_vertex_property("int")
for v in graph.vertices():
    newnames[v] = (int(v)+3)%N    #Hash function to jumble the values
new_g = Graph(g,vorder=newindexes)

您可以将newindexes更改为这些数据类型

这将"重新索引"您的新图。:)

最新更新