Search code examples
pythongraph-theorygraph-tool

Generating incorrect graphs from adjacency matrices using graph-tool on Python


I am trying to generate a graph from an adjacency matrix. I know it is something that has already been asked here but I can't get to generate one correctly. My code is

import numpy as np
import graph_tool.all as gt

L = 10; p = 0.6

Adj = np.zeros((L,L))

for i in range(0,L):
    for j in range(i+1,L):
        if np.random.rand() < p:
            Adj[i,j] = 1

Adj = Adj + np.transpose(Adj)

print('Adjacency matrix is \n', Adj)

g = gt.Graph(directed=False)
g.add_edge_list(Adj.nonzero())

gt.graph_draw(g, vertex_text=g.vertex_index, output="two-nodes.pdf")

It generates an adjacency matrix with each connection happening with a probability of 60%. One result is

Adjacency matrix is 
 [[0. 1. 1. 0. 1. 0. 1. 1. 1. 0.]
 [1. 0. 1. 1. 1. 1. 1. 0. 1. 1.]
 [1. 1. 0. 1. 1. 0. 1. 1. 1. 0.]
 [0. 1. 1. 0. 1. 1. 1. 0. 1. 1.]
 [1. 1. 1. 1. 0. 1. 1. 1. 0. 1.]
 [0. 1. 0. 1. 1. 0. 0. 0. 1. 0.]
 [1. 1. 1. 1. 1. 0. 0. 1. 0. 1.]
 [1. 0. 1. 0. 1. 0. 1. 0. 0. 0.]
 [1. 1. 1. 1. 0. 1. 0. 0. 0. 1.]
 [0. 1. 0. 1. 1. 0. 1. 0. 1. 0.]]

But I don't know why the graphical result is this one which is clearly incorrect.


Solution

  • As stated in add_edge_list docs, you need

    an iterator of (source, target) pairs where both source and target are vertex indexes, or a numpy.ndarray of shape (E,2), where E is the number of edges, and each line specifies a (source, target) pair

    In your case, you're passing a single tuple (check the result of Adj.nonzero()). To fix it, just try this:

    g.add_edge_list(np.transpose(Adj.nonzero()))