graph_tool: re-index vertex ids to be consecutive integers

662 views Asked by At

After applying a vertex filter on a given graph, I'd like to re-index the new filtered graph so that the vertex ids are consecutive integers.

For example:

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

is there a function similar to reindex_vertices in graph_tool?

update

one solution is:

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()])
2

There are 2 answers

0
Peaceful On

What about

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

Now new_g would have consecutive vertex indices.

1
Vinit Kaushik On

You need to set the vorder parameter of Graph() function call. It is of type 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)

You may change newindexes to these datatypes

This will "re-index" your new graph. :)