使用 networkx 创建邻接矩阵时遇到问题

Trouble creating adjacency matrix using networkx

的答案中,有代码创建了所有具有一定数量节点的树。

问题是我尝试使用networkx中的内置函数创建相应的邻接矩阵nx.to_numpy_array但由于某种原因它不起作用,代码如下:

#Function created by warped

import itertools
import numpy as np
import networkx as nx
import matplotlib.pyplot as plt 

def make_all_trees(nodes):
    # generate all pairwise combinations of nodes
    edges =  [a for a in itertools.product(range(nodes), range(nodes))]

    # use sets to lose..
    # ..symmetric edges: (0,1), (1,0) => keep only (0,1) 
    edges = list(set([tuple(set(e)) for e in edges]))
    # ..and self-loops: (0,0)
    edges = [e for e in edges if len(e)>1]

    trees = []
    # generate all graphs that have nodes-1 edges
    for o in itertools.combinations(edges, nodes-1):
        #make sure that all nodes are in the edgelist:
        flattened = [item for sublist in o for item in sublist]

        if len(set(flattened)) == nodes:
            G = nx.Graph()
            G.add_edges_from(o)
            # make sure all nodes are connected
            if len(list(nx.connected_components(G)))==1:
                trees.append(G)

    return trees

#This is what I added it to create the corresponding adjacency matrix

trees = make_all_trees(3) #This create all the graph trees with 3 nodes, so it creates 3 trees

adjaux = []
for i in trees:
    adjaux.append(nx.to_numpy_array(i))

print(np.array(adjaux))

#Draws the graph
for p, tree in enumerate(trees):
    plt.subplot(4,4, p+1)
    nx.draw_networkx(tree)
plt.show()


输出如下

#Adjacency matrix created 

adjaux = [[[0. 1. 0.]   [[0. 1. 1.]     [[0. 1. 0.] 
           [1. 0. 1.]    [1. 0. 0.]      [1. 0. 1.]
           [0. 1. 0.]]   [1. 0. 0.]]     [0. 1. 0.]]]


如你所见,虽然所有的树图都是正确的,前两个邻接矩阵是正确的,但最后一个是错误的,输出应该是:

adjaux = [[[0. 1. 0.]   [[0. 1. 1.]     [[0. 0. 1.] 
           [1. 0. 1.]    [1. 0. 0.]      [0. 0. 1.]
           [0. 1. 0.]]   [1. 0. 0.]]     [1. 1. 0.]]]

我试着一步一步地重新创建代码,但我看不出它不起作用的原因和原因,一切似乎都很好,所以任何帮助将不胜感激,谢谢!

nx.to_numpy_array 的文档:

[...] nodelist (list, optional) – The rows and columns are ordered according to the nodes in nodelist. If nodelist is None, then the ordering is produced by G.nodes(). [...]

正在检查图表的顺序:

trees = make_all_trees(3)
for tree in trees:
    print(tree.nodes())

#output:
[0, 1, 2] # first tree
[0, 1, 2] # second tree
[1, 2, 0] # third tree, node order is changed

所以,邻接矩阵在所有情况下都是正确的(图形显示正确,所以边缘必须正确记录),但顺序乱了。 您需要在节点列表参数中明确指定节点的顺序:

adjaux=[]
for tree in trees:
    adjaux.append(nx.to_numpy_array(tree, nodelist=sorted(tree.nodes())))

for a in adjaux:
    print('-'*10)
    print(a)

----------
[[0. 1. 0.]
 [1. 0. 1.]
 [0. 1. 0.]]
----------
[[0. 1. 1.]
 [1. 0. 0.]
 [1. 0. 0.]]
----------
[[0. 0. 1.]
 [0. 0. 1.]
 [1. 1. 0.]]