3
我有一个NxN
常规网络,其中每个节点有一组(X,Y)
坐标。节点由单元分隔。该网络是这样的:Python:如何计算常规网络的欧氏距离分布?
(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:
线指向。 我哪里错了?
我喜欢这个,但我想有一些缺失。假设你有一个NxN节点的网络:在这种情况下,我希望生成你描述的那种'(N-1)×(N-1)'矩阵。但在你的例子中,我没有看到从哪个参考节点计算距离'1.','2'等。你明白我的意思吗? – FaCoffee
但是* N X N *个节点的网络仅仅意味着有* m = N^2 *个节点,不是?所以距离的数量是[m选择2](https://en.wikipedia.org/wiki/Binomial_coefficient)。我错过了什么吗? –
是的,我错了。距离的总数是m选择2.这意味着我们可以选择2个距离矩阵。但是我的问题是:从'distance.pdist(coords)'得到的值'1.','2'等等是什么节点 - 指的是?因为如果起始节点是'(0,0)',我希望将其作为输出数组([0.,1,2。])'。 – FaCoffee