Ask Your Question
1

Convert Sage's Graph to NetworkX graph

asked 2012-02-13 11:03:40 +0100

juanpool gravatar image

updated 2015-01-14 11:56:11 +0100

FrédéricC gravatar image

I want to use a function of networkx. More specifically I want to use the function

double_edge_swap()

provided in the networkx package included in Sage. For more information see here.

But, I have a Sage graph constructed with:

Graph()

So I want to convert the Sage's Graph() object to a networkx object. How I do that?

Best regards.

edit retag flag offensive close merge delete

1 Answer

Sort by » oldest newest most voted
2

answered 2012-02-13 11:18:02 +0100

DSM gravatar image

updated 2012-02-13 11:21:57 +0100

You can simply call the method .networkx_graph():

sage: import networkx as nx
sage: G = graphs.PetersenGraph()             
sage: ng = G.networkx_graph()                
sage: ng
<networkx.classes.graph.Graph object at 0xd3c2f8c>
sage: nx.double_edge_swap(ng)                
1

Incidentally, I didn't know this five minutes ago, so I should tell you how I found out. Lots of functionality for Sage objects lives inside them, in methods. Typically conversion functions are either called ".targettype" or "._targettype_", so I tried

sage: G.netw[HERE I HIT TAB]
      G.networkx_graph

which looked promising. And then typing

sage: G.networkx_graph?

gives the documentation:

       Creates a new NetworkX graph from the Sage graph.

       INPUT:

       * "copy" - if False, and the underlying implementation is a
         NetworkX graph, then the actual object itself is returned.

       EXAMPLES:

          sage: G = graphs.TetrahedralGraph()
          sage: N = G.networkx_graph()
          sage: type(N)
          <class 'networkx.classes.graph.Graph'>

          sage: G = graphs.TetrahedralGraph()
          sage: G = Graph(G, implementation='networkx')
          sage: N = G.networkx_graph()
          sage: G._backend._nxg is N
          False

          sage: G = Graph(graphs.TetrahedralGraph(), implementation='networkx')
          sage: N = G.networkx_graph(copy=False)
          sage: G._backend._nxg is N
          True

PS: Okay, to be perfectly honest, I tried it first and only looked at the documentation when I came to write this. But I would've looked at the documentation if it hadn't worked, I promise! :^)

edit flag offensive delete link more

Comments

Thanks very much DSM. That solves my problem. Fool of me. I tried using TAB in sage's notebook, and googled a lot. But I couldn't find it.

juanpool gravatar imagejuanpool ( 2012-02-13 12:31:33 +0100 )edit
1

To get this, you need to do G.[tab], not G[tab]. In case that's where the confusion came in.

kcrisman gravatar imagekcrisman ( 2012-02-13 13:50:18 +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: 2012-02-13 11:03:40 +0100

Seen: 2,099 times

Last updated: Feb 13 '12