2013-07-05 48 views
0

我正在通過networkx中的blockmodel函數。這看起來與我想要的非常相似。合併網絡x圖中的2個節點

我希望合併網絡x圖中的兩個節點,並將其替換爲與正在連接的任何節點相對應的節點標籤。剩餘的節點應保持不變,名稱不變。 (該節點加入規則在塊模型1教程所解釋)

  • 至於什麼我理解,塊模型需要創建全圖的顯式paritions它可以用於前,這不太方便。
  • 無法控制形成的塊模型的名稱(即新圖的節點)。

我該如何實現這個看起來更簡單的將兩個節點合併爲一個的任務?我想通過具有加權邊的無向圖來完成它。

回答

1

這是我爲圖形着色程序創建coalesce函數的嘗試。但是,它不適用於加權邊緣。

import networkx as nx 
# G is a graph created using nx 
# this is to establish the number of colors 
k = 5 
# inputs node1 and node2 are labels of nodes, e.g. 'a' or 'b' etc. 
def coalesce(G,node1,node2): 
    """Performs Briggs coalescing. Takes in the graph and two nodes. 
    Returns 1 if unable to coalesce, 0 otherwise.""" 
    if node1 in G.neighbors(node2) or node2 in G.neighbors(node1): 
     print "Cannot coalesce. Node",node1,"and node",node2,"share an edge" 
     return 1 
    elif G.degree(node1)+G.degree(node2) >= k: 
     print "Cannot coalesce. Combined degree of",node1,"and",node2,"\ 
is",G.degree(node1)+G.degree(node2),"which is too high for k =",k 
     return 1 
    else: 
     newedge = [] 
     for i in range(len(G.neighbors(node2))): 
      newedge.append((node1 , G.neighbors(node2)[i])) 
     G.add_edges_from(newedge) 
     G.remove_node(node2) 
     nx.relabel_nodes(G, {node1:node1+node2},copy=False) 
    return 0