NetworkX:如何创建加权图的关联矩阵?

时间:2016-10-19 11:44:08

标签: python matrix graph networkx

创建了这样的网格网络:

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

为每条边分配了一个与其长度相对应的重量(在这个简单的情况下,所有长度= 1):

G.edges()

这就是我[(0, 1, 1.0), (0, 10, 1.0), (1, 11, 1.0), (1, 2, 1.0),... ] #Trivial case: all weights are unitary 的样子:( startnode ID,endnode ID,weight)

nx.incidence_matrix(G, nodelist=None, edgelist=None, oriented=False, weight=None)

如何创建考虑刚刚定义的权重的关联矩阵?我想使用weight,但在这种情况下weight正确值是什么?

docs表示insert是一个字符串,代表"边缘数据键,用于提供矩阵中的每个值",但具体是什么意思?我也没有找到相关的例子。

有什么想法吗?

1 个答案:

答案 0 :(得分:1)

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

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