Networkx边缘未正确添加属性

2024-10-01 04:50:09 发布

您现在位置:Python中文网/ 问答频道 /正文

我在networkx的1.6.1中找到了一些我曾经使用过的代码。在1.8.1中,当写入gmlgraphml时,它不起作用。在

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

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

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

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

导致错误:

^{pr2}$

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

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

AKA新属性在字典之外。在

文件上说我应该可以像上面那样做。然而,我想我犯了一个愚蠢的错误,希望能回到正确的道路上来!在

编辑:

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

然后我用primer:BasicGraph = nx.read_graphml("graphmltest.graphml")中的一个示例graphml文件来运行它,这也起到了作用。(我甚至导入和退出Cytoscape来检查这不是问题所在)

很明显我用的是这个文件。Here's一个链接,有人能看到它有什么问题吗?在


Tags: 文件数据intest程序forreaddata
1条回答
网友
1楼 · 发布于 2024-10-01 04:50:09

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

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(注意多图的额外键字典级别)。在

通过以下方式显式修改结构

^{pr2}$

这就破坏了它。在

允许以这种方式修改数据结构,但使用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'})]

相关问题 更多 >