Johannes Wiesner
Johannes Wiesner

Reputation: 1307

How to convert a list of nodes and edges to an adjacency matrix?

I am building a Dash app including dash_cytoscape where the user is able to connect and disconnect nodes in a given network. Now I would like to write a function that reconstructs the adjacency matrix from a list of edges and nodes of that network. I found this thread on StackOverflow which goes roughly in the right direction, except that my case seems to be an edge case of this problem where not every node is necessarily connected to another node. For example, the network could look like this:

enter image description here

and the correct adjacency matrix for this network could look like this:

A = np.array([[0,1,0,0,0],
              [1,0,0,0,0],
              [0,0,0,0,0],
              [0,0,0,0,2],
              [0,0,0,2,0]])

I am able to obtain both a list of nodes and edges from the network:

edges = [('3', '4', 2),('0', '1', 1)]
nodes = ['0', '1', '2', '3', '4']

But how to get from there to the correct adjacency matrix?

Upvotes: 1

Views: 4660

Answers (3)

Johannes Wiesner
Johannes Wiesner

Reputation: 1307

Based on the suggestion from user Fonzie:

n_nodes = len(nodes)
A = np.zeros((n_nodes,n_nodes))

for edge in edges:
    i = int(edge[0])
    j = int(edge[1])
    weight = edge[2]
    A[i,j] = weight
    A[j,i] = weight

Upvotes: 0

Ajax1234
Ajax1234

Reputation: 71451

You can iterate over edges and update a pre-populated list with the weights:

edges = [('3', '4', 2),('0', '1', 1)]
nodes = ['0', '1', '2', '3', '4']
m = max(map(int, nodes))
d = [[0 for _ in range(m+1)] for _ in range(m+1)]
for x, y, w in edges:
   d[int(x)][int(y)] = w
   d[int(y)][int(x)] = w

Output:

[[0, 1, 0, 0, 0], 
 [1, 0, 0, 0, 0], 
 [0, 0, 0, 0, 0], 
 [0, 0, 0, 0, 2], 
 [0, 0, 0, 2, 0]]

Upvotes: -1

Fonzie
Fonzie

Reputation: 186

You just need to create a matrix M of size V x V where V is your total number of nodes, and populate it with zeroes. Then for each element in your edges list (say (i, j, w)), you know that i, j are the indices to modify in your adjacency matrix. Thus just set M[i, j] = w.

NB : if your graph is undirected, remember that an edge from node i to node j is the same as an edge from node j to node i, so you also have to set M[j,i]=w.

Upvotes: 1

Related Questions