Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python networkx : edge contraction

I have a NetworkX graph. I would like to know how to do edge contraction between multiple nodes.

For example, if I wanted to contract X, Y and Z:

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

Would become

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

Graph creation is not the problem. It works. I want to reduce the graph by merging nodes that have the same "meanings": nodes that I call "end lvl" (node name length is equal to 7) and that are linked together.

I have found the condensation function in NetworkX so I tried to use it:

# 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)

The thing I got when I convert to JSON is:

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

There is a problem as you can see...

Reference to functions are here.

like image 348
qdelettre Avatar asked Mar 26 '13 15:03

qdelettre


1 Answers

How about:

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)
like image 119
user650654 Avatar answered Sep 24 '22 22:09

user650654