问题描述
我正在构建一个包含 dash_cytoscape
的 Dash 应用程序,用户可以在其中连接和断开给定网络中的节点。现在我想编写一个函数,从该网络的边和节点列表中重建邻接矩阵。我发现 this thread on StackOverflow 大致朝着正确的方向发展,但我的情况似乎是此问题的边缘情况,其中并非每个节点都必须连接到另一个节点。例如,网络可能如下所示:
该网络的正确邻接矩阵可能如下所示:
A = np.array([[0,1,0],[1,[0,2],2,0]])
我能够从网络中获取节点和边的列表:
edges = [('3','4',2),('0','1',1)]
nodes = ['0','2','3','4']
但是如何从那里得到正确的邻接矩阵?
解决方法
您只需要创建一个大小为 >>> img_bytes = fig.to_image(format="png")
>>> img=base64.b64encode(fig).decode("ascii")
Traceback (most recent call last):
File "<stdin>",line 1,in <module>
File "C:\Users\bhaskaja\AppData\Local\Continuum\anaconda3\lib\base64.py",line 58,in b64encode
encoded = binascii.b2a_base64(s,newline=False)
TypeError: a bytes-like object is required,not 'Figure'
>>> img=base64.b64encode(fig).decode("ascii")
Traceback (most recent call last):
File "<stdin>",not 'Figure'
的矩阵 M
,其中 V x V
是您的节点总数,并用零填充它。然后对于 V
列表中的每个元素(比如 edges
),您知道 (i,j,w)
是要在邻接矩阵中修改的索引。
因此只需设置 i,j
。
注意:如果您的图是无向图,请记住从节点 i 到节点 j 的边与从节点 j 到节点 i 的边相同,因此您还必须设置 M[i,j] = w
。
您可以遍历 edges
并使用权重更新预先填充的列表:
edges = [('3','4',2),('0','1',1)]
nodes = ['0','2','3','4']
m = max(map(int,nodes))
d = [[0 for _ in range(m+1)] for _ in range(m+1)]
for x,y,w in edges:
d[int(x)][int(y)] = w
d[int(y)][int(x)] = w
输出:
[[0,1,0],[1,[0,2],2,0]]
,
基于用户 Fonzie 的建议:
n_nodes = len(nodes)
A = np.zeros((n_nodes,n_nodes))
for edge in edges:
i = int(edge[0])
j = int(edge[1])
weight = edge[2]
A[i,j] = weight
A[j,i] = weight