Home > Blockchain >  Problem with adjacency matrix in 2d grid graph in Python
Problem with adjacency matrix in 2d grid graph in Python

Time:04-14

The code generates a 2D grid graph. However, there is problem with the adjacency matrix it generates. For instance, node 1 is not connected to 3 but in the matrix, it shows value 1. For node 2, it shows value 0 even though it is connected to node 3 and similarly for other nodes. The adjacency matrix and the 2D grid graph are attached here.

import numpy as np
import networkx as nx

G = nx.grid_2d_graph(3,3)
new_nodes = {e: n for n, e in enumerate(G.nodes, start=1)}
new_edges = [(new_nodes[e1], new_nodes[e2]) for e1, e2 in G.edges]
G = nx.Graph()
G.add_edges_from(new_edges)
nx.draw(G, with_labels=True)

A1 = nx.adjacency_matrix(G) 
A=A1.toarray()
print([A]) 

Figure

CodePudding user response:

the problem I think is with the relabeling. you can relabel your graph with convert_node_labels_to_integers(G) for better relabeling. try this:

import numpy as np
import networkx as nx

G = nx.grid_2d_graph(3,3)
nodes= {i:n 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()
print([A]) 

relabeling doc from networkx.com: https://networkx.org/documentation/stable/reference/relabel.html

  • Related