Search code examples
pythonsubgraphgraph-tool

Graph-tool: subgraphs as new Graph objects


I find graph-tool documentation extremely obscure and much more cryptic than other analogous libraries.

I really can't figure out how to "extract" components (aka connected components) from a graph in graph-tools. I would like to save subgraphs in separate files as separate Graphs but I don't understand how to identify them starting from my Graph object.


Solution

  • The simplest (and fastest) way to do this is to do use a GraphView object.

    # label the components in a property map
    c = label_components(g)[0]
    
    # "extract" component number 3
    u = GraphView(g, vfilt=c.a == 3)
    

    The object u is now an induced subgraph of g that contains all the vertices of the component label 3. Note that a GraphView object does not copy the graph, it simply masks out the other vertices/edges.

    If you wish a copy of the subgraph (e.g. if you want to modify it, or the original graph), you just instantiate a new Graph object from it:

    u = Graph(u, prune=True)
    

    More information on graph views is available in the documentation: https://graph-tool.skewed.de/static/doc/quickstart.html#graph-views