Python:如何计算规则网络的欧氏距离分布?

Python:如何计算规则网络的欧氏距离分布?,python,networkx,euclidean-distance,loglog,Python,Networkx,Euclidean Distance,Loglog,我有一个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)

我有一个
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”对象不可编辑
,指向我为k编写的
行,pos2:
哪里出错了?

该函数尽可能高效地执行此操作

考虑以下几点:

from scipy.spatial import distance
import numpy as np

coords = [np.array(list(c)) for c in [(0,0),(1,0), (2,0)]]
>>> distance.pdist(coords)
array([ 1.,  2.,  1.])
该函数返回距离矩阵的右上部分-对角线为0,左下部分可通过转置获得

例如,上述对应于

0 1 2
1 0 1
2 1 0

  • 0对角线及其左下角的所有内容都已删除

  • 右上角“展平”为[1,2,1]


从展平结果重建距离并不困难。

我喜欢这样,但我想缺少了一些东西。假设您有一个由
NxN
节点组成的网络:在本例中,我希望生成您描述的
(N-1)x(N-1)
矩阵。但在您的示例中,我看不出计算距离
1.
2.
等的参考节点是什么。你明白我的意思吗?但是一个由nxn个节点组成的网络只意味着有m=N^2个节点,不是吗?因此,距离的数量将是。我遗漏了什么吗?是的,我错了。总距离为m,选择2。这意味着我们让m选择2个距离矩阵。但我的问题是:从距离.pdist(coords)得到的值
1.
2.
等是指哪个节点?因为如果起始节点是
(0,0)
,我希望将其作为输出
数组([0,1,2.])
@FC84请参见说明。@FC84但在我给出的示例中,没有(1,1)元素,也没有报告的0(推断出的零位于对角线上,这意味着任何元素与自身之间的距离为0)。我无法将你的最后一个问题与我的答案相匹配。