2013-03-26 58 views
6

我有一个NetworkX图。我想知道如何在多个节点之间做edge contractionPython网络x:边缘收缩

例如,如果我想承揽X,Y和Z:

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

将成为

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

图形创作是没有问题的。有用。我想通过合并具有相同“含义”的节点来缩小图形:我称之为“end lvl”(节点名称长度等于7)并链接在一起的节点。

我发现在NetworkX凝聚作用,所以我尝试使用它:

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

当我转换成JSON我得到的东西是:

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

有一个问题,因为你可以看到...

对函数的引用是here

+0

一个解决方案是使用字典表示(to_dict_of_dicts)手动执行此操作。 – keyser 2013-03-26 15:30:54

+0

好吧,我不熟悉图形,但我应该改善我的问题,因为@ zodiac问我。它来了。 – user1254498 2013-03-26 15:40:06

+0

节点(),neighbours()和condensation()函数做了什么?什么是NX? – xuanji 2013-03-26 15:48:57

回答

3

如何:

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) 
+0

我用python和networkx函数重写了你的伪代码。我做了我想要的。谢谢。 – user1254498 2013-03-27 12:56:04

+0

请注意,上述内容将删除边缘和节点的任何属性信息。 – 2014-10-02 07:09:56