0

I am having a bit of trouble obtaining an iteration through all possible subragphs of a large nx graph G, taken as input from a text file.

The following is some code I found on StackOverflow, but is not yielding what i am looking for:

    g = read_graph(sys.argv[1])

    print ('Number of subgraphs:', len(g.subgraph(g.nodes())))

    # extract subgraphs
    sub_graphs = nx.connected_component_subgraphs(g)

    for i, sg in enumerate(sub_graphs):
        print "subgraph {} has {} nodes".format(i, sg.number_of_nodes())
        print "\tNodes:", sg.nodes(data=True)
        print "\tEdges:", sg.edges() 

Prints out:

('Number of subgraphs:', 4039)
subgraph 0 has 4039 nodes
    Nodes: <generator object nodes at 0x10ed77910>
    Edges: <generator object edges at 0x10ed77910>

What I am trying to do is be able to iterate through all possible subgraphs of length 3 or greater, then perform certain functions on them as graphs.

Thanks!

Sean
  • 1,283
  • 9
  • 27
  • 43
  • could you provide a link to where you got that code? It appears to be from a previous version. – Joel May 04 '17 at 16:16
  • Please also clarify what is meant by "subgraph of length 3". I can think of several things you mean by that. – Joel May 04 '17 at 16:17
  • in older versions of networkx, `sg.nodes()` and `sg.edges()` would have produced lists of nodes and edges, but they now return more efficient generators of nodes and edges. – Joel May 04 '17 at 17:04

1 Answers1

1

I'm writing this under the assumption that "length 3" means "at least 3 nodes".

import networkx as nx
g = read_graph(sys.argv[1])

for subgraph in nx.connected_component_subgraphs(g):
    if subgraph.number_of_nodes()>2:
         #your code here
Joel
  • 22,598
  • 6
  • 69
  • 93