Search code examples
pythonigraphadjacency-matrix

Python: read adjacency matrix from file for igraph


My question is very simple, but I really cannot find it on the web!

I have the adjacency matrix of a weighted-directed graph which is like:

1    2    3    4    
5    2    4    6  
3    5    6    2
4    6    7    8

so the element of column i and row j, shows the weight of the link between node i and j.

How can I read this file (which can be in txt or csv format) as a matrix to use in igraph? I want to find the number of clusters. So, I want sth like this: g.community_multilevel() if g is my matrix.


Solution

  • I'm assuming you already have igraph and cairo installed on your machine. If not and you are on a mac see this post. The method you want to use is Read_Adjacency() which is documented here. To read in your graph I used something like this python code:

    import igraph 
    from igraph import * 
    g=Graph.Read_Adjacency(f="soAdj",sep=None, comment_char='#',attribute="weighted")
    plot(g, "readAdjSoExample.pdf",layout="circle")
    

    and the plot will give something like this: enter image description here

    and you can access the weights to verify that they were read in correctly via command like: g.es[3] which gives result igraph.Edge(<igraph.Graph object at 0x10f614bf0>, 3, {'weighted': 4.0}) The OP mentioned text vs csv format, the difference would be in which separator you include as a string to the sep= argument to the method.