我有一个NxN
常规网络,每个节点都有一(X,Y)
组坐标。节点由单元分隔。网络如下所示:
(0,0) (1,0) (2,0)
(0,1) (1,1) (2,1)
(0,2) (1,2) (2,2)
我希望能够计算从每个节点到所有其他节点的欧几里得距离。例子:
#Euclidean distances from node (0,0):
0 sqrt(1) sqrt(4)
sqrt(1) sqrt(2) sqrt(5)
sqrt(4) sqrt(5) sqrt(8)
然后,我想绘制距离分布,它告诉我给定距离具有某个值的频率。然后我想将图表变成对数对数图。
这是我的尝试:
import networkx as nx
from networkx import *
import matplotlib.pyplot as plt
#Creating the regular network
N=10 #This can vary
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)) #Dict storing the node coordinates
nx.draw_networkx(G, pos=pos2, with_labels=False, node_size = 15)
#Computing the edge length distribution
def plot_edge_length_distribution(): #Euclidean distances from all nodes
lengths={}
for k, item in pos2:
for t, elements in pos2:
if k==t:
lengths[k]=0
else:
lengths[k]=((pos2[t][2]-pos2[k][2])**2)+((pos2[t][1]-pos2[k][1])**2) #The square distance (it's ok to leave it like this)
items=sorted(lengths.items())
fig=plt.figure()
ax=fig.add_subplot(111)
ax.plot([k for (k,v) in items],[v for (k,v) in items],'ks-')
ax.set_xscale("log")
ax.set_yscale("log")
title_string=('Edge Length Distribution')
subtitle_string=('Lattice Network | '+str(N)+'x'+str(N)+' nodes')
plt.suptitle(title_string, y=0.99, fontsize=17)
plt.title(subtitle_string, fontsize=9)
plt.xlabel('Log l')
plt.ylabel('Log p(l)')
ax.grid(True,which="both")
plt.show()
plot_edge_length_distribution()
编辑
运行时,此脚本抛出错误:TypeError: 'int' object is not iterable
,指向我写的行for k, item in pos2:
。我哪里错了?