簡體   English   中英

在networkx圖中合並2個節點

[英]Coalesce 2 nodes in a networkx graph

我正在通過networkx中的blockmodel函數。 似乎與我想要的東西非常相似。

我希望合並networkx圖中的兩個節點,並用與要連接的任何節點相對應的節點標簽替換它。 其余節點應保持原樣,其名稱沒有任何更改。 (節點連接規則如blockmodel 1教程中所述)

  • 據我了解,blockmodel需要在使用整個圖之前創建整個圖的顯式分區,這並不方便。
  • 無法控制所形成的塊模型的名稱(即新圖的節點)。

我如何完成將2個節點折疊為一個的看似更簡單的任務? 我想在具有加權邊緣的無向圖上執行此操作。

這是我為正在處理的圖形着色程序創建合並函數的嘗試。 但是,它不適用於加權邊。

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM