3
votes

I have an incidence matrix (where the rows are nodes and the columns are edges) as follows (it is read from a text file into a NumPy array):

[[1 1 1 1 1 1 1 1 1 1]
 [1 1 1 1 1 1 1 0 0 0]
 [1 1 1 1 1 0 1 1 0 0]
 [0 0 1 1 1 0 1 0 0 0]
 [1 1 1 1 1 1 0 0 0 0]
 [1 1 0 1 1 0 0 0 0 0]
 [1 0 1 0 0 1 0 1 0 0]
 [0 1 0 1 1 0 0 0 0 0]
 [1 1 1 0 0 1 0 0 0 0]
 [0 0 1 1 0 1 0 0 0 0]
 [1 0 1 0 0 1 0 0 0 0]
 [1 0 1 1 0 0 0 0 0 0]
 [1 0 0 0 0 0 1 1 0 0]
 [1 1 0 0 0 0 1 0 0 0]
 [0 1 0 0 0 1 0 0 0 0]
 [1 0 0 1 0 0 0 0 0 0]
 [0 0 1 1 0 0 0 0 0 0]
 [1 1 0 0 0 0 0 0 0 0]
 [0 1 0 0 0 0 0 0 0 0]
 [0 0 0 1 0 0 0 0 0 0]
 [1 0 0 0 0 0 0 0 0 0]
 [0 0 0 1 0 0 0 0 0 0]
 [0 1 0 0 0 0 0 0 0 0]
 [0 0 1 0 0 0 0 0 0 0]
 [0 0 0 0 0 0 1 0 0 0]
 [0 1 0 0 0 0 0 0 0 0]]

I would like to create a graph using NetworkX from this matrix, but could not find how to do that. NetworkX from_numpy_matrix works only with adjacency matrices. Here is a good example of how to create an incidence matrix using NetworkX (but that's not my case, because I have already an incidence matrix to begin with). I have also tried this, but got the nasty error:

File "C:\Python27\lib\site-packages\networkx\convert.py", line 150, in to_networkx_graph
    "Input is not a correct numpy matrix or array.")
networkx.exception.NetworkXError: Input is not a correct numpy matrix or array.

Looks a simple question, but perhaps it isn't. Can anyone help me with it?

Thanks in advance!

1

1 Answers

8
votes

Networkx has a handy nx.from_numpy_matrix function taking an adjacency matrix, so once we convert the incidence matrix to an adjacency matrix, we're good.

Say we start with the incidence matrix

im = np.array([[0, 1, 1], [0, 1, 1], [0, 0, 0]])

To convert it to an adjacency matrix, first let's see which nodes are connected:

am = (np.dot(im, im.T) > 0).astype(int)

Here we're just checking if any two nodes have at least one edge between them.

If you want to remove self loops, you can call

np.fill_diagonal(am, 0)

Let's see now am:

>>> am
array([[0, 1, 0],
       [1, 0, 0],
       [0, 0, 0]])

To create the graph, now we can just call

networkx.from_numpy_matrix(am)