Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there an easy way to prune disconnected networks in a NetworkX graph?

I'm using Python's NetworkX package to calculate a bunch of network statistics for networks of varying size. I'm sweeping an independent parameter that systematically prunes edges, so sometimes a small network will become disconnected from the main network. Is there an easy way to detect and remove those smaller disconnected networks in NetworkX?

like image 934
Randy Olson Avatar asked Nov 15 '13 23:11

Randy Olson


People also ask

How do I delete an isolated node in NetworkX?

The documentation says that isolated vertices in graph can be obtained using networkx. isolates(G). It adds that the isolated vertices can be removed from a graph G using the code G. remove_nodes_from(nx.

How do you check if a directed graph is connected NetworkX?

Test directed graph for strong connectivity. A directed graph is strongly connected if and only if every vertex in the graph is reachable from every other vertex. Parameters: GNetworkX Graph.

What is weakly connected components in NetworkX?

A weakly connected component is a subgraph that is unreachable from other nodes/vertices of a graph or subgraph.


1 Answers

Sorin is correct. The function is called connected_component_subgraphs in NetworkX.

Documentation: http://networkx.github.io/documentation/latest/reference/generated/networkx.algorithms.components.connected.connected_component_subgraphs.html#networkx.algorithms.components.connected.connected_component_subgraphs

Here's some code that finds the largest network in a NetworkX graph:

cur_graph = # whatever graph you're working with

if not nx.is_connected(cur_graph):
    # get a list of unconnected networks
    sub_graphs = nx.connected_component_subgraphs(cur_graph)

    main_graph = sub_graphs[0]

    # find the largest network in that list
    for sg in sub_graphs:
        if len(sg.nodes()) > len(main_graph.nodes()):
            main_graph = sg

    cur_graph = main_graph
like image 183
Randy Olson Avatar answered Nov 09 '22 11:11

Randy Olson