NetworkX: adjacency matrix does not correspond to graph
<p>Say I have two options for generating the <strong>Adjacency Matrix</strong> of a network: <code>nx.adjacency_matrix()</code> and my own code. I wanted to test the correctness of my code and came up with some strange inequalities.</p>

<p>Example: a <code>3x3</code> lattice network.</p>

<pre><code>import networkx as nx
N=3
G=nx.grid_2d_graph(N,N)
pos = dict( (n, n) for n in G.nodes() )
labels = dict( ((i,j), i + (N-1-j) * N ) for i, j in G.nodes() )
nx.relabel_nodes(G,labels,False)
inds=labels.keys()
vals=labels.values()
inds.sort()
vals.sort()
pos2=dict(zip(vals,inds))
plt.figure()
nx.draw_networkx(G, pos=pos2, with_labels=True, node_size = 200)
</code></pre>

<p>This is the visualization:
<a href="https://i.stack.imgur.com/0QbJH.png" rel="noreferrer"><img src="https://i.stack.imgur.com/0QbJH.png" alt="enter image description here"></a></p>

<p>The adjacency matrix with <code>nx.adjacency_matrix()</code>:</p>

<pre><code>B=nx.adjacency_matrix(G)
B1=B.todense()

[[0 0 0 0 0 1 0 0 1]
 [0 0 0 1 0 1 0 0 0]
 [0 0 0 1 0 1 0 1 1]
 [0 1 1 0 0 0 1 0 0]
 [0 0 0 0 0 0 0 1 1]
 [1 1 1 0 0 0 0 0 0]
 [0 0 0 1 0 0 0 1 0]
 [0 0 1 0 1 0 1 0 0]
 [1 0 1 0 1 0 0 0 0]]
</code></pre>

<p>According to it, node <code>0</code> (entire 1st row and entire 1st column) is connected to nodes <code>5</code> and <code>8</code>. But if you look at the image above this is wrong, as it connects to nodes <code>1</code> and <code>3</code>.</p>

<p>Now my code (to be run in in the same script as the above):</p>

<pre><code>import numpy
import math

P=3

def nodes_connected(i, j):
     try: 
        if i in G.neighbors(j):
            return 1
     except nx.NetworkXError:
        return False          

A=numpy.zeros((P*P,P*P))

for i in range(0,P*P,1):
    for j in range(0,P*P,1):

        if i not in G.nodes():
            A[i][:]=0
            A[:][i]=0
        elif i in G.nodes():
            A[i][j]=nodes_connected(i,j)
                A[j][i]=A[i][j]

for i in range(0,P*P,1):
    for j in range(0,P*P,1):
            if math.isnan(A[i][j]):
                A[i][j]=0 

print(A)
</code></pre>

<p>This yields:</p>

<pre><code>[[ 0.  1.  0.  1.  0.  0.  0.  0.  0.]
 [ 1.  0.  1.  0.  1.  0.  0.  0.  0.]
 [ 0.  1.  0.  0.  0.  1.  0.  0.  0.]
 [ 1.  0.  0.  0.  1.  0.  1.  0.  0.]
 [ 0.  1.  0.  1.  0.  1.  0.  1.  0.]
 [ 0.  0.  1.  0.  1.  0.  0.  0.  1.]
 [ 0.  0.  0.  1.  0.  0.  0.  1.  0.]
 [ 0.  0.  0.  0.  1.  0.  1.  0.  1.]
 [ 0.  0.  0.  0.  0.  1.  0.  1.  0.]]
</code></pre>

<p>which says that node <code>0</code> is connected to nodes <code>1</code> and <code>3</code>. <strong>Why does such difference exist? What is wrong in this situation?</strong></p>