0

我已经提取了一些我曾经在 networkx 1.6.1 中使用过的代码。gml在 1.8.1 上,它在写入or时不起作用graphml

问题归结为无法在数据字典中写入边缘属性,如下所示:

BasicGraph = nx.read_graphml("KeggCompleteEng.graphml")

for e,v in BasicGraph.edges_iter():
    BasicGraph[e][v]['test'] = 'test'

nx.write_graphml(BasicGraph, "edgeTester.graphml")

导致错误:

AttributeError: 'str' object has no attribute 'items'

当我使用时:for e,v,data in BasicGraph.edges_iter(data=True):数据打印如下:

{'root_index': -3233, 'label': u'unspecified'}
test

AKA 新属性在字典之外。

文档说我应该能够像上面那样做。但是,我想我犯了一个愚蠢的错误,很高兴能回到正确的道路上!

编辑:

所以我用程序内部生成的图表运行程序: BasicGraph = nx.complete_graph(100)它运行良好。

然后,我使用来自底漆的示例 graphml 文件运行它:BasicGraph = nx.read_graphml("graphmltest.graphml")这也很有效。(我什至导入和导出 Cytoscape 以检查这不是问题)

所以很明显这是我正在使用的文件。这是它的链接,任何人都可以看到它有什么问题吗?

4

1 回答 1

3

问题是您的图具有平行边,因此 NetworkX 将其作为 MultiGraph 对象加载:

In [1]: import networkx as nx

In [2]: G = nx.read_graphml('KeggCompleteEng.graphml')

In [3]: type(G)
Out[3]: networkx.classes.multigraph.MultiGraph

In [4]: G.number_of_edges()
Out[4]: 7123

In [5]: H = nx.Graph(G) # convert to graph, remove parallel edges

In [6]: H.number_of_edges()
Out[6]: 6160

因此,边的图形对象存储的内部结构是 G[node][node][key][attribute]=value(请注意多重图的额外键字典级别)。

您正在通过以下方式显式修改结构

for e,v in BasicGraph.edges_iter():
    BasicGraph[e][v]['test'] = 'test'

这打破了它。

允许以这种方式修改数据结构,但使用 NetworkX API 更安全

In [7]: G = nx.MultiGraph()

In [8]: G.add_edge(1,2,key='one')

In [9]: G.add_edge(1,2,key='two')

In [10]: G.edges(keys=True)
Out[10]: [(1, 2, 'two'), (1, 2, 'one')]

In [11]: G.add_edge(1,2,key='one',color='red')

In [12]: G.add_edge(1,2,key='two',color='blue')

In [13]: G.edges(keys=True,data=True)
Out[13]: [(1, 2, 'two', {'color': 'blue'}), (1, 2, 'one', {'color': 'red'})]
于 2013-10-16T23:09:21.203 回答