2016-03-30 21 views
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) 

、私は与えられた距離が一定の値をとる頻度を私に告げる距離分布を、描きたいです。グラフをログ・ログ・プロットに変換します。

これは私の試みです:私はfor k, item in pos2:を書いた行を指し、TypeError: 'int' object is not iterable:実行している場合

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() 

EDIT

、このスクリプトはエラーをスローします。 どこが間違っているのですか?

答えて

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対角線除去の左下にすべてと

    0 1 2 
    1 0 1 
    2 1 0 
    

    します。

  • [1,2,1]の右上の「平坦化」。

平坦な結果からの距離を再構築することは困難ではありません。

+0

私はこれが好きですが、何か不足していると思います。 'NxN'ノードのネットワークを持っているとしましょう:この場合、あなたが記述する種類の'(N-1)x(N-1) 'の行列を生成すると思います。しかし、あなたの例では、 '1.'、' 2.'などの距離が計算される参照ノードは何か分かりません。私が何を意味するか見ていますか? – FaCoffee

+1

しかし、* N X N *個のノードのネットワークは、* m = N^2 *個のノードがあることを意味するだけで、いいえ?距離の数は[mを2つ選択する](https://en.wikipedia.org/wiki/Binomial_coefficient)です。何か不足していますか? –

+0

はい、私は間違っていました。距離の総数はmです。これは2つの距離の行列を選択することを意味します。しかし、私の質問は、 'distance.pdist(coords)'から得られた '1.'、' 2.'などの値はどのノードにありますか?なぜなら、開始ノードが '(0,0)'なら、 'array([0.、1.、2.。])'という出力を持つことになるからです。 – FaCoffee

関連する問題