Python NetworkX:基于索引的边缘

时间:2018-09-24 16:29:51

标签: python networkx

我想基于数组的索引连接节点。一个例子:

import networkx as nx
import numpy as np

G=nx.Graph()
G.add_nodes_from(["N1","N2","N3","N4","N5"])

set1 = {'A1':np.array([1,0,1,1,0])}
set1["A2"] = np.array([1,1,1,0,1])
set1["A3"]= np.array([0,0,0,0,1])
set1["A4"] = np.array([1,0,1,0,1])

我创建了一个具有五个节点(N1 ... N5)的图形G和一个具有四个键(A1 ... A5)的字典set1。键的值是长度为5且值为0或1的numpy数组。每个条目都对应一个节点。所有具有1的节点都应与边连接。例如。 A1 = [1,0,1,1,0]:节点N1应与N3连接,节点N1与N4连接,而节点N3与N4连接。 A2,A3和A4相同。

因此,我尝试了以下操作:

for key, value in set1.items():
    position = np.where(value)
    for x in np.nditer(position[0]):
        #G.add_edge(names


#nx.draw(G,with_labels=True)

我被困在这里-如果有人可以帮助我,那就太好了。

1 个答案:

答案 0 :(得分:2)

更容易表示的可能是adjacency matrix,它描述了图形中的所有边(权重,可以仅为0/1)。

为此,您需要以不同的方式表示边缘,例如

# adding all-zeros from node 5, since the example dict has no A5 entry
adj = np.array([[1,0,1,1,0], [1,1,1,0,1], [0,0,0,0,1], [1,0,1,0,1], [0,0,0,0,0]])

G1 = nx.from_numpy_array(adj)
# some relabelling because the nodes are automatically given integer labels
mapping = {k:"N{}".format(k+1) for k in G1.nodes()}
G1 = nx.relabel_nodes(G1, mapping)

如果由于其他原因而必须将边缘数据保留在词典中,并且不想生成邻接矩阵,则可以使用以下过程:

for key, value in set1.items():
    # get the source node name, Nx from the key Ax
    source_node = key.replace("A", "N")
    # and the list of targets
    tgt_nodes = np.where(value)[0]
    for tgt_i in tgt_nodes:
        # construct target - note that python arrays are zero-indexed#
        # and your node list starts at 1.
        tgt_node = "N{}".format(tgt_i +1)

        G.add_edge(source_node, tgt_node)

现在让我们以相同的布局绘制两者:

import matplotlib.pyplot as plt
fig, ax = plt.subplots(1,2,sharex=True, sharey=True)    
pos = nx.circular_layout(G)
nx.draw(G, with_labels=True, ax=ax[0], pos=pos)
nx.draw(G1, with_labels=True, ax=ax[1], pos=pos)

two equivalent graphs