首页 > 解决方案 > Python Igraph 中的图联合

问题描述

我有 3 个子图,我想使用 Python 包 Igraph (v. 0.9.1) 获得它们的并集。我使用 Python v. 3.8.5。

让我们假设一个简单的例子,分别有 5 个、4 个和 8 个顶点的 3 个有向图。每个顶点都有一个名为“名称”的属性(我给每个顶点一个唯一的字符串标签)。

# Note: igraph version: 0.9.1
from igraph import *

# Subgraphs

# g1: 5 vertices and 3 edges
g1 = Graph(directed=True)
g1.add_vertices(5)
g1.vs["name"] = ["1_g1", "2_g1", "3_g1", "4_g1", "5_g1"]
g1.add_edges([(0, 1), (2, 3), (4, 2)])

# g2: 4 vertices and 4 edges
g2 = Graph(directed=True)
g2.add_vertices(4)
g2.vs["name"] = ["1_g2", "2_g2", "3_g2", "4_g2"]
g2.add_edges([(1, 2), (3, 1), (2, 3), (0, 1)])

# g3: 3 vertices and 2 edges
g3 = Graph(directed=True)
g3.add_vertices(3)
g3.vs["name"] = ["1_g3", "2_g3", "3_g3"]
g3.add_edges([(0, 2), (1, 0)])

# Union of the 3 subgraphs
g_union = Graph(directed=True)

# Doesn't give me the result I expect...
g_union = g_union.union([g1, g2, g3], byname=True)

如果我有 3 个不共享边且不共享属性“名称”的值的图,我希望联合有 12 个顶点 (5 + 4 + 3) 和 9 个边 (3 + 4 + 2)。这是我想要获得的图表。但是,我收到一个错误"AttributeError: Some graphs are not named"

“union”方法有 2 个参数:“graphs”、“byname”(默认值:'auto')。这是参考:https ://igraph.org/python/doc/api/igraph.operators.html

标签: pythongraphunionigraph

解决方案


我找到了答案,而不是“union”方法,我应该使用“disjoint_union”方法(其参数是要组合的图形列表)。该函数保留所有图形的属性。

所有图形、顶点和边属性都被复制到结果中。


推荐阅读