2013-03-26 59 views
6

我有一個NetworkX圖。我想知道如何在多個節點之間做edge contractionPython網絡x:邊緣收縮

例如,如果我想承攬X,Y和Z:

  _ node A _ 
     _/ |  \_ 
node X --- node Y --- node Z 

將成爲

  node A 
      |  
      node XYZ (or whatever X/Y/Z) 

圖形創作是沒有問題的。有用。我想通過合併具有相同「含義」的節點來縮小圖形:我稱之爲「end lvl」(節點名稱長度等於7)並鏈接在一起的節點。

我發現在NetworkX凝聚作用,所以我嘗試使用它:

# edge contraction for same nodes 
# for each node, get the links to other nodes "end lvl" 
# if there is such a link, it means that these node are 
# the sames 
# 
# copy graph 
I = G 
for n,d in G.nodes(data=True): 
    if n in I.nodes(): 
     if len(n) == 7: 
      # list of nodes adjacent to n : filter only "end lvl" nodes 
      neighbors = [ node for node in I.neighbors(n) if len(node) == 7 ] 
      nodes_to_merges = neighbors.append(n) 
      I = nx.condensation(I,scc=nodes_to_merges) 

當我轉換成JSON我得到的東西是:

{"directed": true, "graph": [], "nodes": [{"id": 0}], "links": [], "multigraph": false} 

有一個問題,因爲你可以看到...

對函數的引用是here

+0

一個解決方案是使用字典表示(to_dict_of_dicts)手動執行此操作。 – keyser 2013-03-26 15:30:54

+0

好吧,我不熟悉圖形,但我應該改善我的問題,因爲@ zodiac問我。它來了。 – user1254498 2013-03-26 15:40:06

+0

節點(),neighbours()和condensation()函數做了什麼?什麼是NX? – xuanji 2013-03-26 15:48:57

回答

3

如何:

add_node(XYZ) 
add_edge(XYZ, A) 
for edge incident on (X, Y, Z): 
    v = nodes in edge not in (X, Y, Z, A) 
    if v: 
     remove_edge(edge) 
     add_edge(v, XYZ) 
for node in (X, Y, Z): 
    remove_node(node) 
+0

我用python和networkx函數重寫了你的僞代碼。我做了我想要的。謝謝。 – user1254498 2013-03-27 12:56:04

+0

請注意,上述內容將刪除邊緣和節點的任何屬性信息。 – 2014-10-02 07:09:56