Python:如何计算常规网络的欧几里德距离分布?

时间:2016-03-30 16:33:02

标签: 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)     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:的行。 我哪里出错?

1 个答案:

答案 0 :(得分:1)

函数scipy.spatial.distance.pdist可以尽可能高效地完成此任务。

请考虑以下事项:

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]。

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

相关问题