简体   繁体   中英

Graph Union in Python Igraph

I have 3 subgraphs and I want to obtain their union using the Python package Igraph (v. 0.9.1). I use Python v. 3.8.5.

Let's assume a simple example of 3 directed graphs of 5, 4 and 8 vertices respectively. Each vertex has an attribute called "name" (I give each one a unique String label).

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

If I have 3 graphs that do not share edges and do not share the value of the attribute "name", I expect the union to have 12 vertices (5 + 4 + 3) and 9 edges (3 + 4 + 2). This is the graph I want to obtain. However, I get an error "AttributeError: Some graphs are not named" .

The "union" method has 2 parameters: "graphs", "byname" (default value: 'auto'). Here is the reference: https://igraph.org/python/doc/api/igraph.operators.html

I found the answer, instead of the "union" method I should have used the "disjoint_union" method (whose parameter is the list of graphs to combine). This function keeps the attributes of all graphs.

All graph, vertex and edge attributes are copied to the result.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM