2013-10-16 58 views
0

我已經拉起了一些代碼,我在網絡x的1.6.1中玩過。在1.8.1上寫入gmlgraphml時不起作用。當我使用Networkx邊緣不能正確添加屬性

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

的問題歸結爲暫時無法寫入數據字典內邊緣屬性,像這樣:

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

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

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

導致錯誤for e,v,data in BasicGraph.edges_iter(data=True):數據打印出像所以:

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

也是新屬性在字典之外。

該文件說我應該能夠像上面那樣做。但是,我想我犯了一個愚蠢的錯誤,並希望被放回正確的道路上!

編輯:

於是我運行該程序與程序中生成的圖表:BasicGraph = nx.complete_graph(100),它運行得很好。

然後我用一個來自底圖的示例graphml文件運行它:BasicGraph = nx.read_graphml("graphmltest.graphml"),這也工作。 (我甚至導入和導出Cytoscape來檢查這不是問題)

所以顯然這是我使用的文件。 Here's一個鏈接,任何人都可以看到它有什麼問題嗎?

+0

您可以修改代碼以不需要加載該文件? – tacaswell

+0

用'nx.complete_graph()'和另一個graphml文件試了一下,它們都工作正常。查看更新! – Darkstarone

回答

3

的問題是您的圖形是具有平行的邊緣,從而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] [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'})]