Search code examples
pythonnumpynetworkx

Modifying the adjacency matrix in Python


The code generates adjacency matrix of 3x3 network where diagonals are not connected. I want the code to generate adjacency matrix of connected diagonals. I present the current and expected output.

import networkx as nx
G = nx.grid_2d_graph(3,3)
nodes = {n: i for i, n in enumerate(G.nodes, start=1)}
edges = {i: e for i, e in enumerate(G.edges, start=1)}
A1 = nx.adjacency_matrix(G)
A = A1.toarray()
G = nx.convert_node_labels_to_integers(G)
G = nx.relabel_nodes(G, {node: node+1 for node in G.nodes})
nx.draw(G, with_labels=True, pos=nx.spring_layout(G))
A1 = nx.adjacency_matrix(G)
A = A1.toarray()

The current output is

array([[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]], dtype=int32)

enter image description here

The expected output is

array([[0, 1, 0, 1, 1, 0, 0, 0, 0],
       [1, 0, 1, 1, 1, 1, 0, 0, 0],
       [0, 1, 0, 0, 1, 1, 0, 0, 0],
       [1, 0, 0, 0, 1, 0, 1, 1, 0],
       [0, 1, 0, 1, 0, 1, 1, 1, 1],
       [0, 0, 1, 0, 1, 0, 0, 1, 1],
       [0, 0, 0, 1, 1, 0, 0, 1, 0],
       [0, 0, 0, 1, 1, 1, 1, 0, 1],
       [0, 0, 0, 0, 1, 1, 0, 1, 0]], dtype=int32)

enter image description here


Solution

  • You can add an edge for every non-last node in 2D grid. Also you can easily extend the solution for a non square case.

    n = 3    
    G = nx.grid_2d_graph(n,n)
    
    iifrom = jjfrom = range(n-1)
    nnfrom = [(ifrom,jfrom) for ifrom in iifrom for jfrom in jjfrom]
    nnto = [(ifrom+1,jfrom+1) for ifrom in iifrom for jfrom in jjfrom]
    nnfrom += [(ifrom+1,jfrom) for ifrom in iifrom for jfrom in jjfrom]
    nnto += [(ifrom,jfrom+1) for ifrom in iifrom for jfrom in jjfrom]
    G.add_edges_from(zip(nnfrom, nnto))
    
    G = nx.convert_node_labels_to_integers(G)
    G = nx.relabel_nodes(G, {node: node+1 for node in G.nodes})
    A1 = nx.adjacency_matrix(G)
    A = A1.toarray()
    
    print(A)
    nx.draw(G, with_labels=True)