简体   繁体   中英

Coalesce 2 nodes in a networkx graph

I was going though the blockmodel function in networkx. It seems something very similar to what I want.

I wish to coalesce two nodes in a networkx graph and replace it by node labels corresponding to any of the nodes being joined. The rest of the nodes should remain as is without any change in their names. (The node joining rules are as explained in the blockmodel 1 tutorial)

  • As for what I understood, blockmodel requires creating explicit paritions of the whole graph before it could be used, which is not so convenient.
  • There is no control over the names of the block models formed (ie. nodes of the new graph).

How can I achieve this seemingly simpler task of collapsing 2 nodes into one? I want to do it over an undirected graph with weighted edges.

Here's my attempt at creating a coalesce function for a graph coloring program I'm working on. It, however, does not work with weighted edges.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM