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 的正确值 是什么?

docsweight是代表"the edge data key used to provide each value in the matrix"的字符串,但是具体是什么意思呢?我也没找到相关的例子。

有什么想法吗?

这里是一个简单的例子,展示了如何正确设置边缘属性以及如何生成加权关联矩阵。

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

如果您想要矩阵中节点和边的特定顺序,请使用 nodelist= 和 edgelist= 可选参数 networkx.indicence_matrix()。