[英]How can I extract all possible induced subgraphs from a given graph with networkx
我想知道我是否可以使用networkx從輸入大圖中提取子圖中具有特定節點數的所有可能的誘導子圖(graphlet),或者是否有其他包可以完成這項工作? 例如,如果我有一個大圖,以networkx鄰接列表格式說明,
圖G:
1 2 3 7
2 1 4
3 1 4 6 5
4 2 3 5
5 3 4 6
6 3 5 7
7 1 6
這看起來像
如果我想用3個節點提取graphlet,算法應該返回給我
subgraph1:
1 2 3
2 1
3 1
[(1,2),(1,3)] subgraph2:
1 3 7
3 1
7 1
[(1,3),(1,7)] subgraph3:
3 4 5
4 3 5
5 3 4
[(3,4),(3,5),(4,5)]
subgraph4,subgraph5,subgraph6 ...
以下是@Hooked建議的問題代碼。 假設n = 3
import itertools
target = nx.complete_graph(3)
for sub_nodes in itertools.combinations(g.nodes(),len(target.nodes())):
subg = g.subgraph(sub_nodes)
if nx.is_connected(subg):
print subg.edges()
輸出看起來像
[(1, 2), (1, 3)]
[(1, 2), (2, 4)]
[(1, 2), (1, 7)]
[(1, 3), (3, 4)]
[(1, 3), (3, 5)]
[(1, 3), (3, 6)]
[(1, 3), (1, 7)]
[(1, 7), (6, 7)]
[(2, 4), (3, 4)]
[(2, 4), (4, 5)]
[(3, 4), (3, 5), (4, 5)]
[(3, 4), (3, 6)]
[(3, 5), (3, 6), (5, 6)]
[(3, 6), (6, 7)]
[(4, 5), (5, 6)]
[(5, 6), (6, 7)]
這假設您需要您必須定義的給定target
所有匹配子圖。 本機方式是遍歷節點的所有組合,找到那些連接的節點,然后檢查同構。 目前還不清楚你是否需要網絡主題或圖形。 在圖表中,原始圖表中存在的所有邊都必須存在 - 這將從目標中排除3-4-5。 這個方法找到graphlet,如果有一個誘導子圖(以及有多少!),找到你必須檢查每個組合的圖案。
import networkx as nx
g = nx.Graph()
g.add_edge(1,2);g.add_edge(1,3)
g.add_edge(1,7);g.add_edge(2,4)
g.add_edge(3,4);g.add_edge(3,5)
g.add_edge(3,6);g.add_edge(4,5)
g.add_edge(5,6);g.add_edge(6,7)
import itertools
target = nx.Graph()
target.add_edge(1,2)
target.add_edge(2,3)
for sub_nodes in itertools.combinations(g.nodes(),len(target.nodes())):
subg = g.subgraph(sub_nodes)
if nx.is_connected(subg) and nx.is_isomorphic(subg, target):
print subg.edges()
對我來說,這給出了邊緣集匹配:
[(1, 2), (1, 3)]
[(1, 2), (2, 4)]
[(1, 2), (1, 7)]
[(1, 3), (3, 4)]
[(1, 3), (3, 5)]
[(1, 3), (3, 6)]
[(1, 3), (1, 7)]
[(1, 7), (6, 7)]
[(2, 4), (3, 4)]
[(2, 4), (4, 5)]
[(3, 4), (3, 6)]
[(3, 6), (6, 7)]
[(4, 5), (5, 6)]
[(5, 6), (6, 7)]
您的示例在此處列出。
對於那些最終遇到相同問題但節點太多的人來說,@ Hooked的答案很少有簡單的改進(雖然我確信有更好的解決方案,因為@Hooked在評論中提到,這只是一個快速的副本 - 粘貼修復為最終在這里的人與我做的相同的原因,並有縮放問題)
1)igraph縮放方式比networkx更好
2)我們只能取一個節點的鄰域來消除大多數不必要的組合
例如,如果我們正在尋找更大network
的motif
(兩個igraph對象)
motif_rank = max(max(motif.shortest_paths_dijkstra()))
result = collections.OrderedDict.fromkeys(network.vs['label'], 0)
for node in self.network.vs:
# Get relevant nodes around node of interest that might create the motif of interest
nodes_to_expand = {node}
for rank in range(motif_rank):
nodes_expanded = nodes_to_expand
for node_to_expand in nodes_to_expand:
nodes_expanded = set.union(nodes_expanded, set(node_to_expand.neighbors()))
nodes_to_expand = nodes_expanded
# Look at all combinations
for sub_nodes in itertools.combinations(nodes_to_expand, motif.vcount()):
subg = network.subgraph(sub_nodes)
if subg.is_connected() and subg.isomorphic(motif):
result[node['label']] = result[node['label']]+1
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.