Python NetworkX creating graph from incidence matrix
<p>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):</p>

<pre><code>[[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]]
</code></pre>

<p>I would like to create a graph using NetworkX from this matrix, but could not find how to do that. NetworkX <a href="https://networkx.github.io/documentation/networkx-1.7/reference/generated/networkx.convert.from_numpy_matrix.html" rel="nofollow">from_numpy_matrix</a> works only with adjacency matrices. <a href="https://stackoverflow.com/questions/28549762/how-to-create-an-incidence-matrix">Here</a> 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 <a href="https://dschult-networkx.readthedocs.io/en/latest/_modules/networkx/convert_matrix.html" rel="nofollow">this</a>, but got the nasty error:  </p>

<pre><code>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.
</code></pre>

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

<p>Thanks in advance!</p>

<p>Networkx has a handy <a href="http://networkx.github.io/documentation/networkx-1.7/reference/generated/networkx.convert.from_numpy_matrix.html" rel="nofollow"><code>nx.from_numpy_matrix</code> function</a> taking an adjacency matrix, so once we convert the incidence matrix to an adjacency matrix, we're good.</p>

<p>Say we start with the incidence matrix</p>

<pre><code>im = np.array([[0, 1, 1], [0, 1, 1], [0, 0, 0]])
</code></pre>

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

<pre><code>am = (np.dot(im, im.T) &gt; 0).astype(int)
</code></pre>

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

<p>If you want to remove self loops, you can call</p>

<pre><code>np.fill_diagonal(am, 0)
</code></pre>

<p>Let's see now <code>am</code>:</p>

<pre><code>&gt;&gt;&gt; am
array([[0, 1, 0],
       [1, 0, 0],
       [0, 0, 0]])
</code></pre>

<p>To create the graph, now we can just call</p>

<pre><code>networkx.from_numpy_matrix(am)
</code></pre>

python networkx