dgl.hetero_from_relations

dgl.hetero_from_relations(rel_graphs)[source]

Create a heterograph from graphs representing connections of each relation.

The input is a list of heterographs where the ``i``th graph contains edges of type \((s_i, e_i, d_i)\).

If two graphs share a same node type, the number of nodes for the corresponding type should be the same. See Examples for details.

Parameters:rel_graphs (list of DGLHeteroGraph) – Each element corresponds to a heterograph for one (src, edge, dst) relation.
Returns:A heterograph consisting of all relations.
Return type:DGLHeteroGraph

Examples

>>> import dgl
>>> follows_g = dgl.graph([(0, 1), (1, 2)], 'user', 'follows')
>>> plays_g = dgl.bipartite([(0, 0), (3, 1)], 'user', 'plays', 'game')
>>> devs_g = dgl.bipartite([(0, 0), (1, 1)], 'developer', 'develops', 'game')
>>> g = dgl.hetero_from_relations([follows_g, plays_g, devs_g])

will raise an error as we have 3 nodes of type ‘user’ in follows_g and 4 nodes of type ‘user’ in plays_g.

We have two possible methods to avoid the construction.

Method 1: Manually specify the number of nodes for all types when constructing the relation graphs.

>>> # A graph with 4 nodes of type 'user'
>>> follows_g = dgl.graph([(0, 1), (1, 2)], 'user', 'follows', card=4)
>>> # A bipartite graph with 4 nodes of src type ('user') and 2 nodes of dst type ('game')
>>> plays_g = dgl.bipartite([(0, 0), (3, 1)], 'user', 'plays', 'game', card=(4, 2))
>>> devs_g = dgl.bipartite([(0, 0), (1, 1)], 'developer', 'develops', 'game')
>>> g = dgl.hetero_from_relations([follows_g, plays_g, devs_g])
>>> print(g)
Graph(num_nodes={'user': 4, 'game': 2, 'developer': 2},
      num_edges={('user', 'follows', 'user'): 2, ('user', 'plays', 'game'): 2,
                 ('developer', 'develops', 'game'): 2},
      metagraph=[('user', 'user'), ('user', 'game'), ('developer', 'game')])

devs_g does not have nodes of type 'user' so no error will be raised.

Method 2: Construct a heterograph at once without intermediate relation graphs, in which case we will infer the number of nodes for each type.

>>> g = dgl.heterograph({
>>>     ('user', 'follows', 'user'): [(0, 1), (1, 2)],
>>>     ('user', 'plays', 'game'): [(0, 0), (3, 1)],
>>>     ('developer', 'develops', 'game'): [(0, 0), (1, 1)]
>>> })
>>> print(g)
Graph(num_nodes={'user': 4, 'game': 2, 'developer': 2},
      num_edges={('user', 'follows', 'user'): 2,
                 ('user', 'plays', 'game'): 2,
                 ('developer', 'develops', 'game'): 2},
      metagraph=[('user', 'user'), ('user', 'game'), ('developer', 'game')])