我正在通过networkx中的blockmodel函数。这似乎与我想要的非常相似。
我希望在networkx图中合并两个节点,并将其替换为与要连接的任何节点相对应的节点标签。其余节点应保持原样,名称不做任何更改。 (节点连接规则如块模型1教程中所述)
如何实现将2个节点合并为一个看似简单的任务?我想在带有加权边的无向图上进行。
答案 0 :(得分:1)
这是我尝试为我正在处理的图形着色程序创建一个合并函数。但是,它不适用于加权边缘。
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