# Networkx graph to Sage graph? + Export graph to csv?

Hi everybody,

I want to work with networkx, in particular with algorithms in networkx. I know how to import a graph with data from a csv-file and how to convert a Sage graph into a networkx graph. Therefor my code:

import csv
f=open(DATA+'example','r')
data=[row for row in data]
f.close()
data=[(column[0:]) for column in data[1:]]
data
Liste=[]
for row in data:
Tupel=()
for item in row:
titem=(int(item),)
Tupel=Tupel+titem
Liste.append(Tupel)
print Liste
G=Graph(Liste)
import networkx as nx
H=G.networkx_graph()
h=nx.minimum_spanning_tree(H)


What do I have to do to convert my so called h-graph into a Sage graph? And how to get the results back into a csv-file?

edit retag close merge delete

Sort by » oldest newest most voted ### MST's

kcrisman's answer works for converting the networkx graph to a sage graph. As he points out Sage has its own implementations of mst algorithms (see here for documentation, you can use the algorithm from networkx too :-). See an example below.

sage: Z=Graph(G.min_spanning_tree(algorithm='Kruskal'))


### Writing graph to csv

It seems that the format you are reading from is the edge list format from here. If this is the case, then you can easily save graph Z with the following commands.

sage: f=open('Z.csv','w')
sage: f.write('\n') # We write the blank line at the top
sage: Zwriter = csv.writer(f,delimiter=';')
sage: Zwriter.writerows(Z.edges(labels=None))
sage: f.close()


Assuming you are reading from the format mentioned above, it might be possible to read the graph in one line as shown below.

sage: f=open('Z.csv','r')
sage: Z = Graph([(int(u),int(v))  for u,v in Zreader])
sage: f.close()

more

Nice, I like that a lot. You could even get the minimum spanning tree in the same Z command, and then write it back to csv in a final command... I wonder what the minimal number of characters needed to do this would be :)

Does the following not work for getting it as a Sage graph?

sage: Z = Graph(h)
sage: Z.order() == Z.size()+1
True  # we hope!


Sage also has a minimum spanning tree method though I think it is an LP one, not the networkx one.

Your question about csv remains unanswered, largely because I didn't know there was a standard way to represent graphs in csv-file format.

more