2016-10-19 3 views
0

このようなグリッド・ネットワーク作成た:NetworkX:加重グラフの発生行列を作成する方法は?

from __future__ import division 
import networkx as nx 
from pylab import * 
import matplotlib.pyplot as plt 
%pylab inline 

ncols=10 

N=10 #Nodes per side 
G=nx.grid_2d_graph(N,N) 
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=[(N-j-1,N-i-1) for i,j in inds] 
pos2=dict(zip(vals,inds)) 

および各エッジに、その長さ(この些細な場合、全てlenghts = 1)に対応する重みを割り当てた:

#Weights 
from math import sqrt 

weights = dict() 
for source, target in G.edges(): 
    x1, y1 = pos2[source] 
    x2, y2 = pos2[target] 
    weights[(source, target)] = round((math.sqrt((x2-x1)**2 + (y2-y1)**2)),3) 

for e in G.edges(): 
    G[e[0]][e[1]] = weights[e] #Assigning weights to G.edges() 

これは何ですか私G.edges()は、次のようになります(startnodeのID、エンドノードのID、重量)

[(0, 1, 1.0), 
(0, 10, 1.0), 
(1, 11, 1.0), 
(1, 2, 1.0),... ] #Trivial case: all weights are unitary 

どのように考慮した入射行列を作成することができますちょうど定義されている重み? nx.incidence_matrix(G, nodelist=None, edgelist=None, oriented=False, weight=None)を使用しますが、となり、ここではweightとなりますか?

docsweightは、「マトリックスの各値を提供するために使用されるエッジデータキー」を表す文字列ですが、具体的にはどういう意味ですか?私はまた、関連する例を見つけることに失敗しました。

アイデア?

答えて

1

ここでは、エッジ属性を適切に設定する方法と、加重インシデンスマトリックスを生成する方法を示す簡単な例を示します。あなたは、マトリックス内のノードやエッジの特定の順序は、ノードリスト=とedgelistを使用したい場合は

import networkx as nx 
from math import sqrt 

G = nx.grid_2d_graph(3,3) 
for s, t in G.edges(): 
    x1, y1 = s 
    x2, y2 = t 
    G[s][t]['weight']=sqrt((x2-x1)**2 + (y2-y1)**2)*42 

print(nx.incidence_matrix(G,weight='weight').todense()) 

OUTPUT

[[ 42. 42. 42. 0. 0. 0. 0. 0. 0. 0. 0. 0.] 
[ 0. 0. 0. 42. 42. 42. 0. 0. 0. 0. 0. 0.] 
[ 42. 0. 0. 0. 0. 0. 42. 0. 0. 0. 0. 0.] 
[ 0. 0. 0. 0. 0. 0. 0. 42. 42. 42. 0. 0.] 
[ 0. 42. 0. 42. 0. 0. 0. 0. 42. 0. 42. 0.] 
[ 0. 0. 0. 0. 0. 0. 0. 42. 0. 0. 0. 42.] 
[ 0. 0. 0. 0. 0. 42. 0. 0. 0. 42. 0. 0.] 
[ 0. 0. 0. 0. 0. 0. 42. 0. 0. 0. 42. 42.] 
[ 0. 0. 42. 0. 42. 0. 0. 0. 0. 0. 0. 0.]] 

は=オプションのパラメータがnetworkx.indicence_matrixします()。

関連する問題