Home > Mobile >  Recovering nodes from indices in 2D grid graph using Python
Recovering nodes from indices in 2D grid graph using Python

Time:04-17

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]

CodePudding user response:

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?

  • Related