Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Recovering nodes from indices in 2D grid graph using Python

This code generates a 2D grid graph with indices corresponding to nodes: {1: (0, 0),2: (0, 1), 3: (0, 2), 4: (1, 0), 5:(1, 1), 6: (1, 2), 7: (2, 0), 8: (2, 1), 9: (2, 2)}. However, I would like to identify specific nodes corresponding to indices. The desired output is attached.

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]) 


Indices= [(1, 1),(2, 2)]

The desired output is

Nodes=[5,9]

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

If you build nodes the other way round (swapping key/value)

nodes = {n: i for i, n in enumerate(G.nodes, start=1)}

then

indices= [(1, 1), (2, 2)]
result = [nodes[i] for i in indices]

gives you

[5, 9]

Is that what you want to do?

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading