Ask Your Question
1

generate all (not necessarily induced) subgraphs of a graph

asked 2013-04-16 16:56:12 +0100

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:

graphs_i_want=[]
for g in graphs.nauty_geng(str(G.order())):
    if G.subgraph_search(g):
        if check(g):
            graphs_i_want.append(g.graph6_string())

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:

graphs_i_want=[]
for g in all_subsets_generator(G):
    if check(g):
        graphs_i_want.append(g.graph6_string())

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
3

answered 2013-04-16 17:19:22 +0100

fidbc gravatar image

You could try the following

E=Set(G.edges())
V=G.vertices()
for s in E.subsets():
    H=Graph()
    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

Comments

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 11:51:29 +0100 )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

Stats

Asked: 2013-04-16 16:56:12 +0100

Seen: 1,811 times

Last updated: Apr 16 '13