在this question的答案中,有代码创建带有一定数量节点的所有树。
问题是,我尝试使用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.]]]
我试图逐步重新创建代码,但是我看不到什么以及为什么它不起作用,一切似乎都很好,因此,任何帮助将不胜感激,谢谢!
[...] 节点列表(列表,可选)–行和列按以下顺序排序 到节点列表中的节点。如果nodelist为None,则排序为 由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
因此,邻接矩阵在所有情况下都是正确的(图形显示正确,因此边缘必须正确记录),但是顺序混乱。您需要在nodelist参数中明确指定节点的顺序:
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.]]