Ask Your Question

generate all (not necessarily induced) subgraphs of a graph

asked 2013-04-16 09:56:12 -0500

vermette gravatar image

I want to, given a Sage graph G, generate all subgraphs of G and check them for some property, and store in a list those which satisfy the propery. What I'm doing currently seems very inefficient:

for g in graphs.nauty_geng(str(G.order())):
    if G.subgraph_search(g):
        if check(g):

check(g) checks that g satisfies the properties I want, and it's done. Actually the code above works completely - it gives a list of the graph6 strings for every subgraph of G. However, I think it's overkill to check through all graphs, and it's also pretty slow for graphs larger than 6 vertices or so. I need it to work for more, up to maybe 15.

An iterator would be fine. I just need to check each of the graphs for some property. The code could be something like this:

for g in all_subsets_generator(G):
    if check(g):

where all_subsets_generator(G) iterates over all subsets of G.

Thanks for any advice. Let me know if more information is needed.

edit retag flag offensive close merge delete

1 answer

Sort by ยป oldest newest most voted

answered 2013-04-16 10:19:22 -0500

fidbc gravatar image

You could try the following

for s in E.subsets():
    H.add_edges( s )
    #If you are interested only in spanning subgraphs you have to include this line
    H.add_vertices( V )
    if check( H ):
        graphs_you_want.append( H.graph6_string() )

One thing to keep in mind is that you might want to get the canonical label of H into the list of graphs you want (in case you are interested in non labelled subgraphs). This could help avoid duplicates (isomorphic graphs) in the list.

This does not guarantee it will be faster, it will take the same time (maybe more) as your first approach when G is the complete graph.

edit flag offensive delete link more


thanks, this is what I want. my graphs are relatively sparse, so I think it should be faster. I didn't know much about `.edges()` or `.add_edges()`, those are quite useful. to handle the isomorphic graphs, I added just before appending graphs which pass `check()` the following: `H_can=H.canonical_label()`, then `graphs_you_want.append( H_can.graph6_string() )` to append. after it runs, `list(set(graphs_you_want))` removes duplicates (and is fairly fast because the list is short). thanks again~

vermette gravatar imagevermette ( 2013-04-17 04:51:29 -0500 )edit

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account.

Add Answer

Question Tools


Asked: 2013-04-16 09:56:12 -0500

Seen: 775 times

Last updated: Apr 16 '13