簡體   English   中英

NetworkX:如何創建加權圖的關聯矩陣?

[英]NetworkX: how to create an incidence matrix of a weighted graph?

創建了這樣的網格網絡:

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

並為每個邊緣分配了與其長度相對應的權重(在這種情況下,所有長度均為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()樣子:(起始節點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 的正確值是多少?

文檔weight是一個字符串,表示“用於在矩陣中提供每個值的邊緣數據鍵”,但是它的具體含義是什么? 我也沒有找到相關的例子。

有任何想法嗎?

這是一個簡單的示例,顯示了如何正確設置邊緣屬性以及如何生成加權的入射矩陣。

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

輸出值

[[ 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()的nodelist =和edgelist =可選參數。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM