Search code examples
pythonnetworkxwritefileundirected-graph

Write a Graph into a file in an adjacency list form [mentioning all neighbors of each node in each line]


I need to write a graph in a text file where each line of the file is composed from one node followed by all its neighbors. It's basically what an Adjacency List is, and what the function write_adjlist is supposed to do. Unfortunatly it's not the case, as the edge are not replicated. In the exemple of wikipedia the adjacency list is :

a adjacent to b, c

b adjacent to a, c

c adjacent to a, b

We can see that all edges are present two times (the edge (a,b) in lines 1 and 2, the edge (b,c) in lines 2 and 3...).

But now if I use the following code to generate a small world network :

import networkx as nx

N=5  #Number of nodes
v=2  #Number of neighbours
p=.1 #rewiring proba

G = nx.connected_watts_strogatz_graph(N,v,p)
nx.write_adjlist(G.to_undirected(),"test.txt")

it gives me :

#adj.py
# GMT Thu Jan 21 06:57:29 2016
# watts_strogatz_graph(5,2,0.1)
0 1 4
1 2
2 3
3 4
4

where I would like to have

0 1 4
1 2 0
2 3 1
3 2 4 
4 0 3

Do you know how I could do to have the output I want?


Solution

  • Actually this is how the write_adjlist is defined so in order to have the file written as you want a simple work around can be done with the following function:

    def adj_list_to_file(G,file_name):
        f = open('tst.txt', "w")
        for n in G.nodes():
            f.write(str(n) + ' ')
            for neighbor in G.neighbors(n):
                f.write(str(neighbor) + ' ')
            f.write('\n')
    
    N=5  #Number of nodes
    v=2  #Number of neighbours
    p=.1 #rewiring proba
    G = nx.connected_watts_strogatz_graph(N,v,p)
    nx.draw(G, with_labels= True)
    plt.show()
    adj_list_to_file(G.to_undirected(),"tst.txt")
    

    The file output is:

    0 1 4 
    1 0 2 
    2 1 3 
    3 2 4 
    4 0 3