2015-09-22 71 views
2

我在圖中有一個圖g和節點列表subset_nodes。我想刪除節點v_i,v_j之間的所有邊緣,其中v_iv_j均在subset_nodes之間。刪除節點子集之間的所有邊緣

我目前使用以下方法:

import igraph 

g = igraph.Graph.Full(10) 
subset_nodes = [g.vs[i] for i in range(4)] 

to_delete = set() 
for node in subset_nodes: 
    for v in node.neighbors(): 
     if v in subset_nodes: 
      tp = (node.index, v.index) 
      to_delete.add(tuple(sorted(tp))) 

print(len(g.es)) 
g.delete_edges(to_delete) 
print(len(g.es)) 

此打印:

45 
39 

這是有道理的,因爲

10 choose 2 = 45 # total # of edges (since it is a full graph) 
4 choose 2 = 6  # # of removed edges 
45 - 6 = 39  # # of edges remaining 

我的問題是,有沒有更好的,更優雅或更pythonic方式做同樣的?

回答

1

另一種解決辦法是:

from igraph import Graph 
g = Graph.Full(10) 
g.es.select(_within=range(4)).delete() 
1

IGRAPH具有 「induced_subgraph」 方法,其可以方便來爲更簡潔的解決方案:

import igraph as ig 
g=ig.Graph.Full(10) 
subset_nodes=[g.vs[i] for i in range(4)] 
smallgraph=g.induced_subgraph(subset_nodes) 
es=ig.EdgeSeq(smallgraph) 
mytup=[e.tuple for e in es] 
g.delete_edges(mytup)