Reputation: 7909
Say that I have a regular grid of points with a given set of coordinates, like this:
Node IDs Coordinates
0 1 2 (0,0) (1,0) (2,0)
3 4 5 (0,1) (1,1) (2,1)
6 7 8 (0,2) (1,2) (2,2)
In my case, the regular grid is a 2D graph
generated with NetworkX.
How can I create a dict
of lists where the key represents each node ID in the network and the list contains the distances from one specific node to those that are connected to it?
Example: node (0,0)
is connected to nodes (1,0)
and (0,1)
. Considering the squared distance to avoid the computational costs of sqrt
, the dict I want would feature mydict={0:[1,1],...]
, since the squared distance from node (0,0)
to its connected neighbors is in both cases 1. Each list is therefore as long as there are neighbors to the each node.
I failed to provide some code as I don't understand how to solve the problem. Many thanks to those who will help.
EDIT
This is how the regular network is created:
import networkx as nx
N=3
G=nx.grid_2d_graph(N,N)
pos = dict( (n, n) for n in G.nodes() )
labels = dict( ((i, j), i + (N-1-j) * N ) for i, j in G.nodes() )
nx.relabel_nodes(G,labels,False)
inds=labels.keys()
vals=labels.values()
inds.sort()
vals.sort()
pos2=dict(zip(vals,inds))
nx.draw_networkx(G, pos=pos2, with_labels=False, node_size = 15)
This is how one can get the neighbors of each node:
for node in G.nodes():
list_of_neigh=G.neighbors(node) #The connected neighbors of node n
And this is how one can access each node in the graph:
G.nodes()
Upvotes: 0
Views: 725
Reputation: 7293
Supposing that nodes are tuples (a,b), something like this (not tested)? :
def dist(n1, n2):
x = n2[0]-n1[0]
y = n2[1]-n1[1]
return math.sqrt(x*x + y*y) # or math.hypot(x, y)
distances = {}
for node in G.nodes():
list_of_neigh = G.neighbors(node)
distances[node] = [dist(node, x) for x in list_of_neigh]
Upvotes: 1