dgl.DGLHeteroGraph.edge_subgraph

DGLHeteroGraph.edge_subgraph(edges, preserve_nodes=False)[source]

Return the subgraph induced on given edges.

The metagraph of the returned subgraph is the same as the parent graph.

Features are copied from the original graph.

Parameters:
  • edges (dict[str->list or iterable]) –

    A dictionary mapping edge types to edge ID array for constructing subgraph. All edges must exist in the subgraph.

    The edge types are characterized by triplets of (src type, etype, dst type).

  • preserve_nodes (bool) – Whether to preserve all nodes or not. If false, all nodes without edges will be removed. (Default: False)
Returns:

G – The subgraph.

The nodes and edges are relabeled using consecutive integers from 0.

One can retrieve the mapping from subgraph node/edge ID to parent node/edge ID via dgl.NID and dgl.EID node/edge features of the subgraph.

Return type:

DGLHeteroGraph

Examples

The following example uses PyTorch backend.

Instantiate a heterograph.

>>> plays_g = dgl.bipartite([(0, 0), (1, 0), (1, 2), (2, 1)], 'user', 'plays', 'game')
>>> follows_g = dgl.graph([(0, 1), (1, 2), (1, 2)], 'user', 'follows')
>>> g = dgl.hetero_from_relations([plays_g, follows_g])
>>> # Set edge features
>>> g.edges['follows'].data['h'] = torch.tensor([[0.], [1.], [2.]])

Get subgraphs.

>>> g.edge_subgraph({('user', 'follows', 'user'): [5, 6]})
An error occurs as these edges do not exist.
>>> sub_g = g.edge_subgraph({('user', 'follows', 'user'): [1, 2],
>>>                          ('user', 'plays', 'game'): [2]})
>>> print(sub_g)
Graph(num_nodes={'user': 2, 'game': 1},
      num_edges={('user', 'plays', 'game'): 1, ('user', 'follows', 'user'): 2},
      metagraph=[('user', 'game'), ('user', 'user')])

Get the original node/edge indices.

>>> sub_g['follows'].ndata[dgl.NID] # Get the node indices in the raw graph
tensor([1, 2])
>>> sub_g['plays'].edata[dgl.EID]   # Get the edge indices in the raw graph
tensor([2])

Get the copied node features.

>>> sub_g.edges['follows'].data['h']
tensor([[1.],
        [2.]])
>>> sub_g.edges['follows'].data['h'] += 1
>>> g.edges['follows'].data['h']          # Features are not shared.
tensor([[0.],
        [1.],
        [2.]])

See also

subgraph()