Ian
Ian

Reputation: 3898

Better way to extract vertices from connected components?

The following graph, with edges [(0,1),(1,2),(3,3),(3,4),(1,1),(5,5),(5,6)], should have connected component vertex sets as follow: [0, 1, 2], [3, 4], [5, 6].

graph setup

import graph_tool as gt
from graph_tool.topology import label_components
edges = [(0,1),(1,2),(3,3),(3,4),(1,1),(5,5),(5,6)]
g = gt.Graph()
g.set_directed(False)
g.add_edge_list(edges)

extract vertices from connected components

lc = label_components(g)
[gt.GraphView(g, vfilt=lc[0].a == _).get_vertices() for _ in range(len(lc[1]))]  # [1]

output

[array([0, 1, 2], dtype=uint64), array([3, 4], dtype=uint64), array([5, 6], dtype=uint64)]

My question is, is this really the best approach? [1] in particular seems more convoluted than might be necessary. Maybe there's a function in the documentation that I'm not finding.

Upvotes: 1

Views: 364

Answers (1)

Roy2012
Roy2012

Reputation: 12513

Here's one way to do it, using the a attribute of the property map. Not sure it's dramatically better than yours, but nevertheless here it is:

comp, a = gt.topology.label_components(g) 
[[i for i, x in enumerate(comp.a) if x == c] for c in range(len(a))]  

The output is:

[[0, 1, 2], [3, 4], [5, 6]]

Upvotes: 1

Related Questions