Search code examples
pythonnetworkxgraph-theoryadjacency-matrixcytoscape

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?


Solution

  • 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