heterograph.py 240 KB
Newer Older
Da Zheng's avatar
Da Zheng committed
1
"""Classes for heterogeneous graphs."""
2
#pylint: disable= too-many-lines
3
4
from collections import defaultdict
from collections.abc import Mapping, Iterable
Minjie Wang's avatar
Minjie Wang committed
5
from contextlib import contextmanager
6
import copy
7
import numbers
8
import itertools
9
import networkx as nx
Minjie Wang's avatar
Minjie Wang committed
10
11
import numpy as np

12
from ._ffi.function import _init_api
13
from .ops import segment
14
15
from .base import ALL, SLICE_FULL, NTYPE, NID, ETYPE, EID, is_all, DGLError, dgl_warning
from . import core
Minjie Wang's avatar
Minjie Wang committed
16
17
from . import graph_index
from . import heterograph_index
18
19
from . import utils
from . import backend as F
20
from .frame import Frame
21
from .view import HeteroNodeView, HeteroNodeDataView, HeteroEdgeView, HeteroEdgeDataView
Minjie Wang's avatar
Minjie Wang committed
22

peizhou001's avatar
peizhou001 committed
23
__all__ = ['DGLGraph', 'combine_names']
Minjie Wang's avatar
Minjie Wang committed
24

peizhou001's avatar
peizhou001 committed
25
class DGLGraph(object):
26
27
    """Class for storing graph structure and node/edge feature data.

28
    There are a few ways to create a DGLGraph:
29
30
31
32
33
34
35
36

    * To create a homogeneous graph from Tensor data, use :func:`dgl.graph`.
    * To create a heterogeneous graph from Tensor data, use :func:`dgl.heterograph`.
    * To create a graph from other data sources, use ``dgl.*`` create ops. See
      :ref:`api-graph-create-ops`.

    Read the user guide chapter :ref:`guide-graph` for an in-depth explanation about its
    usage.
Minjie Wang's avatar
Minjie Wang committed
37
    """
38
39
    is_block = False

40
    # pylint: disable=unused-argument, dangerous-default-value
Minjie Wang's avatar
Minjie Wang committed
41
    def __init__(self,
42
                 gidx=[],
43
44
                 ntypes=['_N'],
                 etypes=['_E'],
Minjie Wang's avatar
Minjie Wang committed
45
                 node_frames=None,
46
47
                 edge_frames=None,
                 **deprecate_kwargs):
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
        """Internal constructor for creating a DGLGraph.

        Parameters
        ----------
        gidx : HeteroGraphIndex
            Graph index object.
        ntypes : list of str, pair of list of str
            Node type list. ``ntypes[i]`` stores the name of node type i.
            If a pair is given, the graph created is a uni-directional bipartite graph,
            and its SRC node types and DST node types are given as in the pair.
        etypes : list of str
            Edge type list. ``etypes[i]`` stores the name of edge type i.
        node_frames : list[Frame], optional
            Node feature storage. If None, empty frame is created.
            Otherwise, ``node_frames[i]`` stores the node features
            of node type i. (default: None)
        edge_frames : list[Frame], optional
            Edge feature storage. If None, empty frame is created.
            Otherwise, ``edge_frames[i]`` stores the edge features
            of edge type i. (default: None)
        """
peizhou001's avatar
peizhou001 committed
69
        if isinstance(gidx, DGLGraph):
70
71
72
73
            raise DGLError('The input is already a DGLGraph. No need to create it again.')
        if not isinstance(gidx, heterograph_index.HeteroGraphIndex):
            dgl_warning('Recommend creating graphs by `dgl.graph(data)`'
                        ' instead of `dgl.DGLGraph(data)`.')
74
75
76
77
78
79
80
81
            (sparse_fmt, arrays), num_src, num_dst = utils.graphdata2tensors(gidx)
            if sparse_fmt == 'coo':
                gidx = heterograph_index.create_unitgraph_from_coo(
                    1, num_src, num_dst, arrays[0], arrays[1], ['coo', 'csr', 'csc'])
            else:
                gidx = heterograph_index.create_unitgraph_from_csr(
                    1, num_src, num_dst, arrays[0], arrays[1], arrays[2], ['coo', 'csr', 'csc'],
                    sparse_fmt == 'csc')
82
83
84
        if len(deprecate_kwargs) != 0:
            dgl_warning('Keyword arguments {} are deprecated in v0.5, and can be safely'
                        ' removed in all cases.'.format(list(deprecate_kwargs.keys())))
85
        self._init(gidx, ntypes, etypes, node_frames, edge_frames)
Da Zheng's avatar
Da Zheng committed
86

87
88
    def _init(self, gidx, ntypes, etypes, node_frames, edge_frames):
        """Init internal states."""
Minjie Wang's avatar
Minjie Wang committed
89
        self._graph = gidx
90
        self._canonical_etypes = None
91
92
        self._batch_num_nodes = None
        self._batch_num_edges = None
93
94
95
96
97
98
99

        # Handle node types
        if isinstance(ntypes, tuple):
            if len(ntypes) != 2:
                errmsg = 'Invalid input. Expect a pair (srctypes, dsttypes) but got {}'.format(
                    ntypes)
                raise TypeError(errmsg)
100
            if not self._graph.is_metagraph_unibipartite():
101
102
103
104
105
106
                raise ValueError('Invalid input. The metagraph must be a uni-directional'
                                 ' bipartite graph.')
            self._ntypes = ntypes[0] + ntypes[1]
            self._srctypes_invmap = {t : i for i, t in enumerate(ntypes[0])}
            self._dsttypes_invmap = {t : i + len(ntypes[0]) for i, t in enumerate(ntypes[1])}
            self._is_unibipartite = True
107
108
            if len(ntypes[0]) == 1 and len(ntypes[1]) == 1 and len(etypes) == 1:
                self._canonical_etypes = [(ntypes[0][0], etypes[0], ntypes[1][0])]
109
110
        else:
            self._ntypes = ntypes
111
112
113
114
            if len(ntypes) == 1:
                src_dst_map = None
            else:
                src_dst_map = find_src_dst_ntypes(self._ntypes, self._graph.metagraph)
115
116
117
118
119
120
121
122
            self._is_unibipartite = (src_dst_map is not None)
            if self._is_unibipartite:
                self._srctypes_invmap, self._dsttypes_invmap = src_dst_map
            else:
                self._srctypes_invmap = {t : i for i, t in enumerate(self._ntypes)}
                self._dsttypes_invmap = self._srctypes_invmap

        # Handle edge types
123
        self._etypes = etypes
124
        if self._canonical_etypes is None:
125
126
127
128
129
            if (len(etypes) == 1 and len(ntypes) == 1):
                self._canonical_etypes = [(ntypes[0], etypes[0], ntypes[0])]
            else:
                self._canonical_etypes = make_canonical_etypes(
                    self._etypes, self._ntypes, self._graph.metagraph)
130

Minjie Wang's avatar
Minjie Wang committed
131
        # An internal map from etype to canonical etype tuple.
132
133
        # If two etypes have the same name, an empty tuple is stored instead to indicate
        # ambiguity.
Minjie Wang's avatar
Minjie Wang committed
134
        self._etype2canonical = {}
135
        for i, ety in enumerate(self._etypes):
Minjie Wang's avatar
Minjie Wang committed
136
137
138
139
140
            if ety in self._etype2canonical:
                self._etype2canonical[ety] = tuple()
            else:
                self._etype2canonical[ety] = self._canonical_etypes[i]
        self._etypes_invmap = {t : i for i, t in enumerate(self._canonical_etypes)}
Da Zheng's avatar
Da Zheng committed
141

Minjie Wang's avatar
Minjie Wang committed
142
143
144
        # node and edge frame
        if node_frames is None:
            node_frames = [None] * len(self._ntypes)
145
        node_frames = [Frame(num_rows=self._graph.number_of_nodes(i))
Minjie Wang's avatar
Minjie Wang committed
146
147
148
                       if frame is None else frame
                       for i, frame in enumerate(node_frames)]
        self._node_frames = node_frames
Da Zheng's avatar
Da Zheng committed
149

Minjie Wang's avatar
Minjie Wang committed
150
151
        if edge_frames is None:
            edge_frames = [None] * len(self._etypes)
152
        edge_frames = [Frame(num_rows=self._graph.number_of_edges(i))
Minjie Wang's avatar
Minjie Wang committed
153
154
155
                       if frame is None else frame
                       for i, frame in enumerate(edge_frames)]
        self._edge_frames = edge_frames
Da Zheng's avatar
Da Zheng committed
156

157
    def __setstate__(self, state):
158
159
        # Compatibility check
        # TODO: version the storage
160
161
162
        if isinstance(state, dict):
            # Since 0.5 we use the default __dict__ method
            self.__dict__.update(state)
163
164
165
166
        elif isinstance(state, tuple) and len(state) == 5:
            # DGL == 0.4.3
            dgl_warning("The object is pickled with DGL == 0.4.3.  "
                        "Some of the original attributes are ignored.")
167
168
            self._init(*state)
        elif isinstance(state, dict):
169
170
            # DGL <= 0.4.2
            dgl_warning("The object is pickled with DGL <= 0.4.2.  "
171
172
173
174
175
                        "Some of the original attributes are ignored.")
            self._init(state['_graph'], state['_ntypes'], state['_etypes'], state['_node_frames'],
                       state['_edge_frames'])
        else:
            raise IOError("Unrecognized pickle format.")
Mufei Li's avatar
Mufei Li committed
176

Minjie Wang's avatar
Minjie Wang committed
177
178
179
180
181
182
183
184
185
186
187
188
189
190
    def __repr__(self):
        if len(self.ntypes) == 1 and len(self.etypes) == 1:
            ret = ('Graph(num_nodes={node}, num_edges={edge},\n'
                   '      ndata_schemes={ndata}\n'
                   '      edata_schemes={edata})')
            return ret.format(node=self.number_of_nodes(), edge=self.number_of_edges(),
                              ndata=str(self.node_attr_schemes()),
                              edata=str(self.edge_attr_schemes()))
        else:
            ret = ('Graph(num_nodes={node},\n'
                   '      num_edges={edge},\n'
                   '      metagraph={meta})')
            nnode_dict = {self.ntypes[i] : self._graph.number_of_nodes(i)
                          for i in range(len(self.ntypes))}
191
            nedge_dict = {self.canonical_etypes[i] : self._graph.number_of_edges(i)
Minjie Wang's avatar
Minjie Wang committed
192
                          for i in range(len(self.etypes))}
193
            meta = str(self.metagraph().edges(keys=True))
Minjie Wang's avatar
Minjie Wang committed
194
195
            return ret.format(node=nnode_dict, edge=nedge_dict, meta=meta)

196
197
198
199
200
    def __copy__(self):
        """Shallow copy implementation."""
        #TODO(minjie): too many states in python; should clean up and lower to C
        cls = type(self)
        obj = cls.__new__(cls)
201
        obj.__dict__.update(self.__dict__)
202
203
        return obj

Minjie Wang's avatar
Minjie Wang committed
204
205
206
207
208
    #################################################################
    # Mutation operations
    #################################################################

    def add_nodes(self, num, data=None, ntype=None):
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
        r"""Add new nodes of the same node type

        Parameters
        ----------
        num : int
            Number of nodes to add.
        data : dict, optional
            Feature data of the added nodes.
        ntype : str, optional
            The type of the new nodes. Can be omitted if there is
            only one node type in the graph.

        Notes
        -----

        * Inplace update is applied to the current graph.
        * If the key of ``data`` does not contain some existing feature fields,
226
227
          those features for the new nodes will be created by initializers
          defined with :func:`set_n_initializer` (default initializer fills zeros).
228
        * If the key of ``data`` contains new feature fields, those features for
229
230
231
232
233
234
          the old nodes will be created by initializers defined with
          :func:`set_n_initializer` (default initializer fills zeros).
        * This function discards the batch information. Please use
          :func:`dgl.DGLGraph.set_batch_num_nodes`
          and :func:`dgl.DGLGraph.set_batch_num_edges` on the transformed graph
          to maintain the information.
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277

        Examples
        --------

        The following example uses PyTorch backend.

        >>> import dgl
        >>> import torch

        **Homogeneous Graphs or Heterogeneous Graphs with A Single Node Type**

        >>> g = dgl.graph((torch.tensor([0, 1]), torch.tensor([1, 2])))
        >>> g.num_nodes()
        3
        >>> g.add_nodes(2)
        >>> g.num_nodes()
        5

        If the graph has some node features and new nodes are added without
        features, their features will be created by initializers defined
        with :func:`set_n_initializer`.

        >>> g.ndata['h'] = torch.ones(5, 1)
        >>> g.add_nodes(1)
        >>> g.ndata['h']
        tensor([[1.], [1.], [1.], [1.], [1.], [0.]])

        We can also assign features for the new nodes in adding new nodes.

        >>> g.add_nodes(1, {'h': torch.ones(1, 1), 'w': torch.ones(1, 1)})
        >>> g.ndata['h']
        tensor([[1.], [1.], [1.], [1.], [1.], [0.], [1.]])

        Since ``data`` contains new feature fields, the features for old nodes
        will be created by initializers defined with :func:`set_n_initializer`.

        >>> g.ndata['w']
        tensor([[0.], [0.], [0.], [0.], [0.], [0.], [1.]])


        **Heterogeneous Graphs with Multiple Node Types**

        >>> g = dgl.heterograph({
278
279
280
281
282
        ...     ('user', 'plays', 'game'): (torch.tensor([0, 1, 1, 2]),
        ...                                 torch.tensor([0, 0, 1, 1])),
        ...     ('developer', 'develops', 'game'): (torch.tensor([0, 1]),
        ...                                         torch.tensor([0, 1]))
        ...     })
283
284
285
286
287
288
289
290
        >>> g.add_nodes(2)
        DGLError: Node type name must be specified
        if there are more than one node types.
        >>> g.num_nodes('user')
        3
        >>> g.add_nodes(2, ntype='user')
        >>> g.num_nodes('user')
        5
Minjie Wang's avatar
Minjie Wang committed
291

292
293
294
295
296
        See Also
        --------
        remove_nodes
        add_edges
        remove_edges
Minjie Wang's avatar
Minjie Wang committed
297
        """
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
        # TODO(xiangsx): block do not support add_nodes
        if ntype is None:
            if self._graph.number_of_ntypes() != 1:
                raise DGLError('Node type name must be specified if there are more than one '
                               'node types.')

        # nothing happen
        if num == 0:
            return

        assert num > 0, 'Number of new nodes should be larger than one.'
        ntid = self.get_ntype_id(ntype)
        # update graph idx
        metagraph = self._graph.metagraph
        num_nodes_per_type = []
        for c_ntype in self.ntypes:
            if self.get_ntype_id(c_ntype) == ntid:
                num_nodes_per_type.append(self.number_of_nodes(c_ntype) + num)
            else:
                num_nodes_per_type.append(self.number_of_nodes(c_ntype))

        relation_graphs = []
        for c_etype in self.canonical_etypes:
            # src or dst == ntype, update the relation graph
            if self.get_ntype_id(c_etype[0]) == ntid or self.get_ntype_id(c_etype[2]) == ntid:
                u, v = self.edges(form='uv', order='eid', etype=c_etype)
                hgidx = heterograph_index.create_unitgraph_from_coo(
                    1 if c_etype[0] == c_etype[2] else 2,
                    self.number_of_nodes(c_etype[0]) + \
                        (num if self.get_ntype_id(c_etype[0]) == ntid else 0),
                    self.number_of_nodes(c_etype[2]) + \
                        (num if self.get_ntype_id(c_etype[2]) == ntid else 0),
                    u,
                    v,
                    ['coo', 'csr', 'csc'])
                relation_graphs.append(hgidx)
            else:
                # do nothing
                relation_graphs.append(self._graph.get_relation_graph(self.get_etype_id(c_etype)))
        hgidx = heterograph_index.create_heterograph_from_relations(
            metagraph, relation_graphs, utils.toindex(num_nodes_per_type, "int64"))
        self._graph = hgidx

        # update data frames
        if data is None:
            # Initialize feature with :func:`set_n_initializer`
            self._node_frames[ntid].add_rows(num)
        else:
            self._node_frames[ntid].append(data)
        self._reset_cached_info()
Minjie Wang's avatar
Minjie Wang committed
348
349

    def add_edge(self, u, v, data=None, etype=None):
350
        """Add one edge to the graph.
Minjie Wang's avatar
Minjie Wang committed
351

352
        DEPRECATED: please use ``add_edges``.
Minjie Wang's avatar
Minjie Wang committed
353
        """
354
355
        dgl_warning("DGLGraph.add_edge is deprecated. Please use DGLGraph.add_edges")
        self.add_edges(u, v, data, etype)
Minjie Wang's avatar
Minjie Wang committed
356
357

    def add_edges(self, u, v, data=None, etype=None):
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
        r"""Add multiple new edges for the specified edge type

        The i-th new edge will be from ``u[i]`` to ``v[i]``.

        Parameters
        ----------
        u : int, tensor, numpy.ndarray, list
            Source node IDs, ``u[i]`` gives the source node for the i-th new edge.
        v : int, tensor, numpy.ndarray, list
            Destination node IDs, ``v[i]`` gives the destination node for the i-th new edge.
        data : dict, optional
            Feature data of the added edges. The i-th row of the feature data
            corresponds to the i-th new edge.
        etype : str or tuple of str, optional
            The type of the new edges. Can be omitted if there is
            only one edge type in the graph.

        Notes
        -----

        * Inplace update is applied to the current graph.
        * If end nodes of adding edges does not exists, add_nodes is invoked
380
381
382
383
          to add new nodes. The node features of the new nodes will be created
          by initializers defined with :func:`set_n_initializer` (default
          initializer fills zeros). In certain cases, it is recommanded to
          add_nodes first and then add_edges.
384
        * If the key of ``data`` does not contain some existing feature fields,
385
386
          those features for the new edges will be created by initializers
          defined with :func:`set_n_initializer` (default initializer fills zeros).
387
        * If the key of ``data`` contains new feature fields, those features for
388
389
390
391
392
393
          the old edges will be created by initializers defined with
          :func:`set_n_initializer` (default initializer fills zeros).
        * This function discards the batch information. Please use
          :func:`dgl.DGLGraph.set_batch_num_nodes`
          and :func:`dgl.DGLGraph.set_batch_num_edges` on the transformed graph
          to maintain the information.
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428

        Examples
        --------

        The following example uses PyTorch backend.

        >>> import dgl
        >>> import torch

        **Homogeneous Graphs or Heterogeneous Graphs with A Single Edge Type**

        >>> g = dgl.graph((torch.tensor([0, 1]), torch.tensor([1, 2])))
        >>> g.num_edges()
        2
        >>> g.add_edges(torch.tensor([1, 3]), torch.tensor([0, 1]))
        >>> g.num_edges()
        4

        Since ``u`` or ``v`` contains a non-existing node ID, the nodes are
        added implicitly.
        >>> g.num_nodes()
        4

        If the graph has some edge features and new edges are added without
        features, their features will be created by initializers defined
        with :func:`set_n_initializer`.

        >>> g.edata['h'] = torch.ones(4, 1)
        >>> g.add_edges(torch.tensor([1]), torch.tensor([1]))
        >>> g.edata['h']
        tensor([[1.], [1.], [1.], [1.], [0.]])

        We can also assign features for the new edges in adding new edges.

        >>> g.add_edges(torch.tensor([0, 0]), torch.tensor([2, 2]),
429
        ...             {'h': torch.tensor([[1.], [2.]]), 'w': torch.ones(2, 1)})
430
431
432
433
434
435
436
437
438
439
440
441
        >>> g.edata['h']
        tensor([[1.], [1.], [1.], [1.], [0.], [1.], [2.]])

        Since ``data`` contains new feature fields, the features for old edges
        will be created by initializers defined with :func:`set_n_initializer`.

        >>> g.edata['w']
        tensor([[0.], [0.], [0.], [0.], [0.], [1.], [1.]])

        **Heterogeneous Graphs with Multiple Edge Types**

        >>> g = dgl.heterograph({
442
443
444
445
446
        ...     ('user', 'plays', 'game'): (torch.tensor([0, 1, 1, 2]),
        ...                                 torch.tensor([0, 0, 1, 1])),
        ...     ('developer', 'develops', 'game'): (torch.tensor([0, 1]),
        ...                                         torch.tensor([0, 1]))
        ...     })
447
448
449
450
451
        >>> g.add_edges(torch.tensor([3]), torch.tensor([3]))
        DGLError: Edge type name must be specified
        if there are more than one edge types.
        >>> g.number_of_edges('plays')
        4
452
        >>> g.add_edges(torch.tensor([3]), torch.tensor([3]), etype='plays')
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
        >>> g.number_of_edges('plays')
        5

        See Also
        --------
        add_nodes
        remove_nodes
        remove_edges
        """
        # TODO(xiangsx): block do not support add_edges
        u = utils.prepare_tensor(self, u, 'u')
        v = utils.prepare_tensor(self, v, 'v')

        if etype is None:
            if self._graph.number_of_etypes() != 1:
                raise DGLError('Edge type name must be specified if there are more than one '
                               'edge types.')

        # nothing changed
        if len(u) == 0 or len(v) == 0:
            return

        assert len(u) == len(v) or len(u) == 1 or len(v) == 1, \
            'The number of source nodes and the number of destination nodes should be same, ' \
            'or either the number of source nodes or the number of destination nodes is 1.'

        if len(u) == 1 and len(v) > 1:
            u = F.full_1d(len(v), F.as_scalar(u), dtype=F.dtype(u), ctx=F.context(u))
        if len(v) == 1 and len(u) > 1:
            v = F.full_1d(len(u), F.as_scalar(v), dtype=F.dtype(v), ctx=F.context(v))

        u_type, e_type, v_type = self.to_canonical_etype(etype)
        # if end nodes of adding edges does not exists
        # use add_nodes to add new nodes first.
        num_of_u = self.number_of_nodes(u_type)
        num_of_v = self.number_of_nodes(v_type)
        u_max = F.as_scalar(F.max(u, dim=0)) + 1
        v_max = F.as_scalar(F.max(v, dim=0)) + 1

        if u_type == v_type:
            num_nodes = max(u_max, v_max)
            if num_nodes > num_of_u:
                self.add_nodes(num_nodes - num_of_u, ntype=u_type)
        else:
            if u_max > num_of_u:
                self.add_nodes(u_max - num_of_u, ntype=u_type)
            if v_max > num_of_v:
                self.add_nodes(v_max - num_of_v, ntype=v_type)

        # metagraph is not changed
        metagraph = self._graph.metagraph
        num_nodes_per_type = []
        for ntype in self.ntypes:
            num_nodes_per_type.append(self.number_of_nodes(ntype))
        # update graph idx
        relation_graphs = []
        for c_etype in self.canonical_etypes:
            # the target edge type
            if c_etype == (u_type, e_type, v_type):
                old_u, old_v = self.edges(form='uv', order='eid', etype=c_etype)
                hgidx = heterograph_index.create_unitgraph_from_coo(
                    1 if u_type == v_type else 2,
                    self.number_of_nodes(u_type),
                    self.number_of_nodes(v_type),
                    F.cat([old_u, u], dim=0),
                    F.cat([old_v, v], dim=0),
                    ['coo', 'csr', 'csc'])
                relation_graphs.append(hgidx)
            else:
                # do nothing
                # Note: node range change has been handled in add_nodes()
                relation_graphs.append(self._graph.get_relation_graph(self.get_etype_id(c_etype)))

        hgidx = heterograph_index.create_heterograph_from_relations(
            metagraph, relation_graphs, utils.toindex(num_nodes_per_type, "int64"))
        self._graph = hgidx

        # handle data
        etid = self.get_etype_id(etype)
        if data is None:
            self._edge_frames[etid].add_rows(len(u))
        else:
            self._edge_frames[etid].append(data)
        self._reset_cached_info()

538
    def remove_edges(self, eids, etype=None, store_ids=False):
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
        r"""Remove multiple edges with the specified edge type

        Nodes will not be removed. After removing edges, the rest
        edges will be re-indexed using consecutive integers from 0,
        with their relative order preserved.

        The features for the removed edges will be removed accordingly.

        Parameters
        ----------
        eids : int, tensor, numpy.ndarray, list
            IDs for the edges to remove.
        etype : str or tuple of str, optional
            The type of the edges to remove. Can be omitted if there is
            only one edge type in the graph.
554
555
556
557
        store_ids : bool, optional
            If True, it will store the raw IDs of the extracted nodes and edges in the ``ndata``
            and ``edata`` of the resulting graph under name ``dgl.NID`` and ``dgl.EID``,
            respectively.
558

559
560
        Notes
        -----
561
        This function preserves the batch information.
562

563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
        Examples
        --------

        >>> import dgl
        >>> import torch

        **Homogeneous Graphs or Heterogeneous Graphs with A Single Edge Type**

        >>> g = dgl.graph((torch.tensor([0, 0, 2]), torch.tensor([0, 1, 2])))
        >>> g.edata['he'] = torch.arange(3).float().reshape(-1, 1)
        >>> g.remove_edges(torch.tensor([0, 1]))
        >>> g
        Graph(num_nodes=3, num_edges=1,
            ndata_schemes={}
            edata_schemes={'he': Scheme(shape=(1,), dtype=torch.float32)})
        >>> g.edges('all')
        (tensor([2]), tensor([2]), tensor([0]))
        >>> g.edata['he']
        tensor([[2.]])

583
584
585
586
587
588
589
590
591
592
593
        Removing edges from a batched graph preserves batch information.

        >>> g = dgl.graph((torch.tensor([0, 0, 2]), torch.tensor([0, 1, 2])))
        >>> g2 = dgl.graph((torch.tensor([1, 2, 3]), torch.tensor([1, 3, 4])))
        >>> bg = dgl.batch([g, g2])
        >>> bg.batch_num_edges()
        tensor([3, 3])
        >>> bg.remove_edges([1, 4])
        >>> bg.batch_num_edges()
        tensor([2, 2])

594
595
596
        **Heterogeneous Graphs with Multiple Edge Types**

        >>> g = dgl.heterograph({
597
598
599
600
601
        ...     ('user', 'plays', 'game'): (torch.tensor([0, 1, 1, 2]),
        ...                                 torch.tensor([0, 0, 1, 1])),
        ...     ('developer', 'develops', 'game'): (torch.tensor([0, 1]),
        ...                                         torch.tensor([0, 1]))
        ...     })
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
        >>> g.remove_edges(torch.tensor([0, 1]))
        DGLError: Edge type name must be specified
        if there are more than one edge types.
        >>> g.remove_edges(torch.tensor([0, 1]), 'plays')
        >>> g.edges('all', etype='plays')
        (tensor([0, 1]), tensor([0, 0]), tensor([0, 1]))

        See Also
        --------
        add_nodes
        add_edges
        remove_nodes
        """
        # TODO(xiangsx): block do not support remove_edges
        if etype is None:
            if self._graph.number_of_etypes() != 1:
                raise DGLError('Edge type name must be specified if there are more than one ' \
                               'edge types.')
        eids = utils.prepare_tensor(self, eids, 'u')
        if len(eids) == 0:
            # no edge to delete
            return
        assert self.number_of_edges(etype) > F.as_scalar(F.max(eids, dim=0)), \
            'The input eid {} is out of the range [0:{})'.format(
                F.as_scalar(F.max(eids, dim=0)), self.number_of_edges(etype))

        # edge_subgraph
        edges = {}
        u_type, e_type, v_type = self.to_canonical_etype(etype)
        for c_etype in self.canonical_etypes:
            # the target edge type
            if c_etype == (u_type, e_type, v_type):
                origin_eids = self.edges(form='eid', order='eid', etype=c_etype)
                edges[c_etype] = utils.compensate(eids, origin_eids)
            else:
                edges[c_etype] = self.edges(form='eid', order='eid', etype=c_etype)

639
640
641
642
643
644
645
646
647
648
649
650
651
        # If the graph is batched, update batch_num_edges
        batched = self._batch_num_edges is not None
        if batched:
            c_etype = (u_type, e_type, v_type)
            one_hot_removed_edges = F.zeros((self.num_edges(c_etype),), F.float32, self.device)
            one_hot_removed_edges = F.scatter_row(one_hot_removed_edges, eids,
                                                  F.full_1d(len(eids), 1., F.float32, self.device))
            c_etype_batch_num_edges = self._batch_num_edges[c_etype]
            batch_num_removed_edges = segment.segment_reduce(c_etype_batch_num_edges,
                                                             one_hot_removed_edges, reducer='sum')
            self._batch_num_edges[c_etype] = c_etype_batch_num_edges - \
                                             F.astype(batch_num_removed_edges, F.int64)

652
        sub_g = self.edge_subgraph(edges, relabel_nodes=False, store_ids=store_ids)
653
654
655
656
        self._graph = sub_g._graph
        self._node_frames = sub_g._node_frames
        self._edge_frames = sub_g._edge_frames

657
    def remove_nodes(self, nids, ntype=None, store_ids=False):
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
        r"""Remove multiple nodes with the specified node type

        Edges that connect to the nodes will be removed as well. After removing
        nodes and edges, the rest nodes and edges will be re-indexed using
        consecutive integers from 0, with their relative order preserved.

        The features for the removed nodes/edges will be removed accordingly.

        Parameters
        ----------
        nids : int, tensor, numpy.ndarray, list
            Nodes to remove.
        ntype : str, optional
            The type of the nodes to remove. Can be omitted if there is
            only one node type in the graph.
673
674
675
676
        store_ids : bool, optional
            If True, it will store the raw IDs of the extracted nodes and edges in the ``ndata``
            and ``edata`` of the resulting graph under name ``dgl.NID`` and ``dgl.EID``,
            respectively.
677

678
679
        Notes
        -----
680
        This function preserves the batch information.
681

682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
        Examples
        --------

        >>> import dgl
        >>> import torch

        **Homogeneous Graphs or Heterogeneous Graphs with A Single Node Type**

        >>> g = dgl.graph((torch.tensor([0, 0, 2]), torch.tensor([0, 1, 2])))
        >>> g.ndata['hv'] = torch.arange(3).float().reshape(-1, 1)
        >>> g.edata['he'] = torch.arange(3).float().reshape(-1, 1)
        >>> g.remove_nodes(torch.tensor([0, 1]))
        >>> g
        Graph(num_nodes=1, num_edges=1,
            ndata_schemes={'hv': Scheme(shape=(1,), dtype=torch.float32)}
            edata_schemes={'he': Scheme(shape=(1,), dtype=torch.float32)})
        >>> g.ndata['hv']
        tensor([[2.]])
        >>> g.edata['he']
        tensor([[2.]])

703
704
705
706
707
708
709
710
711
712
713
714
715
        Removing nodes from a batched graph preserves batch information.

        >>> g = dgl.graph((torch.tensor([0, 0, 2]), torch.tensor([0, 1, 2])))
        >>> g2 = dgl.graph((torch.tensor([1, 2, 3]), torch.tensor([1, 3, 4])))
        >>> bg = dgl.batch([g, g2])
        >>> bg.batch_num_nodes()
        tensor([3, 5])
        >>> bg.remove_nodes([1, 4])
        >>> bg.batch_num_nodes()
        tensor([2, 4])
        >>> bg.batch_num_edges()
        tensor([2, 2])

716
717
718
        **Heterogeneous Graphs with Multiple Node Types**

        >>> g = dgl.heterograph({
719
720
721
722
723
        ...     ('user', 'plays', 'game'): (torch.tensor([0, 1, 1, 2]),
        ...                                 torch.tensor([0, 0, 1, 1])),
        ...     ('developer', 'develops', 'game'): (torch.tensor([0, 1]),
        ...                                         torch.tensor([0, 1]))
        ...     })
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
        >>> g.remove_nodes(torch.tensor([0, 1]))
        DGLError: Node type name must be specified
        if there are more than one node types.
        >>> g.remove_nodes(torch.tensor([0, 1]), ntype='game')
        >>> g.num_nodes('user')
        3
        >>> g.num_nodes('game')
        0
        >>> g.num_edges('plays')
        0

        See Also
        --------
        add_nodes
        add_edges
        remove_edges
        """
        # TODO(xiangsx): block do not support remove_nodes
        if ntype is None:
            if self._graph.number_of_ntypes() != 1:
                raise DGLError('Node type name must be specified if there are more than one ' \
                               'node types.')
Minjie Wang's avatar
Minjie Wang committed
746

747
748
749
750
751
752
753
754
755
756
757
758
        nids = utils.prepare_tensor(self, nids, 'u')
        if len(nids) == 0:
            # no node to delete
            return
        assert self.number_of_nodes(ntype) > F.as_scalar(F.max(nids, dim=0)), \
            'The input nids {} is out of the range [0:{})'.format(
                F.as_scalar(F.max(nids, dim=0)), self.number_of_nodes(ntype))

        ntid = self.get_ntype_id(ntype)
        nodes = {}
        for c_ntype in self.ntypes:
            if self.get_ntype_id(c_ntype) == ntid:
759
                target_ntype = c_ntype
760
761
762
763
764
                original_nids = self.nodes(c_ntype)
                nodes[c_ntype] = utils.compensate(nids, original_nids)
            else:
                nodes[c_ntype] = self.nodes(c_ntype)

765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
        # If the graph is batched, update batch_num_nodes
        batched = self._batch_num_nodes is not None
        if batched:
            one_hot_removed_nodes = F.zeros((self.num_nodes(target_ntype),),
                                            F.float32, self.device)
            one_hot_removed_nodes = F.scatter_row(one_hot_removed_nodes, nids,
                                                  F.full_1d(len(nids), 1., F.float32, self.device))
            c_ntype_batch_num_nodes = self._batch_num_nodes[target_ntype]
            batch_num_removed_nodes = segment.segment_reduce(
                c_ntype_batch_num_nodes, one_hot_removed_nodes, reducer='sum')
            self._batch_num_nodes[target_ntype] = c_ntype_batch_num_nodes - \
                                                  F.astype(batch_num_removed_nodes, F.int64)
            # Record old num_edges to check later whether some edges were removed
            old_num_edges = {c_etype: self._graph.number_of_edges(self.get_etype_id(c_etype))
                             for c_etype in self.canonical_etypes}

781
        # node_subgraph
782
783
        # If batch_num_edges is to be updated, record the original edge IDs
        sub_g = self.subgraph(nodes, store_ids=store_ids or batched)
784
785
786
787
        self._graph = sub_g._graph
        self._node_frames = sub_g._node_frames
        self._edge_frames = sub_g._edge_frames

788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
        # If the graph is batched, update batch_num_edges
        if batched:
            canonical_etypes = [
                c_etype for c_etype in self.canonical_etypes if
                self._graph.number_of_edges(self.get_etype_id(c_etype)) != old_num_edges[c_etype]]

            for c_etype in canonical_etypes:
                if self._graph.number_of_edges(self.get_etype_id(c_etype)) == 0:
                    self._batch_num_edges[c_etype] = F.zeros(
                        (self.batch_size,), F.int64, self.device)
                    continue

                one_hot_left_edges = F.zeros((old_num_edges[c_etype],), F.float32, self.device)
                eids = self.edges[c_etype].data[EID]
                one_hot_left_edges = F.scatter_row(one_hot_left_edges, eids,
                                                   F.full_1d(len(eids), 1., F.float32, self.device))
                batch_num_left_edges = segment.segment_reduce(
                    self._batch_num_edges[c_etype], one_hot_left_edges, reducer='sum')
                self._batch_num_edges[c_etype] = F.astype(batch_num_left_edges, F.int64)

        if batched and not store_ids:
            for c_ntype in self.ntypes:
                self.nodes[c_ntype].data.pop(NID)
            for c_etype in self.canonical_etypes:
                self.edges[c_etype].data.pop(EID)

814
815
816
    def _reset_cached_info(self):
        """Some info like batch_num_nodes may be stale after mutation
        Clean these cached info
Minjie Wang's avatar
Minjie Wang committed
817
        """
818
819
820
        self._batch_num_nodes = None
        self._batch_num_edges = None

Minjie Wang's avatar
Minjie Wang committed
821
822
823
824

    #################################################################
    # Metagraph query
    #################################################################
Da Zheng's avatar
Da Zheng committed
825

826
827
828
829
830
831
    @property
    def is_unibipartite(self):
        """Return whether the graph is a uni-bipartite graph.

        A uni-bipartite heterograph can further divide its node types into two sets:
        SRC and DST. All edges are from nodes in SRC to nodes in DST. The following APIs
832
        can be used to get the type, data, and nodes that belong to SRC and DST sets:
833
834
835
836
837
838
839
840
841
842
843

        * :func:`srctype` and :func:`dsttype`
        * :func:`srcdata` and :func:`dstdata`
        * :func:`srcnodes` and :func:`dstnodes`

        Note that we allow two node types to have the same name as long as one
        belongs to SRC while the other belongs to DST. To distinguish them, prepend
        the name with ``"SRC/"`` or ``"DST/"`` when specifying a node type.
        """
        return self._is_unibipartite

844
    @property
Minjie Wang's avatar
Minjie Wang committed
845
    def ntypes(self):
846
        """Return all the node type names in the graph.
Mufei Li's avatar
Mufei Li committed
847
848
849

        Returns
        -------
850
851
852
853
854
855
856
        list[str]
            All the node type names in a list.

        Notes
        -----
        DGL internally assigns an integer ID for each node type. The returned
        node type names are sorted according to their IDs.
Mufei Li's avatar
Mufei Li committed
857
858
859

        Examples
        --------
860
861
862
863
        The following example uses PyTorch backend.

        >>> import dgl
        >>> import torch
Mufei Li's avatar
Mufei Li committed
864

865
866
867
868
869
        >>> g = dgl.heterograph({
        ...     ('user', 'follows', 'user'): (torch.tensor([0, 1]), torch.tensor([1, 2])),
        ...     ('user', 'follows', 'game'): (torch.tensor([0, 1, 2]), torch.tensor([1, 2, 3])),
        ...     ('user', 'plays', 'game'): (torch.tensor([1, 3]), torch.tensor([2, 3]))
        ... })
Mufei Li's avatar
Mufei Li committed
870
        >>> g.ntypes
871
        ['game', 'user']
Mufei Li's avatar
Mufei Li committed
872
        """
873
        return self._ntypes
Da Zheng's avatar
Da Zheng committed
874

875
    @property
Minjie Wang's avatar
Minjie Wang committed
876
    def etypes(self):
877
        """Return all the edge type names in the graph.
Mufei Li's avatar
Mufei Li committed
878
879
880

        Returns
        -------
881
882
        list[str]
            All the edge type names in a list.
883
884
885

        Notes
        -----
886
887
888
889
890
891
892
893
894
895
896
897
        DGL internally assigns an integer ID for each edge type. The returned
        edge type names are sorted according to their IDs.

        The complete format to specify an relation is a string triplet ``(str, str, str)``
        for source node type, edge type and destination node type. DGL calls this
        format *canonical edge type*. An edge type can appear in multiple canonical edge types.
        For example, ``'interacts'`` can appear in two canonical edge types
        ``('drug', 'interacts', 'drug')`` and ``('protein', 'interacts', 'protein')``.

        See Also
        --------
        canonical_etypes
Mufei Li's avatar
Mufei Li committed
898
899
900

        Examples
        --------
901
902
903
904
        The following example uses PyTorch backend.

        >>> import dgl
        >>> import torch
Mufei Li's avatar
Mufei Li committed
905

906
907
908
909
910
        >>> g = dgl.heterograph({
        ...     ('user', 'follows', 'user'): (torch.tensor([0, 1]), torch.tensor([1, 2])),
        ...     ('user', 'follows', 'game'): (torch.tensor([0, 1, 2]), torch.tensor([1, 2, 3])),
        ...     ('user', 'plays', 'game'): (torch.tensor([1, 3]), torch.tensor([2, 3]))
        ... })
Mufei Li's avatar
Mufei Li committed
911
        >>> g.etypes
912
        ['follows', 'follows', 'plays']
Mufei Li's avatar
Mufei Li committed
913
        """
914
        return self._etypes
Da Zheng's avatar
Da Zheng committed
915

Minjie Wang's avatar
Minjie Wang committed
916
917
    @property
    def canonical_etypes(self):
918
        """Return all the canonical edge types in the graph.
Minjie Wang's avatar
Minjie Wang committed
919

920
921
        A canonical edge type is a string triplet ``(str, str, str)``
        for source node type, edge type and destination node type.
Mufei Li's avatar
Mufei Li committed
922
923
924

        Returns
        -------
925
926
927
928
929
930
931
932
933
934
935
        list[(str, str, str)]
            All the canonical edge type triplets in a list.

        Notes
        -----
        DGL internally assigns an integer ID for each edge type. The returned
        edge type names are sorted according to their IDs.

        See Also
        --------
        etypes
Mufei Li's avatar
Mufei Li committed
936
937
938

        Examples
        --------
939
940
941
942
        The following example uses PyTorch backend.

        >>> import dgl
        >>> import torch
Mufei Li's avatar
Mufei Li committed
943

944
945
946
947
948
        >>> g = dgl.heterograph({
        ...     ('user', 'follows', 'user'): (torch.tensor([0, 1]), torch.tensor([1, 2])),
        ...     ('user', 'follows', 'game'): (torch.tensor([0, 1, 2]), torch.tensor([1, 2, 3])),
        ...     ('user', 'plays', 'game'): (torch.tensor([1, 3]), torch.tensor([2, 3]))
        ... })
Mufei Li's avatar
Mufei Li committed
949
        >>> g.canonical_etypes
950
951
952
        [('user', 'follows', 'user'),
         ('user', 'follows', 'game'),
         ('user', 'plays', 'game')]
Minjie Wang's avatar
Minjie Wang committed
953
954
955
        """
        return self._canonical_etypes

956
    @property
957
    def srctypes(self):
958
959
960
961
962
963
964
965
        """Return all the source node type names in this graph.

        If the graph can further divide its node types into two subsets A and B where
        all the edeges are from nodes of types in A to nodes of types in B, we call
        this graph a *uni-bipartite* graph and the nodes in A being the *source*
        nodes and the ones in B being the *destination* nodes. If the graph is not
        uni-bipartite, the source and destination nodes are just the entire set of
        nodes in the graph.
966
967
968

        Returns
        -------
969
970
        list[str]
            All the source node type names in a list.
971

972
973
974
975
        See Also
        --------
        dsttypes
        is_unibipartite
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000

        Examples
        --------
        The following example uses PyTorch backend.

        >>> import dgl
        >>> import torch

        Query for a uni-bipartite graph.

        >>> g = dgl.heterograph({
        ...     ('user', 'plays', 'game'): (torch.tensor([0]), torch.tensor([1])),
        ...     ('developer', 'develops', 'game'): (torch.tensor([1]), torch.tensor([2]))
        ... })
        >>> g.srctypes
        ['developer', 'user']

        Query for a graph that is not uni-bipartite.

        >>> g = dgl.heterograph({
        ...     ('user', 'follows', 'user'): (torch.tensor([0]), torch.tensor([1])),
        ...     ('developer', 'develops', 'game'): (torch.tensor([1]), torch.tensor([2]))
        ... })
        >>> g.srctypes
        ['developer', 'game', 'user']
1001
1002
1003
1004
1005
        """
        if self.is_unibipartite:
            return sorted(list(self._srctypes_invmap.keys()))
        else:
            return self.ntypes
1006
1007

    @property
1008
    def dsttypes(self):
1009
1010
1011
1012
1013
1014
1015
1016
        """Return all the destination node type names in this graph.

        If the graph can further divide its node types into two subsets A and B where
        all the edeges are from nodes of types in A to nodes of types in B, we call
        this graph a *uni-bipartite* graph and the nodes in A being the *source*
        nodes and the ones in B being the *destination* nodes. If the graph is not
        uni-bipartite, the source and destination nodes are just the entire set of
        nodes in the graph.
1017
1018
1019

        Returns
        -------
1020
1021
        list[str]
            All the destination node type names in a list.
1022

1023
1024
1025
1026
        See Also
        --------
        srctypes
        is_unibipartite
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051

        Examples
        --------
        The following example uses PyTorch backend.

        >>> import dgl
        >>> import torch

        Query for a uni-bipartite graph.

        >>> g = dgl.heterograph({
        ...     ('user', 'plays', 'game'): (torch.tensor([0]), torch.tensor([1])),
        ...     ('developer', 'develops', 'game'): (torch.tensor([1]), torch.tensor([2]))
        ... })
        >>> g.dsttypes
        ['game']

        Query for a graph that is not uni-bipartite.

        >>> g = dgl.heterograph({
        ...     ('user', 'follows', 'user'): (torch.tensor([0]), torch.tensor([1])),
        ...     ('developer', 'develops', 'game'): (torch.tensor([1]), torch.tensor([2]))
        ... })
        >>> g.dsttypes
        ['developer', 'game', 'user']
1052
1053
1054
1055
1056
        """
        if self.is_unibipartite:
            return sorted(list(self._dsttypes_invmap.keys()))
        else:
            return self.ntypes
1057

Da Zheng's avatar
Da Zheng committed
1058
    def metagraph(self):
1059
        """Return the metagraph of the heterograph.
1060

1061
1062
1063
        The metagraph (or network schema) of a heterogeneous network specifies type constraints
        on the sets of nodes and edges between the nodes. For a formal definition, refer to
        `Yizhou et al. <https://www.kdd.org/exploration_files/V14-02-03-Sun.pdf>`_.
Minjie Wang's avatar
Minjie Wang committed
1064
1065
1066
1067

        Returns
        -------
        networkx.MultiDiGraph
1068
            The metagraph.
Mufei Li's avatar
Mufei Li committed
1069
1070
1071

        Examples
        --------
1072
        The following example uses PyTorch backend.
Mufei Li's avatar
Mufei Li committed
1073

1074
1075
        >>> import dgl
        >>> import torch
Mufei Li's avatar
Mufei Li committed
1076

1077
1078
1079
1080
1081
1082
        >>> g = dgl.heterograph({
        ...     ('user', 'follows', 'user'): (torch.tensor([0, 1]), torch.tensor([1, 2])),
        ...     ('user', 'follows', 'game'): (torch.tensor([0, 1, 2]), torch.tensor([1, 2, 3])),
        ...     ('user', 'plays', 'game'): (torch.tensor([1, 3]), torch.tensor([2, 3]))
        ... })
        >>> meta_g = g.metagraph()
Mufei Li's avatar
Mufei Li committed
1083
1084
1085
        >>> meta_g.nodes()
        NodeView(('user', 'game'))
        >>> meta_g.edges()
1086
        OutMultiEdgeDataView([('user', 'user'), ('user', 'game'), ('user', 'game')])
Minjie Wang's avatar
Minjie Wang committed
1087
        """
1088
1089
1090
1091
1092
1093
        nx_graph = self._graph.metagraph.to_networkx()
        nx_metagraph = nx.MultiDiGraph()
        for u_v in nx_graph.edges:
            srctype, etype, dsttype = self.canonical_etypes[nx_graph.edges[u_v]['id']]
            nx_metagraph.add_edge(srctype, dsttype, etype)
        return nx_metagraph
Minjie Wang's avatar
Minjie Wang committed
1094
1095

    def to_canonical_etype(self, etype):
1096
        """Convert an edge type to the corresponding canonical edge type in the graph.
Minjie Wang's avatar
Minjie Wang committed
1097

1098
1099
1100
1101
1102
        A canonical edge type is a string triplet ``(str, str, str)``
        for source node type, edge type and destination node type.

        The function expects the given edge type name can uniquely identify a canonical edge
        type. DGL will raise error if this is not the case.
Minjie Wang's avatar
Minjie Wang committed
1103
1104
1105

        Parameters
        ----------
1106
        etype : str or (str, str, str)
1107
            If :attr:`etype` is an edge type (str), it returns the corresponding canonical edge
1108
1109
            type in the graph. If :attr:`etype` is already a canonical edge type,
            it directly returns the input unchanged.
Minjie Wang's avatar
Minjie Wang committed
1110
1111
1112

        Returns
        -------
1113
        (str, str, str)
1114
1115
            The canonical edge type corresponding to the edge type.

Mufei Li's avatar
Mufei Li committed
1116
1117
        Examples
        --------
1118
        The following example uses PyTorch backend.
Mufei Li's avatar
Mufei Li committed
1119

1120
1121
1122
1123
        >>> import dgl
        >>> import torch

        Create a heterograph.
Mufei Li's avatar
Mufei Li committed
1124

1125
1126
1127
1128
1129
        >>> g = dgl.heterograph({
        ...     ('user', 'follows', 'user'): ([0, 1], [1, 2]),
        ...     ('user', 'plays', 'game'): ([0, 1, 1, 2], [0, 0, 1, 1]),
        ...     ('developer', 'follows', 'game'): ([0, 1], [0, 1])
        ... })
Mufei Li's avatar
Mufei Li committed
1130

1131
        Map an edge type to its corresponding canonical edge type.
Mufei Li's avatar
Mufei Li committed
1132
1133
1134
1135
1136

        >>> g.to_canonical_etype('plays')
        ('user', 'plays', 'game')
        >>> g.to_canonical_etype(('user', 'plays', 'game'))
        ('user', 'plays', 'game')
1137
1138
1139
1140

        See Also
        --------
        canonical_etypes
1141
        """
1142
1143
1144
1145
1146
        if etype is None:
            if len(self.etypes) != 1:
                raise DGLError('Edge type name must be specified if there are more than one '
                               'edge types.')
            etype = self.etypes[0]
Minjie Wang's avatar
Minjie Wang committed
1147
1148
        if isinstance(etype, tuple):
            return etype
1149
        else:
Minjie Wang's avatar
Minjie Wang committed
1150
1151
1152
1153
            ret = self._etype2canonical.get(etype, None)
            if ret is None:
                raise DGLError('Edge type "{}" does not exist.'.format(etype))
            if len(ret) == 0:
1154
1155
                raise DGLError('Edge type "%s" is ambiguous. Please use canonical edge type '
                               'in the form of (srctype, etype, dsttype)' % etype)
Minjie Wang's avatar
Minjie Wang committed
1156
1157
1158
            return ret

    def get_ntype_id(self, ntype):
1159
        """Return the ID of the given node type.
Minjie Wang's avatar
Minjie Wang committed
1160
1161
1162

        ntype can also be None. If so, there should be only one node type in the
        graph.
1163

Minjie Wang's avatar
Minjie Wang committed
1164
1165
1166
1167
        Parameters
        ----------
        ntype : str
            Node type
Da Zheng's avatar
Da Zheng committed
1168
1169
1170

        Returns
        -------
Minjie Wang's avatar
Minjie Wang committed
1171
1172
        int
        """
1173
        if self.is_unibipartite and ntype is not None:
1174
1175
1176
1177
1178
1179
1180
1181
            # Only check 'SRC/' and 'DST/' prefix when is_unibipartite graph is True.
            if ntype.startswith('SRC/'):
                return self.get_ntype_id_from_src(ntype[4:])
            elif ntype.startswith('DST/'):
                return self.get_ntype_id_from_dst(ntype[4:])
            # If there is no prefix, fallback to normal lookup.

        # Lookup both SRC and DST
Minjie Wang's avatar
Minjie Wang committed
1182
        if ntype is None:
1183
            if self.is_unibipartite or len(self._srctypes_invmap) != 1:
Minjie Wang's avatar
Minjie Wang committed
1184
1185
1186
                raise DGLError('Node type name must be specified if there are more than one '
                               'node types.')
            return 0
1187
        ntid = self._srctypes_invmap.get(ntype, self._dsttypes_invmap.get(ntype, None))
Minjie Wang's avatar
Minjie Wang committed
1188
1189
1190
        if ntid is None:
            raise DGLError('Node type "{}" does not exist.'.format(ntype))
        return ntid
Da Zheng's avatar
Da Zheng committed
1191

1192
    def get_ntype_id_from_src(self, ntype):
1193
        """Internal function to return the ID of the given SRC node type.
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210

        ntype can also be None. If so, there should be only one node type in the
        SRC category. Callable even when the self graph is not uni-bipartite.

        Parameters
        ----------
        ntype : str
            Node type

        Returns
        -------
        int
        """
        if ntype is None:
            if len(self._srctypes_invmap) != 1:
                raise DGLError('SRC node type name must be specified if there are more than one '
                               'SRC node types.')
1211
            return next(iter(self._srctypes_invmap.values()))
1212
1213
1214
1215
1216
1217
        ntid = self._srctypes_invmap.get(ntype, None)
        if ntid is None:
            raise DGLError('SRC node type "{}" does not exist.'.format(ntype))
        return ntid

    def get_ntype_id_from_dst(self, ntype):
1218
        """Internal function to return the ID of the given DST node type.
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235

        ntype can also be None. If so, there should be only one node type in the
        DST category. Callable even when the self graph is not uni-bipartite.

        Parameters
        ----------
        ntype : str
            Node type

        Returns
        -------
        int
        """
        if ntype is None:
            if len(self._dsttypes_invmap) != 1:
                raise DGLError('DST node type name must be specified if there are more than one '
                               'DST node types.')
1236
            return next(iter(self._dsttypes_invmap.values()))
1237
1238
1239
1240
1241
        ntid = self._dsttypes_invmap.get(ntype, None)
        if ntid is None:
            raise DGLError('DST node type "{}" does not exist.'.format(ntype))
        return ntid

Minjie Wang's avatar
Minjie Wang committed
1242
1243
    def get_etype_id(self, etype):
        """Return the id of the given edge type.
1244

Minjie Wang's avatar
Minjie Wang committed
1245
1246
1247
1248
1249
1250
1251
        etype can also be None. If so, there should be only one edge type in the
        graph.

        Parameters
        ----------
        etype : str or tuple of str
            Edge type
Da Zheng's avatar
Da Zheng committed
1252

1253
1254
        Returns
        -------
Minjie Wang's avatar
Minjie Wang committed
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
        int
        """
        if etype is None:
            if self._graph.number_of_etypes() != 1:
                raise DGLError('Edge type name must be specified if there are more than one '
                               'edge types.')
            return 0
        etid = self._etypes_invmap.get(self.to_canonical_etype(etype), None)
        if etid is None:
            raise DGLError('Edge type "{}" does not exist.'.format(etype))
        return etid
Da Zheng's avatar
Da Zheng committed
1266

1267
1268
1269
1270
1271
    #################################################################
    # Batching
    #################################################################
    @property
    def batch_size(self):
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
        """Return the number of graphs in the batched graph.

        Returns
        -------
        int
            The Number of graphs in the batch. If the graph is not a batched one,
            it will return 1.

        Examples
        --------

        The following example uses PyTorch backend.

        >>> import dgl
        >>> import torch

        Query for homogeneous graphs.

        >>> g1 = dgl.graph((torch.tensor([0, 1, 2]), torch.tensor([1, 2, 3])))
        >>> g1.batch_size
        1
        >>> g2 = dgl.graph((torch.tensor([0, 0, 0, 1]), torch.tensor([0, 1, 2, 0])))
        >>> bg = dgl.batch([g1, g2])
        >>> bg.batch_size
        2

        Query for heterogeneous graphs.

        >>> hg1 = dgl.heterograph({
        ...       ('user', 'plays', 'game') : (torch.tensor([0, 1]), torch.tensor([0, 0]))})
        >>> hg1.batch_size
        1
        >>> hg2 = dgl.heterograph({
        ...       ('user', 'plays', 'game') : (torch.tensor([0, 0]), torch.tensor([1, 0]))})
        >>> bg = dgl.batch([hg1, hg2])
        >>> bg.batch_size
        2
        """
1310
1311
1312
        return len(self.batch_num_nodes(self.ntypes[0]))

    def batch_num_nodes(self, ntype=None):
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
        """Return the number of nodes for each graph in the batch with the specified node type.

        Parameters
        ----------
        ntype : str, optional
            The node type for query. If the graph has multiple node types, one must
            specify the argument. Otherwise, it can be omitted. If the graph is not a batched
            one, it will return a list of length 1 that holds the number of nodes in the graph.

        Returns
        -------
        Tensor
            The number of nodes with the specified type for each graph in the batch. The i-th
            element of it is the number of nodes with the specified type for the i-th graph.

        Examples
        --------

        The following example uses PyTorch backend.

        >>> import dgl
        >>> import torch

        Query for homogeneous graphs.

        >>> g1 = dgl.graph((torch.tensor([0, 1, 2]), torch.tensor([1, 2, 3])))
        >>> g1.batch_num_nodes()
        tensor([4])
        >>> g2 = dgl.graph((torch.tensor([0, 0, 0, 1]), torch.tensor([0, 1, 2, 0])))
        >>> bg = dgl.batch([g1, g2])
        >>> bg.batch_num_nodes()
        tensor([4, 3])

        Query for heterogeneous graphs.

        >>> hg1 = dgl.heterograph({
        ...       ('user', 'plays', 'game') : (torch.tensor([0, 1]), torch.tensor([0, 0]))})
        >>> hg2 = dgl.heterograph({
        ...       ('user', 'plays', 'game') : (torch.tensor([0, 0]), torch.tensor([1, 0]))})
        >>> bg = dgl.batch([hg1, hg2])
        >>> bg.batch_num_nodes('user')
        tensor([2, 1])
        """
        if ntype is not None and ntype not in self.ntypes:
            raise DGLError('Expect ntype in {}, got {}'.format(self.ntypes, ntype))

1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
        if self._batch_num_nodes is None:
            self._batch_num_nodes = {}
            for ty in self.ntypes:
                bnn = F.copy_to(F.tensor([self.number_of_nodes(ty)], F.int64), self.device)
                self._batch_num_nodes[ty] = bnn
        if ntype is None:
            if len(self.ntypes) != 1:
                raise DGLError('Node type name must be specified if there are more than one '
                               'node types.')
            ntype = self.ntypes[0]
        return self._batch_num_nodes[ntype]

    def set_batch_num_nodes(self, val):
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
        """Manually set the number of nodes for each graph in the batch with the specified node
        type.

        Parameters
        ----------
        val : Tensor or Mapping[str, Tensor]
            The dictionary storing number of nodes for each graph in the batch for all node types.
            If the graph has only one node type, ``val`` can also be a single array indicating the
            number of nodes per graph in the batch.

        Notes
        -----
        This API is always used together with ``set_batch_num_edges`` to specify batching
        information of a graph, it also do not check the correspondance between the graph structure
        and batching information and user must guarantee there will be no cross-graph edges in the
        batch.

        Examples
        --------

        The following example uses PyTorch backend.

        >>> import dgl
        >>> import torch

        Create a homogeneous graph.
1398

1399
1400
1401
        >>> g = dgl.graph(([0, 1, 2, 3, 4, 5], [1, 2, 0, 4, 5, 3]))

        Manually set batch information
1402

1403
1404
        >>> g.set_batch_num_nodes(torch.tensor([3, 3]))
        >>> g.set_batch_num_edges(torch.tensor([3, 3]))
1405
1406

        Unbatch the graph.
1407

1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
        >>> dgl.unbatch(g)
        [Graph(num_nodes=3, num_edges=3,
              ndata_schemes={}
              edata_schemes={}), Graph(num_nodes=3, num_edges=3,
              ndata_schemes={}
              edata_schemes={})]

        Create a heterogeneous graph.

        >>> hg = dgl.heterograph({
        ...      ('user', 'plays', 'game') : ([0, 1, 2, 3, 4, 5], [0, 1, 1, 3, 3, 2]),
        ...      ('developer', 'develops', 'game') : ([0, 1, 2, 3], [1, 0, 3, 2])})

        Manually set batch information.

        >>> hg.set_batch_num_nodes({
        ...     'user': torch.tensor([3, 3]),
        ...     'game': torch.tensor([2, 2]),
        ...     'developer': torch.tensor([2, 2])})
        >>> hg.set_batch_num_edges({
        ...     ('user', 'plays', 'game'): torch.tensor([3, 3]),
        ...     ('developer', 'develops', 'game'): torch.tensor([2, 2])})

        Unbatch the graph.

        >>> g1, g2 = dgl.unbatch(hg)
        >>> g1
        Graph(num_nodes={'developer': 2, 'game': 2, 'user': 3},
              num_edges={('developer', 'develops', 'game'): 2, ('user', 'plays', 'game'): 3},
              metagraph=[('developer', 'game', 'develops'), ('user', 'game', 'plays')])
        >>> g2
        Graph(num_nodes={'developer': 2, 'game': 2, 'user': 3},
              num_edges={('developer', 'develops', 'game'): 2, ('user', 'plays', 'game'): 3},
              metagraph=[('developer', 'game', 'develops'), ('user', 'game', 'plays')])

        See Also
        --------
        set_batch_num_edges
        batch
        unbatch
        """
1449
1450
1451
1452
1453
1454
1455
        if not isinstance(val, Mapping):
            if len(self.ntypes) != 1:
                raise DGLError('Must provide a dictionary when there are multiple node types.')
            val = {self.ntypes[0] : val}
        self._batch_num_nodes = val

    def batch_num_edges(self, etype=None):
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
        """Return the number of edges for each graph in the batch with the specified edge type.

        Parameters
        ----------
        etype : str or tuple of str, optional
            The edge type for query, which can be an edge type (str) or a canonical edge type
            (3-tuple of str). When an edge type appears in multiple canonical edge types, one
            must use a canonical edge type. If the graph has multiple edge types, one must
            specify the argument. Otherwise, it can be omitted.

        Returns
        -------
        Tensor
            The number of edges with the specified type for each graph in the batch. The i-th
            element of it is the number of edges with the specified type for the i-th graph.
            If the graph is not a batched one, it will return a list of length 1 that holds
            the number of edges in the graph.

        Examples
        --------

        The following example uses PyTorch backend.

        >>> import dgl
        >>> import torch

        Query for homogeneous graphs.

        >>> g1 = dgl.graph((torch.tensor([0, 1, 2]), torch.tensor([1, 2, 3])))
        >>> g1.batch_num_edges()
        tensor([3])
        >>> g2 = dgl.graph((torch.tensor([0, 0, 0, 1]), torch.tensor([0, 1, 2, 0])))
        >>> bg = dgl.batch([g1, g2])
        >>> bg.batch_num_edges()
        tensor([3, 4])

        Query for heterogeneous graphs.

        >>> hg1 = dgl.heterograph({
        ...       ('user', 'plays', 'game') : (torch.tensor([0, 1]), torch.tensor([0, 0]))})
        >>> hg2 = dgl.heterograph({
        ...       ('user', 'plays', 'game') : (torch.tensor([0, 0]), torch.tensor([1, 0]))})
        >>> bg = dgl.batch([hg1, hg2])
        >>> bg.batch_num_edges('plays')
        tensor([2, 2])
        """
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
        if self._batch_num_edges is None:
            self._batch_num_edges = {}
            for ty in self.canonical_etypes:
                bne = F.copy_to(F.tensor([self.number_of_edges(ty)], F.int64), self.device)
                self._batch_num_edges[ty] = bne
        if etype is None:
            if len(self.etypes) != 1:
                raise DGLError('Edge type name must be specified if there are more than one '
                               'edge types.')
            etype = self.canonical_etypes[0]
1512
1513
        else:
            etype = self.to_canonical_etype(etype)
1514
1515
1516
        return self._batch_num_edges[etype]

    def set_batch_num_edges(self, val):
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
        """Manually set the number of edges for each graph in the batch with the specified edge
        type.

        Parameters
        ----------
        val : Tensor or Mapping[str, Tensor]
            The dictionary storing number of edges for each graph in the batch for all edge types.
            If the graph has only one edge type, ``val`` can also be a single array indicating the
            number of edges per graph in the batch.

        Notes
        -----
1529
        This API is always used together with ``set_batch_num_nodes`` to specify batching
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
        information of a graph, it also do not check the correspondance between the graph structure
        and batching information and user must guarantee there will be no cross-graph edges in the
        batch.

        Examples
        --------

        The following example uses PyTorch backend.

        >>> import dgl
        >>> import torch

        Create a homogeneous graph.
1543

1544
1545
1546
        >>> g = dgl.graph(([0, 1, 2, 3, 4, 5], [1, 2, 0, 4, 5, 3]))

        Manually set batch information
1547

1548
1549
        >>> g.set_batch_num_nodes(torch.tensor([3, 3]))
        >>> g.set_batch_num_edges(torch.tensor([3, 3]))
1550
1551

        Unbatch the graph.
1552

1553
        >>> dgl.unbatch(g)
1554
1555
1556
1557
1558
        [Graph(num_nodes=3, num_edges=3,
              ndata_schemes={}
              edata_schemes={}), Graph(num_nodes=3, num_edges=3,
              ndata_schemes={}
              edata_schemes={})]
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593

        Create a heterogeneous graph.

        >>> hg = dgl.heterograph({
        ...      ('user', 'plays', 'game') : ([0, 1, 2, 3, 4, 5], [0, 1, 1, 3, 3, 2]),
        ...      ('developer', 'develops', 'game') : ([0, 1, 2, 3], [1, 0, 3, 2])})

        Manually set batch information.

        >>> hg.set_batch_num_nodes({
        ...     'user': torch.tensor([3, 3]),
        ...     'game': torch.tensor([2, 2]),
        ...     'developer': torch.tensor([2, 2])})
        >>> hg.set_batch_num_edges(
        ...     {('user', 'plays', 'game'): torch.tensor([3, 3]),
        ...     ('developer', 'develops', 'game'): torch.tensor([2, 2])})

        Unbatch the graph.

        >>> g1, g2 = dgl.unbatch(hg)
        >>> g1
        Graph(num_nodes={'developer': 2, 'game': 2, 'user': 3},
              num_edges={('developer', 'develops', 'game'): 2, ('user', 'plays', 'game'): 3},
              metagraph=[('developer', 'game', 'develops'), ('user', 'game', 'plays')])
        >>> g2
        Graph(num_nodes={'developer': 2, 'game': 2, 'user': 3},
              num_edges={('developer', 'develops', 'game'): 2, ('user', 'plays', 'game'): 3},
              metagraph=[('developer', 'game', 'develops'), ('user', 'game', 'plays')])

        See Also
        --------
        set_batch_num_nodes
        batch
        unbatch
        """
1594
1595
1596
1597
1598
1599
        if not isinstance(val, Mapping):
            if len(self.etypes) != 1:
                raise DGLError('Must provide a dictionary when there are multiple edge types.')
            val = {self.canonical_etypes[0] : val}
        self._batch_num_edges = val

Minjie Wang's avatar
Minjie Wang committed
1600
1601
1602
    #################################################################
    # View
    #################################################################
Da Zheng's avatar
Da Zheng committed
1603

1604
1605
1606
1607
1608
1609
1610
1611
    def get_node_storage(self, key, ntype=None):
        """Get storage object of node feature of type :attr:`ntype` and name :attr:`key`."""
        return self._node_frames[self.get_ntype_id(ntype)]._columns[key]

    def get_edge_storage(self, key, etype=None):
        """Get storage object of edge feature of type :attr:`etype` and name :attr:`key`."""
        return self._edge_frames[self.get_etype_id(etype)]._columns[key]

1612
    @property
Minjie Wang's avatar
Minjie Wang committed
1613
    def nodes(self):
1614
1615
1616
1617
1618
1619
        """Return a node view

        One can use it for:

        1. Getting the node IDs for a single node type.
        2. Setting/getting features for all nodes of a single node type.
Da Zheng's avatar
Da Zheng committed
1620

Minjie Wang's avatar
Minjie Wang committed
1621
1622
        Examples
        --------
Mufei Li's avatar
Mufei Li committed
1623
1624
        The following example uses PyTorch backend.

1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
        >>> import dgl
        >>> import torch

        Create a homogeneous graph and a heterogeneous graph of two node types.

        >>> g = dgl.graph((torch.tensor([0, 1]), torch.tensor([1, 2])))
        >>> hg = dgl.heterograph({
        ...     ('user', 'follows', 'user'): (torch.tensor([0, 1]), torch.tensor([1, 2])),
        ...     ('user', 'plays', 'game'): (torch.tensor([3, 4]), torch.tensor([5, 6]))
        ... })

        Get the node IDs of the homogeneous graph.

        >>> g.nodes()
        tensor([0, 1, 2])

        Get the node IDs of the heterogeneous graph. With multiple node types introduced,
        one needs to specify the node type for query.

        >>> hg.nodes('user')
        tensor([0, 1, 2, 3, 4])
Mufei Li's avatar
Mufei Li committed
1646

1647
1648
1649
1650
1651
1652
1653
        Set and get a feature 'h' for all nodes of a single type in the heterogeneous graph.

        >>> hg.nodes['user'].data['h'] = torch.ones(5, 1)
        >>> hg.nodes['user'].data['h']
        tensor([[1.], [1.], [1.], [1.], [1.]])

        To set node features for a graph with a single node type, use :func:`DGLGraph.ndata`.
Mufei Li's avatar
Mufei Li committed
1654
1655
1656
1657

        See Also
        --------
        ndata
1658
        """
1659
        # Todo (Mufei) Replace the syntax g.nodes[...].ndata[...] with g.nodes[...][...]
1660
1661
1662
1663
        return HeteroNodeView(self, self.get_ntype_id)

    @property
    def srcnodes(self):
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
        """Return a node view for source nodes

        If the graph is a uni-bipartite graph (see :func:`is_unibipartite` for reference),
        this is :func:`nodes` restricted to source node types. Otherwise, it is an alias
        for :func:`nodes`.

        One can use it for:

        1. Getting the node IDs for a single node type.
        2. Setting/getting features for all nodes of a single node type.
1674
1675
1676
1677
1678

        Examples
        --------
        The following example uses PyTorch backend.

1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
        >>> import dgl
        >>> import torch

        Create a uni-bipartite graph.

        >>> g = dgl.heterograph({
        ...     ('user', 'plays', 'game'): (torch.tensor([0]), torch.tensor([1])),
        ...     ('developer', 'develops', 'game'): (torch.tensor([1]), torch.tensor([2]))
        ... })

        Get the node IDs for source node types.

        >>> g.srcnodes('user')
        tensor([0])
        >>> g.srcnodes('developer')
        tensor([0, 1])

        Set/get features for source node types.

        >>> g.srcnodes['user'].data['h'] = torch.ones(1, 1)
        >>> g.srcnodes['user'].data['h']
        tensor([[1.]])
1701

1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
        Create a graph that is not uni-bipartite.

        >>> g = dgl.heterograph({
        ...     ('user', 'follows', 'user'): (torch.tensor([0]), torch.tensor([1])),
        ...     ('developer', 'develops', 'game'): (torch.tensor([1]), torch.tensor([2]))
        ... })

        :func:`dgl.DGLGraph.srcnodes` falls back to :func:`dgl.DGLGraph.nodes` and one can
        get the node IDs for both source and destination node types.

        >>> g.srcnodes('game')
        tensor([0, 1, 2])

        One can also set/get features for destination node types in this case.

        >>> g.srcnodes['game'].data['h'] = torch.ones(3, 1)
        >>> g.srcnodes['game'].data['h']
        tensor([[1.],
                [1.],
                [1.]])
1722
1723
1724
1725
1726
1727
1728
1729
1730

        See Also
        --------
        srcdata
        """
        return HeteroNodeView(self, self.get_ntype_id_from_src)

    @property
    def dstnodes(self):
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
        """Return a node view for destination nodes

        If the graph is a uni-bipartite graph (see :func:`is_unibipartite` for reference),
        this is :func:`nodes` restricted to destination node types. Otherwise, it is an alias
        for :func:`nodes`.

        One can use it for:

        1. Getting the node IDs for a single node type.
        2. Setting/getting features for all nodes of a single node type.
1741
1742
1743
1744
1745

        Examples
        --------
        The following example uses PyTorch backend.

1746
1747
1748
1749
        >>> import dgl
        >>> import torch

        Create a uni-bipartite graph.
1750

1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
        >>> g = dgl.heterograph({
        ...     ('user', 'plays', 'game'): (torch.tensor([0]), torch.tensor([1])),
        ...     ('developer', 'develops', 'game'): (torch.tensor([1]), torch.tensor([2]))
        ... })

        Get the node IDs for destination node types.

        >>> g.dstnodes('game')
        tensor([0, 1, 2])

        Set/get features for destination node types.

        >>> g.dstnodes['game'].data['h'] = torch.ones(3, 1)
        >>> g.dstnodes['game'].data['h']
        tensor([[1.],
                [1.],
                [1.]])

        Create a graph that is not uni-bipartite.

        >>> g = dgl.heterograph({
        ...     ('user', 'follows', 'user'): (torch.tensor([0]), torch.tensor([1])),
        ...     ('developer', 'develops', 'game'): (torch.tensor([1]), torch.tensor([2]))
        ... })

        :func:`dgl.DGLGraph.dstnodes` falls back to :func:`dgl.DGLGraph.nodes` and one can
        get the node IDs for both source and destination node types.

        >>> g.dstnodes('developer')
        tensor([0, 1])

        One can also set/get features for source node types in this case.

        >>> g.dstnodes['developer'].data['h'] = torch.ones(2, 1)
        >>> g.dstnodes['developer'].data['h']
        tensor([[1.],
                [1.]])
1788
1789
1790
1791
1792
1793

        See Also
        --------
        dstdata
        """
        return HeteroNodeView(self, self.get_ntype_id_from_dst)
Da Zheng's avatar
Da Zheng committed
1794

1795
    @property
Minjie Wang's avatar
Minjie Wang committed
1796
    def ndata(self):
1797
1798
1799
1800
1801
        """Return a node data view for setting/getting node features

        Let ``g`` be a DGLGraph. If ``g`` is a graph of a single node type, ``g.ndata[feat]``
        returns the node feature associated with the name ``feat``. One can also set a node
        feature associated with the name ``feat`` by setting ``g.ndata[feat]`` to a tensor.
Da Zheng's avatar
Da Zheng committed
1802

1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
        If ``g`` is a graph of multiple node types, ``g.ndata[feat]`` returns a
        dict[str, Tensor] mapping node types to the node features associated with the name
        ``feat`` for the corresponding type. One can also set a node feature associated
        with the name ``feat`` for some node type(s) by setting ``g.ndata[feat]`` to a
        dictionary as described.

        Notes
        -----
        For setting features, the device of the features must be the same as the device
        of the graph.
Minjie Wang's avatar
Minjie Wang committed
1813
1814
1815

        Examples
        --------
Mufei Li's avatar
Mufei Li committed
1816
1817
        The following example uses PyTorch backend.

1818
1819
        >>> import dgl
        >>> import torch
Mufei Li's avatar
Mufei Li committed
1820

1821
        Set and get feature 'h' for a graph of a single node type.
1822

1823
1824
        >>> g = dgl.graph((torch.tensor([0, 1]), torch.tensor([1, 2])))
        >>> g.ndata['h'] = torch.ones(3, 1)
1825
        >>> g.ndata['h']
1826
1827
1828
        tensor([[1.],
                [1.],
                [1.]])
1829

1830
        Set and get feature 'h' for a graph of multiple node types.
1831

1832
1833
1834
1835
1836
        >>> g = dgl.heterograph({
        ...     ('user', 'follows', 'user'): (torch.tensor([1, 2]), torch.tensor([3, 4])),
        ...     ('player', 'plays', 'game'): (torch.tensor([2, 2]), torch.tensor([1, 1]))
        ... })
        >>> g.ndata['h'] = {'game': torch.zeros(2, 1), 'player': torch.ones(3, 1)}
1837
        >>> g.ndata['h']
1838
1839
1840
        {'game': tensor([[0.], [0.]]),
         'player': tensor([[1.], [1.], [1.]])}
        >>> g.ndata['h'] = {'game': torch.ones(2, 1)}
1841
        >>> g.ndata['h']
1842
1843
        {'game': tensor([[1.], [1.]]),
         'player': tensor([[1.], [1.], [1.]])}
1844

Mufei Li's avatar
Mufei Li committed
1845
1846
1847
        See Also
        --------
        nodes
Da Zheng's avatar
Da Zheng committed
1848
        """
1849
1850
1851
1852
1853
1854
1855
1856
1857
        if len(self.ntypes) == 1:
            ntid = self.get_ntype_id(None)
            ntype = self.ntypes[0]
            return HeteroNodeDataView(self, ntype, ntid, ALL)
        else:
            ntids = [self.get_ntype_id(ntype) for ntype in self.ntypes]
            ntypes = self.ntypes
            return HeteroNodeDataView(self, ntypes, ntids, ALL)

1858
1859
    @property
    def srcdata(self):
1860
        """Return a node data view for setting/getting source node features.
1861

1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
        Let ``g`` be a DGLGraph. If ``g`` is a graph of a single source node type,
        ``g.srcdata[feat]`` returns the source node feature associated with the name ``feat``.
        One can also set a source node feature associated with the name ``feat`` by
        setting ``g.srcdata[feat]`` to a tensor.

        If ``g`` is a graph of multiple source node types, ``g.srcdata[feat]`` returns a
        dict[str, Tensor] mapping source node types to the node features associated with
        the name ``feat`` for the corresponding type. One can also set a node feature
        associated with the name ``feat`` for some source node type(s) by setting
        ``g.srcdata[feat]`` to a dictionary as described.

        Notes
        -----
        For setting features, the device of the features must be the same as the device
        of the graph.
1877
1878
1879
1880
1881

        Examples
        --------
        The following example uses PyTorch backend.

1882
1883
        >>> import dgl
        >>> import torch
1884

1885
        Set and get feature 'h' for a graph of a single source node type.
1886
1887

        >>> g = dgl.heterograph({
1888
1889
1890
1891
1892
        ...     ('user', 'plays', 'game'): (torch.tensor([0, 1]), torch.tensor([1, 2]))})
        >>> g.srcdata['h'] = torch.ones(2, 1)
        >>> g.srcdata['h']
        tensor([[1.],
                [1.]])
1893

1894
        Set and get feature 'h' for a graph of multiple source node types.
1895
1896

        >>> g = dgl.heterograph({
1897
1898
1899
1900
        ...     ('user', 'plays', 'game'): (torch.tensor([1, 2]), torch.tensor([3, 4])),
        ...     ('player', 'plays', 'game'): (torch.tensor([2, 2]), torch.tensor([1, 1]))
        ... })
        >>> g.srcdata['h'] = {'user': torch.zeros(3, 1), 'player': torch.ones(3, 1)}
1901
        >>> g.srcdata['h']
1902
1903
1904
        {'player': tensor([[1.], [1.], [1.]]),
         'user': tensor([[0.], [0.], [0.]])}
        >>> g.srcdata['h'] = {'user': torch.ones(3, 1)}
1905
        >>> g.srcdata['h']
1906
1907
        {'player': tensor([[1.], [1.], [1.]]),
         'user': tensor([[1.], [1.], [1.]])}
1908
1909
1910
1911

        See Also
        --------
        nodes
1912
1913
        ndata
        srcnodes
1914
        """
1915
1916
1917
1918
1919
1920
1921
1922
        if len(self.srctypes) == 1:
            ntype = self.srctypes[0]
            ntid = self.get_ntype_id_from_src(ntype)
            return HeteroNodeDataView(self, ntype, ntid, ALL)
        else:
            ntypes = self.srctypes
            ntids = [self.get_ntype_id_from_src(ntype) for ntype in ntypes]
            return HeteroNodeDataView(self, ntypes, ntids, ALL)
1923
1924
1925

    @property
    def dstdata(self):
1926
1927
1928
1929
1930
1931
        """Return a node data view for setting/getting destination node features.

        Let ``g`` be a DGLGraph. If ``g`` is a graph of a single destination node type,
        ``g.dstdata[feat]`` returns the destination node feature associated with the name
        ``feat``. One can also set a destination node feature associated with the name
        ``feat`` by setting ``g.dstdata[feat]`` to a tensor.
1932

1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
        If ``g`` is a graph of multiple destination node types, ``g.dstdata[feat]`` returns a
        dict[str, Tensor] mapping destination node types to the node features associated with
        the name ``feat`` for the corresponding type. One can also set a node feature
        associated with the name ``feat`` for some destination node type(s) by setting
        ``g.dstdata[feat]`` to a dictionary as described.

        Notes
        -----
        For setting features, the device of the features must be the same as the device
        of the graph.
1943
1944
1945
1946
1947

        Examples
        --------
        The following example uses PyTorch backend.

1948
1949
        >>> import dgl
        >>> import torch
1950

1951
        Set and get feature 'h' for a graph of a single destination node type.
1952
1953

        >>> g = dgl.heterograph({
1954
1955
1956
1957
1958
1959
        ...     ('user', 'plays', 'game'): (torch.tensor([0, 1]), torch.tensor([1, 2]))})
        >>> g.dstdata['h'] = torch.ones(3, 1)
        >>> g.dstdata['h']
        tensor([[1.],
                [1.],
                [1.]])
1960

1961
        Set and get feature 'h' for a graph of multiple destination node types.
1962
1963

        >>> g = dgl.heterograph({
1964
1965
1966
1967
        ...     ('user', 'plays', 'game'): (torch.tensor([1, 2]), torch.tensor([1, 2])),
        ...     ('user', 'watches', 'movie'): (torch.tensor([2, 2]), torch.tensor([1, 1]))
        ... })
        >>> g.dstdata['h'] = {'game': torch.zeros(3, 1), 'movie': torch.ones(2, 1)}
1968
        >>> g.dstdata['h']
1969
1970
1971
        {'game': tensor([[0.], [0.], [0.]]),
         'movie': tensor([[1.], [1.]])}
        >>> g.dstdata['h'] = {'game': torch.ones(3, 1)}
1972
        >>> g.dstdata['h']
1973
1974
        {'game': tensor([[1.], [1.], [1.]]),
         'movie': tensor([[1.], [1.]])}
1975
1976
1977
1978

        See Also
        --------
        nodes
1979
1980
        ndata
        dstnodes
1981
        """
1982
1983
1984
1985
1986
1987
1988
1989
        if len(self.dsttypes) == 1:
            ntype = self.dsttypes[0]
            ntid = self.get_ntype_id_from_dst(ntype)
            return HeteroNodeDataView(self, ntype, ntid, ALL)
        else:
            ntypes = self.dsttypes
            ntids = [self.get_ntype_id_from_dst(ntype) for ntype in ntypes]
            return HeteroNodeDataView(self, ntypes, ntids, ALL)
1990

1991
    @property
Minjie Wang's avatar
Minjie Wang committed
1992
    def edges(self):
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
        """Return an edge view

        One can use it for:

        1. Getting the edges for a single edge type. In this case, it can take the
           following optional arguments:

            - form : str, optional
                  The return form, which can be one of the following:

                  - ``'uv'`` (default): The returned result is a 2-tuple of 1D tensors
                    :math:`(U, V)`, representing the source and destination nodes of all edges.
                    For each :math:`i`, :math:`(U[i], V[i])` forms an edge.
                  - ``'eid'``: The returned result is a 1D tensor :math:`EID`, representing
                    the IDs of all edges.
                  - ``'all'``: The returned result is a 3-tuple of 1D tensors :math:`(U, V, EID)`,
                    representing the source nodes, destination nodes and IDs of all edges.
                    For each :math:`i`, :math:`(U[i], V[i])` forms an edge with ID :math:`EID[i]`.
            - order : str, optional
                  The order of the returned edges, which can be one of the following:

                  - ``'eid'`` (default): The edges are sorted by their IDs.
                  - ``'srcdst'``: The edges are sorted first by their source node IDs and then
                    by their destination node IDs to break ties.
            - etype : str or tuple of str, optional
                  The edge type for query, which can be an edge type (str) or a canonical edge
                  type (3-tuple of str). When an edge type appears in multiple canonical edge
                  types, one must use a canonical edge type. If the graph has multiple edge
                  types, one must specify the argument. Otherwise, it can be omitted.
        2. Setting/getting features for all edges of a single edge type. To set/get a feature
           ``feat`` for edges of type ``etype`` in a graph ``g``, one can use
           ``g.edges[etype].data[feat]``.
2025

Minjie Wang's avatar
Minjie Wang committed
2026
2027
        Examples
        --------
Mufei Li's avatar
Mufei Li committed
2028
2029
        The following example uses PyTorch backend.

2030
2031
        >>> import dgl
        >>> import torch
Mufei Li's avatar
Mufei Li committed
2032

2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
        **Get the Edges for a Single Edge Type**

        Create a graph with a single edge type.

        >>> g = dgl.graph((torch.tensor([1, 0, 0]), torch.tensor([1, 1, 0])))
        >>> g.edges()
        (tensor([1, 0, 0]), tensor([1, 1, 0]))

        Specify a different value for :attr:`form` and :attr:`order`.

        >>> g.edges(form='all', order='srcdst')
        (tensor([0, 0, 1]), tensor([0, 1, 1]), tensor([2, 1, 0]))

        For a graph of multiple edge types, it is required to specify the edge type in query.

        >>> hg = dgl.heterograph({
        ...     ('user', 'follows', 'user'): (torch.tensor([0, 1]), torch.tensor([1, 2])),
        ...     ('user', 'plays', 'game'): (torch.tensor([3, 4]), torch.tensor([5, 6]))
        ... })
        >>> hg.edges(etype='plays')
        (tensor([3, 4]), tensor([5, 6]))

        **Set/get Features for All Edges of a Single Edge Type**

        Create a heterogeneous graph of two edge types.

        >>> hg = dgl.heterograph({
        ...     ('user', 'follows', 'user'): (torch.tensor([0, 1]), torch.tensor([1, 2])),
        ...     ('user', 'plays', 'game'): (torch.tensor([3, 4]), torch.tensor([5, 6]))
        ... })

        Set and get a feature 'h' for all edges of a single type in the heterogeneous graph.

        >>> hg.edges['follows'].data['h'] = torch.ones(2, 1)
        >>> hg.edges['follows'].data['h']
        tensor([[1.], [1.]])

        To set edge features for a graph with a single edge type, use :func:`DGLGraph.edata`.
Mufei Li's avatar
Mufei Li committed
2071
2072
2073
2074

        See Also
        --------
        edata
2075
        """
2076
        # TODO(Mufei): Replace the syntax g.edges[...].edata[...] with g.edges[...][...]
Minjie Wang's avatar
Minjie Wang committed
2077
        return HeteroEdgeView(self)
2078
2079

    @property
Minjie Wang's avatar
Minjie Wang committed
2080
    def edata(self):
2081
2082
2083
2084
2085
        """Return an edge data view for setting/getting edge features.

        Let ``g`` be a DGLGraph. If ``g`` is a graph of a single edge type, ``g.edata[feat]``
        returns the edge feature associated with the name ``feat``. One can also set an
        edge feature associated with the name ``feat`` by setting ``g.edata[feat]`` to a tensor.
2086

2087
2088
2089
2090
2091
        If ``g`` is a graph of multiple edge types, ``g.edata[feat]`` returns a
        dict[str, Tensor] mapping canonical edge types to the edge features associated with
        the name ``feat`` for the corresponding type. One can also set an edge feature
        associated with the name ``feat`` for some edge type(s) by setting
        ``g.edata[feat]`` to a dictionary as described.
2092

2093
2094
2095
2096
        Notes
        -----
        For setting features, the device of the features must be the same as the device
        of the graph.
Minjie Wang's avatar
Minjie Wang committed
2097
2098
2099

        Examples
        --------
Mufei Li's avatar
Mufei Li committed
2100
2101
        The following example uses PyTorch backend.

2102
2103
        >>> import dgl
        >>> import torch
Mufei Li's avatar
Mufei Li committed
2104

2105
        Set and get feature 'h' for a graph of a single edge type.
2106

2107
2108
        >>> g = dgl.graph((torch.tensor([0, 1]), torch.tensor([1, 2])))
        >>> g.edata['h'] = torch.ones(2, 1)
2109
        >>> g.edata['h']
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
        tensor([[1.],
                [1.]])

        Set and get feature 'h' for a graph of multiple edge types.

        >>> g = dgl.heterograph({
        ...     ('user', 'follows', 'user'): (torch.tensor([1, 2]), torch.tensor([3, 4])),
        ...     ('user', 'plays', 'user'): (torch.tensor([2, 2]), torch.tensor([1, 1])),
        ...     ('player', 'plays', 'game'): (torch.tensor([2, 2]), torch.tensor([1, 1]))
        ... })
        >>> g.edata['h'] = {('user', 'follows', 'user'): torch.zeros(2, 1),
        ...                 ('user', 'plays', 'user'): torch.ones(2, 1)}
2122
        >>> g.edata['h']
2123
2124
2125
        {('user', 'follows', 'user'): tensor([[0.], [0.]]),
         ('user', 'plays', 'user'): tensor([[1.], [1.]])}
        >>> g.edata['h'] = {('user', 'follows', 'user'): torch.ones(2, 1)}
2126
        >>> g.edata['h']
2127
2128
        {('user', 'follows', 'user'): tensor([[1.], [1.]]),
         ('user', 'plays', 'user'): tensor([[1.], [1.]])}
2129

Mufei Li's avatar
Mufei Li committed
2130
2131
2132
        See Also
        --------
        edges
2133
        """
2134
2135
2136
2137
        if len(self.canonical_etypes) == 1:
            return HeteroEdgeDataView(self, None, ALL)
        else:
            return HeteroEdgeDataView(self, self.canonical_etypes, ALL)
Minjie Wang's avatar
Minjie Wang committed
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149

    def _find_etypes(self, key):
        etypes = [
            i for i, (srctype, etype, dsttype) in enumerate(self._canonical_etypes) if
            (key[0] == SLICE_FULL or key[0] == srctype) and
            (key[1] == SLICE_FULL or key[1] == etype) and
            (key[2] == SLICE_FULL or key[2] == dsttype)]
        return etypes

    def __getitem__(self, key):
        """Return the relation slice of this graph.

2150
        You can get a relation slice with ``self[srctype, etype, dsttype]``, where
Minjie Wang's avatar
Minjie Wang committed
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
        ``srctype``, ``etype``, and ``dsttype`` can be either a string or a full
        slice (``:``) representing wildcard (i.e. any source/edge/destination type).

        A relation slice is a homogeneous (with one node type and one edge type) or
        bipartite (with two node types and one edge type) graph, transformed from
        the original heterogeneous graph.

        If there is only one canonical edge type found, then the returned relation
        slice would be a subgraph induced from the original graph.  That is, it is
        equivalent to ``self.edge_type_subgraph(etype)``.  The node and edge features
        of the returned graph would be shared with thew original graph.

2163
        If there are multiple canonical edge types found, then the source/edge/destination
Minjie Wang's avatar
Minjie Wang committed
2164
2165
2166
2167
        node types would be a *concatenation* of original node/edge types.  The
        new source/destination node type would have the concatenation determined by
        :func:`dgl.combine_names() <dgl.combine_names>` called on original source/destination
        types as its name.  The source/destination node would be formed by concatenating the
2168
        common features of the original source/destination types.  Therefore they are not
Minjie Wang's avatar
Minjie Wang committed
2169
        shared with the original graph.  Edge type is similar.
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224

        Parameters
        ----------
        key : str or tuple
            Either a string representing the edge type name, or a tuple in the form of
            ``(srctype, etype, dsttype)`` where ``srctype``, ``etype``, ``dsttype`` can be either
            strings representing type names or a full slice object (`:`).

        Returns
        -------
        DGLGraph
            The relation slice.

        Notes
        -----
        This function returns a new graph.  Changing the content of this graph does not reflect
        onto the original graph.

        If the graph combines multiple node types or edge types together, it will have the
        mapping of node/edge types and IDs from the new graph to the original graph.
        The mappings have the name ``dgl.NTYPE``, ``dgl.NID``, ``dgl.ETYPE`` and ``dgl.EID``,
        similar to the function :func:`dgl.to_homogenenous`.

        Examples
        --------
        >>> g = dgl.heterograph({
        ...     ('A1', 'AB1', 'B'): ([0, 1, 2], [1, 2, 3]),
        ...     ('A1', 'AB2', 'B'): ([1, 2, 3], [3, 4, 5]),
        ...     ('A2', 'AB2', 'B'): ([1, 3, 5], [2, 4, 6])})
        >>> new_g = g['A1', :, 'B']         # combines all edge types between A1 and B
        >>> new_g
        Graph(num_nodes={'A1': 4, 'B': 7},
              num_edges={('A1', 'AB1+AB2', 'B'): 6},
              metagraph=[('A1', 'B', 'AB1+AB2')])
        >>> new_g.edges()
        (tensor([0, 1, 2, 1, 2, 3]), tensor([1, 2, 3, 3, 4, 5]))
        >>> new_g2 = g[:, 'AB2', 'B']        # combines all node types that are source of AB2
        >>> new_g2
        Graph(num_nodes={'A1+A2': 10, 'B': 7},
              num_edges={('A1+A2', 'AB2+AB2', 'B'): 6},
              metagraph=[('A1+A2', 'B', 'AB2+AB2')])
        >>> new_g2.edges()
        (tensor([1, 2, 3, 5, 7, 9]), tensor([3, 4, 5, 2, 4, 6]))

        If a combination of multiple node types and edge types occur, one can find
        the mapping to the original node type and IDs like the following:

        >>> new_g1.edges['AB1+AB2'].data[dgl.EID]
        tensor([0, 1, 2, 0, 1, 2])
        >>> new_g1.edges['AB1+AB2'].data[dgl.ETYPE]
        tensor([0, 0, 0, 1, 1, 1])
        >>> new_g2.nodes['A1+A2'].data[dgl.NID]
        tensor([0, 1, 2, 3, 0, 1, 2, 3, 4, 5])
        >>> new_g2.nodes['A1+A2'].data[dgl.NTYPE]
        tensor([0, 0, 0, 0, 1, 1, 1, 1, 1, 1])
Minjie Wang's avatar
Minjie Wang committed
2225
2226
2227
2228
2229
        """
        err_msg = "Invalid slice syntax. Use G['etype'] or G['srctype', 'etype', 'dsttype'] " +\
                  "to get view of one relation type. Use : to slice multiple types (e.g. " +\
                  "G['srctype', :, 'dsttype'])."

2230
        orig_key = key
Minjie Wang's avatar
Minjie Wang committed
2231
2232
2233
2234
2235
2236
2237
        if not isinstance(key, tuple):
            key = (SLICE_FULL, key, SLICE_FULL)

        if len(key) != 3:
            raise DGLError(err_msg)

        etypes = self._find_etypes(key)
2238
2239
2240
2241

        if len(etypes) == 0:
            raise DGLError('Invalid key "{}". Must be one of the edge types.'.format(orig_key))

Minjie Wang's avatar
Minjie Wang committed
2242
2243
2244
        if len(etypes) == 1:
            # no ambiguity: return the unitgraph itself
            srctype, etype, dsttype = self._canonical_etypes[etypes[0]]
2245
            stid = self.get_ntype_id_from_src(srctype)
Minjie Wang's avatar
Minjie Wang committed
2246
            etid = self.get_etype_id((srctype, etype, dsttype))
2247
            dtid = self.get_ntype_id_from_dst(dsttype)
Minjie Wang's avatar
Minjie Wang committed
2248
2249
2250
2251
2252
2253
            new_g = self._graph.get_relation_graph(etid)

            if stid == dtid:
                new_ntypes = [srctype]
                new_nframes = [self._node_frames[stid]]
            else:
2254
                new_ntypes = ([srctype], [dsttype])
Minjie Wang's avatar
Minjie Wang committed
2255
2256
2257
                new_nframes = [self._node_frames[stid], self._node_frames[dtid]]
            new_etypes = [etype]
            new_eframes = [self._edge_frames[etid]]
2258

2259
            return self.__class__(new_g, new_ntypes, new_etypes, new_nframes, new_eframes)
Minjie Wang's avatar
Minjie Wang committed
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
        else:
            flat = self._graph.flatten_relations(etypes)
            new_g = flat.graph

            # merge frames
            stids = flat.induced_srctype_set.asnumpy()
            dtids = flat.induced_dsttype_set.asnumpy()
            etids = flat.induced_etype_set.asnumpy()
            new_ntypes = [combine_names(self.ntypes, stids)]
            if new_g.number_of_ntypes() == 2:
                new_ntypes.append(combine_names(self.ntypes, dtids))
                new_nframes = [
                    combine_frames(self._node_frames, stids),
                    combine_frames(self._node_frames, dtids)]
            else:
                assert np.array_equal(stids, dtids)
                new_nframes = [combine_frames(self._node_frames, stids)]
            new_etypes = [combine_names(self.etypes, etids)]
            new_eframes = [combine_frames(self._edge_frames, etids)]

            # create new heterograph
2281
            new_hg = self.__class__(new_g, new_ntypes, new_etypes, new_nframes, new_eframes)
Minjie Wang's avatar
Minjie Wang committed
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299

            src = new_ntypes[0]
            dst = new_ntypes[1] if new_g.number_of_ntypes() == 2 else src
            # put the parent node/edge type and IDs
            new_hg.nodes[src].data[NTYPE] = F.zerocopy_from_dgl_ndarray(flat.induced_srctype)
            new_hg.nodes[src].data[NID] = F.zerocopy_from_dgl_ndarray(flat.induced_srcid)
            new_hg.nodes[dst].data[NTYPE] = F.zerocopy_from_dgl_ndarray(flat.induced_dsttype)
            new_hg.nodes[dst].data[NID] = F.zerocopy_from_dgl_ndarray(flat.induced_dstid)
            new_hg.edata[ETYPE] = F.zerocopy_from_dgl_ndarray(flat.induced_etype)
            new_hg.edata[EID] = F.zerocopy_from_dgl_ndarray(flat.induced_eid)

            return new_hg

    #################################################################
    # Graph query
    #################################################################

    def number_of_nodes(self, ntype=None):
2300
        """Alias of :meth:`num_nodes`"""
2301
2302
2303
        return self.num_nodes(ntype)

    def num_nodes(self, ntype=None):
2304
        """Return the number of nodes in the graph.
Da Zheng's avatar
Da Zheng committed
2305
2306
2307

        Parameters
        ----------
Minjie Wang's avatar
Minjie Wang committed
2308
        ntype : str, optional
2309
            The node type name. If given, it returns the number of nodes of the
2310
            type. If not given (default), it returns the total number of nodes of all types.
2311
2312
2313
2314

        Returns
        -------
        int
2315
            The number of nodes.
Da Zheng's avatar
Da Zheng committed
2316
2317
2318

        Examples
        --------
Mufei Li's avatar
Mufei Li committed
2319

2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
        The following example uses PyTorch backend.

        >>> import dgl
        >>> import torch

        Create a graph with two node types -- 'user' and 'game'.

        >>> g = dgl.heterograph({
        ...     ('user', 'follows', 'user'): (torch.tensor([0, 1]), torch.tensor([1, 2])),
        ...     ('user', 'plays', 'game'): (torch.tensor([3, 4]), torch.tensor([5, 6]))
        ... })

        Query for the number of nodes.

        >>> g.num_nodes('user')
        5
        >>> g.num_nodes('game')
        7
        >>> g.num_nodes()
        12
Da Zheng's avatar
Da Zheng committed
2340
        """
2341
2342
2343
2344
        if ntype is None:
            return sum([self._graph.number_of_nodes(ntid) for ntid in range(len(self.ntypes))])
        else:
            return self._graph.number_of_nodes(self.get_ntype_id(ntype))
2345

2346
    def number_of_src_nodes(self, ntype=None):
2347
        """Alias of :meth:`num_src_nodes`"""
2348
        return self.num_src_nodes(ntype)
2349

2350
    def num_src_nodes(self, ntype=None):
2351
2352
2353
2354
2355
2356
2357
2358
        """Return the number of source nodes in the graph.

        If the graph can further divide its node types into two subsets A and B where
        all the edeges are from nodes of types in A to nodes of types in B, we call
        this graph a *uni-bipartite* graph and the nodes in A being the *source*
        nodes and the ones in B being the *destination* nodes. If the graph is not
        uni-bipartite, the source and destination nodes are just the entire set of
        nodes in the graph.
2359
2360
2361
2362

        Parameters
        ----------
        ntype : str, optional
2363
2364
            The source node type name. If given, it returns the number of nodes for
            the source node type. If not given (default), it returns the number of
2365
            nodes summed over all source node types.
2366
2367
2368
2369
2370
2371

        Returns
        -------
        int
            The number of nodes

2372
2373
2374
2375
2376
        See Also
        --------
        num_dst_nodes
        is_unibipartite

2377
2378
        Examples
        --------
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
        The following example uses PyTorch backend.

        >>> import dgl
        >>> import torch

        Create a homogeneous graph for query.

        >>> g = dgl.graph((torch.tensor([0, 1]), torch.tensor([1, 2])))
        >>> g.num_src_nodes()
        3

        Create a heterogeneous graph with two source node types -- 'developer' and 'user'.

        >>> g = dgl.heterograph({
        ...     ('developer', 'develops', 'game'): (torch.tensor([0, 1]), torch.tensor([1, 2])),
        ...     ('user', 'plays', 'game'): (torch.tensor([3, 4]), torch.tensor([5, 6]))
        ... })

        Query for the number of nodes.

        >>> g.num_src_nodes('developer')
2400
        2
2401
2402
2403
2404
        >>> g.num_src_nodes('user')
        5
        >>> g.num_src_nodes()
        7
2405
        """
2406
2407
2408
2409
2410
        if ntype is None:
            return sum([self._graph.number_of_nodes(self.get_ntype_id_from_src(nty))
                        for nty in self.srctypes])
        else:
            return self._graph.number_of_nodes(self.get_ntype_id_from_src(ntype))
2411
2412

    def number_of_dst_nodes(self, ntype=None):
2413
2414
        """Alias of :func:`num_dst_nodes`"""
        return self.num_dst_nodes(ntype)
2415

2416
    def num_dst_nodes(self, ntype=None):
2417
2418
2419
2420
2421
2422
2423
2424
        """Return the number of destination nodes in the graph.

        If the graph can further divide its node types into two subsets A and B where
        all the edeges are from nodes of types in A to nodes of types in B, we call
        this graph a *uni-bipartite* graph and the nodes in A being the *source*
        nodes and the ones in B being the *destination* nodes. If the graph is not
        uni-bipartite, the source and destination nodes are just the entire set of
        nodes in the graph.
2425
2426
2427
2428

        Parameters
        ----------
        ntype : str, optional
2429
2430
2431
            The destination node type name. If given, it returns the number of nodes of
            the destination node type. If not given (default), it returns the number of
            nodes summed over all the destination node types.
2432
2433
2434
2435
2436
2437

        Returns
        -------
        int
            The number of nodes

2438
2439
2440
2441
2442
        See Also
        --------
        num_src_nodes
        is_unibipartite

2443
2444
        Examples
        --------
2445
2446
2447
2448
2449
2450
2451
2452
2453
        The following example uses PyTorch backend.

        >>> import dgl
        >>> import torch

        Create a homogeneous graph for query.

        >>> g = dgl.graph((torch.tensor([0, 1]), torch.tensor([1, 2])))
        >>> g.num_dst_nodes()
2454
        3
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470

        Create a heterogeneous graph with two destination node types -- 'user' and 'game'.

        >>> g = dgl.heterograph({
        ...     ('user', 'follows', 'user'): (torch.tensor([0, 1]), torch.tensor([1, 2])),
        ...     ('user', 'plays', 'game'): (torch.tensor([3, 4]), torch.tensor([5, 6]))
        ... })

        Query for the number of nodes.

        >>> g.num_dst_nodes('user')
        5
        >>> g.num_dst_nodes('game')
        7
        >>> g.num_dst_nodes()
        12
2471
        """
2472
2473
2474
2475
2476
        if ntype is None:
            return sum([self._graph.number_of_nodes(self.get_ntype_id_from_dst(nty))
                        for nty in self.dsttypes])
        else:
            return self._graph.number_of_nodes(self.get_ntype_id_from_dst(ntype))
2477

Minjie Wang's avatar
Minjie Wang committed
2478
    def number_of_edges(self, etype=None):
2479
2480
2481
2482
        """Alias of :func:`num_edges`"""
        return self.num_edges(etype)

    def num_edges(self, etype=None):
2483
        """Return the number of edges in the graph.
2484
2485
2486

        Parameters
        ----------
2487
2488
2489
2490
2491
2492
2493
2494
2495
        etype : str or (str, str, str), optional
            The type name of the edges. The allowed type name formats are:

            * ``(str, str, str)`` for source node type, edge type and destination node type.
            * or one ``str`` edge type name if the name can uniquely identify a
              triplet format in the graph.

            If not provided, return the total number of edges regardless of the types
            in the graph.
Da Zheng's avatar
Da Zheng committed
2496
2497
2498
2499

        Returns
        -------
        int
2500
            The number of edges.
Da Zheng's avatar
Da Zheng committed
2501

2502
2503
        Examples
        --------
Mufei Li's avatar
Mufei Li committed
2504

2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
        The following example uses PyTorch backend.

        >>> import dgl
        >>> import torch

        Create a graph with three canonical edge types.

        >>> g = dgl.heterograph({
        ...     ('user', 'follows', 'user'): (torch.tensor([0, 1]), torch.tensor([1, 2])),
        ...     ('user', 'follows', 'game'): (torch.tensor([0, 1, 2]), torch.tensor([1, 2, 3])),
        ...     ('user', 'plays', 'game'): (torch.tensor([1, 3]), torch.tensor([2, 3]))
        ... })

        Query for the number of edges.

        >>> g.num_edges('plays')
Mufei Li's avatar
Mufei Li committed
2521
        2
2522
2523
2524
2525
2526
2527
        >>> g.num_edges()
        7

        Use a canonical edge type instead when there is ambiguity for an edge type.

        >>> g.num_edges(('user', 'follows', 'user'))
Mufei Li's avatar
Mufei Li committed
2528
        2
2529
2530
        >>> g.num_edges(('user', 'follows', 'game'))
        3
2531
        """
2532
2533
2534
2535
2536
        if etype is None:
            return sum([self._graph.number_of_edges(etid)
                        for etid in range(len(self.canonical_etypes))])
        else:
            return self._graph.number_of_edges(self.get_etype_id(etype))
Minjie Wang's avatar
Minjie Wang committed
2537
2538
2539

    @property
    def is_multigraph(self):
2540
        """Return whether the graph is a multigraph with parallel edges.
Mufei Li's avatar
Mufei Li committed
2541

2542
2543
2544
2545
        A multigraph has more than one edges between the same pair of nodes, called
        *parallel edges*.  For heterogeneous graphs, parallel edge further requires
        the canonical edge type to be the same (see :meth:`canonical_etypes` for the
        definition).
2546

Mufei Li's avatar
Mufei Li committed
2547
2548
2549
        Returns
        -------
        bool
2550
            True if the graph is a multigraph.
2551
2552
2553

        Notes
        -----
2554
        Checking whether the graph is a multigraph could be expensive for a large one.
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586

        Examples
        --------

        The following example uses PyTorch backend.

        >>> import dgl
        >>> import torch

        Check for homogeneous graphs.

        >>> g = dgl.graph((torch.tensor([0, 1]), torch.tensor([1, 3])))
        >>> g.is_multigraph
        False
        >>> g = dgl.graph((torch.tensor([0, 1, 1]), torch.tensor([1, 3, 3])))
        >>> g.is_multigraph
        True

        Check for heterogeneous graphs.

        >>> g = dgl.heterograph({
        ...     ('user', 'follows', 'user'): (torch.tensor([0, 1]), torch.tensor([1, 2])),
        ...     ('user', 'follows', 'game'): (torch.tensor([0, 1, 2]), torch.tensor([1, 2, 3]))
        ... })
        >>> g.is_multigraph
        False
        >>> g = dgl.heterograph({
        ...     ('user', 'follows', 'user'): (torch.tensor([0, 1, 1]), torch.tensor([1, 2, 2])),
        ...     ('user', 'follows', 'game'): (torch.tensor([0, 1, 2]), torch.tensor([1, 2, 3]))
        ... })
        >>> g.is_multigraph
        True
Mufei Li's avatar
Mufei Li committed
2587
        """
2588
        return self._graph.is_multigraph()
Minjie Wang's avatar
Minjie Wang committed
2589

2590
2591
    @property
    def is_homogeneous(self):
2592
        """Return whether the graph is a homogeneous graph.
2593
2594
2595
2596
2597
2598

        A homogeneous graph only has one node type and one edge type.

        Returns
        -------
        bool
2599
            True if the graph is a homogeneous graph.
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625

        Examples
        --------

        The following example uses PyTorch backend.

        >>> import dgl
        >>> import torch

        Create a homogeneous graph for check.

        >>> g = dgl.graph((torch.tensor([0, 0, 1, 1]), torch.tensor([1, 0, 2, 3])))
        >>> g.is_homogeneous
        True

        Create a heterogeneous graph for check.

        If the graph has multiple edge types, one need to specify the edge type.

        >>> g = dgl.heterograph({
        ...     ('user', 'follows', 'game'): (torch.tensor([0, 1, 2]), torch.tensor([1, 2, 3]))})
        >>> g.is_homogeneous
        False
        """
        return len(self.ntypes) == 1 and len(self.etypes) == 1

Minjie Wang's avatar
Minjie Wang committed
2626
2627
    @property
    def is_readonly(self):
2628
        """**DEPRECATED**: DGLGraph will always be mutable.
Mufei Li's avatar
Mufei Li committed
2629
2630
2631
2632
2633
2634

        Returns
        -------
        bool
            True if the graph is readonly, False otherwise.
        """
2635
2636
2637
2638
        dgl_warning('DGLGraph.is_readonly is deprecated in v0.5.\n'
                    'DGLGraph now always supports mutable operations like add_nodes'
                    ' and add_edges.')
        return False
Da Zheng's avatar
Da Zheng committed
2639

2640
2641
    @property
    def idtype(self):
2642
2643
        """The data type for storing the structure-related graph information
        such as node and edge IDs.
2644
2645
2646

        Returns
        -------
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
        Framework-specific device object
            For example, this can be ``torch.int32`` or ``torch.int64`` for PyTorch.

        Examples
        --------

        The following example uses PyTorch backend.

        >>> import dgl
        >>> import torch

        >>> src_ids = torch.tensor([0, 0, 1])
        >>> dst_ids = torch.tensor([1, 2, 2])
        >>> g = dgl.graph((src_ids, dst_ids))
        >>> g.idtype
        torch.int64
        >>> g = dgl.graph((src_ids, dst_ids), idtype=torch.int32)
        >>> g.idtype
        torch.int32
2666
2667
2668
2669
2670

        See Also
        --------
        long
        int
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
        """
        return getattr(F, self._graph.dtype)

    @property
    def _idtype_str(self):
        """The dtype of graph index

        Returns
        -------
        backend dtype object
            th.int32/th.int64 or tf.int32/tf.int64 etc.
        """
        return self._graph.dtype

2685
    def __contains__(self, vid):
2686
        """**DEPRECATED**: please directly call :func:`has_nodes`."""
2687
2688
2689
2690
2691
        dgl_warning('DGLGraph.__contains__ is deprecated.'
                    ' Please directly call has_nodes.')
        return self.has_nodes(vid)

    def has_nodes(self, vid, ntype=None):
2692
        """Return whether the graph contains the given nodes.
Da Zheng's avatar
Da Zheng committed
2693
2694
2695

        Parameters
        ----------
2696
        vid : node ID(s)
2697
2698
2699
2700
2701
2702
            The nodes IDs. The allowed nodes ID formats are:

            * ``int``: The ID of a single node.
            * Int Tensor: Each element is a node ID. The tensor must have the same device type
              and ID data type as the graph's.
            * iterable[int]: Each element is a node ID.
2703

Minjie Wang's avatar
Minjie Wang committed
2704
        ntype : str, optional
2705
2706
            The node type name. Can be omitted if there is
            only one type of nodes in the graph.
Da Zheng's avatar
Da Zheng committed
2707
2708
2709

        Returns
        -------
2710
        bool or bool Tensor
2711
2712
            A tensor of bool flags where each element is True if the node is in the graph.
            If the input is a single node, return one bool value.
Da Zheng's avatar
Da Zheng committed
2713
2714
2715

        Examples
        --------
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730

        The following example uses PyTorch backend.

        >>> import dgl
        >>> import torch

        Create a graph with two node types -- 'user' and 'game'.

        >>> g = dgl.heterograph({
        ...     ('user', 'follows', 'user'): (torch.tensor([0, 1]), torch.tensor([1, 2])),
        ...     ('user', 'plays', 'game'): (torch.tensor([3, 4]), torch.tensor([0, 1]))
        ... })

        Query for the nodes.

2731
        >>> g.has_nodes(0, 'user')
Da Zheng's avatar
Da Zheng committed
2732
        True
2733
        >>> g.has_nodes(3, 'game')
Da Zheng's avatar
Da Zheng committed
2734
        False
2735
2736
        >>> g.has_nodes(torch.tensor([3, 0, 1]), 'game')
        tensor([False,  True,  True])
Da Zheng's avatar
Da Zheng committed
2737
        """
2738
2739
2740
        vid_tensor = utils.prepare_tensor(self, vid, "vid")
        if len(vid_tensor) > 0 and F.as_scalar(F.min(vid_tensor, 0)) < 0 < len(vid_tensor):
            raise DGLError('All IDs must be non-negative integers.')
2741
        ret = self._graph.has_nodes(
2742
            self.get_ntype_id(ntype), vid_tensor)
2743
2744
2745
2746
        if isinstance(vid, numbers.Integral):
            return bool(F.as_scalar(ret))
        else:
            return F.astype(ret, F.bool)
Da Zheng's avatar
Da Zheng committed
2747

2748
    def has_node(self, vid, ntype=None):
2749
        """Whether the graph has a particular node of a given type.
Da Zheng's avatar
Da Zheng committed
2750

2751
        **DEPRECATED**: see :func:`~DGLGraph.has_nodes`
Da Zheng's avatar
Da Zheng committed
2752
        """
2753
2754
        dgl_warning("DGLGraph.has_node is deprecated. Please use DGLGraph.has_nodes")
        return self.has_nodes(vid, ntype)
Da Zheng's avatar
Da Zheng committed
2755

2756
    def has_edges_between(self, u, v, etype=None):
2757
        """Return whether the graph contains the given edges.
Da Zheng's avatar
Da Zheng committed
2758
2759
2760

        Parameters
        ----------
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
        u : node IDs
            The source node IDs of the edges. The allowed formats are:

            * ``int``: A single node.
            * Int Tensor: Each element is a node ID. The tensor must have the same device type
              and ID data type as the graph's.
            * iterable[int]: Each element is a node ID.

        v : node IDs
            The destination node IDs of the edges. The allowed formats are:

            * ``int``: A single node.
            * Int Tensor: Each element is a node ID. The tensor must have the same device type
              and ID data type as the graph's.
            * iterable[int]: Each element is a node ID.

        etype : str or (str, str, str), optional
            The type names of the edges. The allowed type name formats are:

            * ``(str, str, str)`` for source node type, edge type and destination node type.
            * or one ``str`` edge type name if the name can uniquely identify a
              triplet format in the graph.

            Can be omitted if the graph has only one type of edges.

Da Zheng's avatar
Da Zheng committed
2786
2787
2788

        Returns
        -------
2789
        bool or bool Tensor
2790
2791
            A tensor of bool flags where each element is True if the node is in the graph.
            If the input is a single node, return one bool value.
Da Zheng's avatar
Da Zheng committed
2792
2793
2794

        Examples
        --------
Mufei Li's avatar
Mufei Li committed
2795

2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
        The following example uses PyTorch backend.

        >>> import dgl
        >>> import torch

        Create a homogeneous graph.

        >>> g = dgl.graph((torch.tensor([0, 0, 1, 1]), torch.tensor([1, 0, 2, 3])))

        Query for the edges.

        >>> g.has_edges_between(1, 2)
Da Zheng's avatar
Da Zheng committed
2808
        True
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
        >>> g.has_edges_between(torch.tensor([1, 2]), torch.tensor([2, 3]))
        tensor([ True, False])

        If the graph has multiple edge types, one need to specify the edge type.

        >>> g = dgl.heterograph({
        ...     ('user', 'follows', 'user'): (torch.tensor([0, 1]), torch.tensor([1, 2])),
        ...     ('user', 'follows', 'game'): (torch.tensor([0, 1, 2]), torch.tensor([1, 2, 3])),
        ...     ('user', 'plays', 'game'): (torch.tensor([1, 3]), torch.tensor([2, 3]))
        ... })
        >>> g.has_edges_between(torch.tensor([1, 2]), torch.tensor([2, 3]), 'plays')
        tensor([ True, False])

        Use a canonical edge type instead when there is ambiguity for an edge type.

        >>> g.has_edges_between(torch.tensor([1, 2]), torch.tensor([2, 3]),
        ...                     ('user', 'follows', 'user'))
        tensor([ True, False])
        >>> g.has_edges_between(torch.tensor([1, 2]), torch.tensor([2, 3]),
        ...                     ('user', 'follows', 'game'))
        tensor([True, True])
Da Zheng's avatar
Da Zheng committed
2830
        """
2831
2832
2833
2834
2835
2836
2837
        srctype, _, dsttype = self.to_canonical_etype(etype)
        u_tensor = utils.prepare_tensor(self, u, 'u')
        if F.as_scalar(F.sum(self.has_nodes(u_tensor, ntype=srctype), dim=0)) != len(u_tensor):
            raise DGLError('u contains invalid node IDs')
        v_tensor = utils.prepare_tensor(self, v, 'v')
        if F.as_scalar(F.sum(self.has_nodes(v_tensor, ntype=dsttype), dim=0)) != len(v_tensor):
            raise DGLError('v contains invalid node IDs')
2838
2839
        ret = self._graph.has_edges_between(
            self.get_etype_id(etype),
2840
            u_tensor, v_tensor)
2841
2842
2843
2844
        if isinstance(u, numbers.Integral) and isinstance(v, numbers.Integral):
            return bool(F.as_scalar(ret))
        else:
            return F.astype(ret, F.bool)
Da Zheng's avatar
Da Zheng committed
2845

2846
    def has_edge_between(self, u, v, etype=None):
Mufei Li's avatar
Mufei Li committed
2847
        """Whether the graph has edges of type ``etype``.
Da Zheng's avatar
Da Zheng committed
2848

2849
        **DEPRECATED**: please use :func:`~DGLGraph.has_edge_between`.
Da Zheng's avatar
Da Zheng committed
2850
        """
2851
2852
2853
        dgl_warning("DGLGraph.has_edge_between is deprecated. "
                    "Please use DGLGraph.has_edges_between")
        return self.has_edges_between(u, v, etype)
Da Zheng's avatar
Da Zheng committed
2854

Minjie Wang's avatar
Minjie Wang committed
2855
    def predecessors(self, v, etype=None):
2856
        """Return the predecessor(s) of a particular node with the specified edge type.
Da Zheng's avatar
Da Zheng committed
2857

2858
2859
        Node ``u`` is a predecessor of node ``v`` if there is an edge ``(u, v)`` with type
        ``etype`` in the graph.
Da Zheng's avatar
Da Zheng committed
2860
2861
2862
2863

        Parameters
        ----------
        v : int
2864
2865
            The node ID. If the graph has multiple edge types, the ID is for the destination
            type corresponding to the edge type.
2866
2867
2868
2869
2870
2871
2872
2873
2874
        etype : str or (str, str, str), optional
            The type names of the edges. The allowed type name formats are:

            * ``(str, str, str)`` for source node type, edge type and destination node type.
            * or one ``str`` edge type name if the name can uniquely identify a
              triplet format in the graph.

            Can be omitted if the graph has only one type of edges.

Da Zheng's avatar
Da Zheng committed
2875
2876
2877

        Returns
        -------
2878
2879
        Tensor
            The predecessors of :attr:`v` with the specified edge type.
Da Zheng's avatar
Da Zheng committed
2880
2881
2882
2883
2884

        Examples
        --------
        The following example uses PyTorch backend.

2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
        >>> import dgl
        >>> import torch

        Create a homogeneous graph.

        >>> g = dgl.graph((torch.tensor([0, 0, 1, 1]), torch.tensor([1, 1, 2, 3])))

        Query for node 1.

        >>> g.predecessors(1)
        tensor([0, 0])

        For a graph of multiple edge types, it is required to specify the edge type in query.

        >>> hg = dgl.heterograph({
        ...     ('user', 'follows', 'user'): (torch.tensor([0, 1]), torch.tensor([1, 2])),
        ...     ('user', 'plays', 'game'): (torch.tensor([3, 4]), torch.tensor([5, 6]))
        ... })
        >>> hg.predecessors(1, etype='follows')
Mufei Li's avatar
Mufei Li committed
2904
        tensor([0])
Da Zheng's avatar
Da Zheng committed
2905
2906
2907
2908
2909

        See Also
        --------
        successors
        """
2910
2911
        if not self.has_nodes(v, self.to_canonical_etype(etype)[-1]):
            raise DGLError('Non-existing node ID {}'.format(v))
2912
        return self._graph.predecessors(self.get_etype_id(etype), v)
Da Zheng's avatar
Da Zheng committed
2913

Minjie Wang's avatar
Minjie Wang committed
2914
    def successors(self, v, etype=None):
2915
        """Return the successor(s) of a particular node with the specified edge type.
Da Zheng's avatar
Da Zheng committed
2916

2917
2918
        Node ``u`` is a successor of node ``v`` if there is an edge ``(v, u)`` with type
        ``etype`` in the graph.
Da Zheng's avatar
Da Zheng committed
2919
2920
2921
2922

        Parameters
        ----------
        v : int
2923
2924
            The node ID. If the graph has multiple edge types, the ID is for the source
            type corresponding to the edge type.
2925
2926
2927
2928
2929
2930
2931
2932
        etype : str or (str, str, str), optional
            The type names of the edges. The allowed type name formats are:

            * ``(str, str, str)`` for source node type, edge type and destination node type.
            * or one ``str`` edge type name if the name can uniquely identify a
              triplet format in the graph.

            Can be omitted if the graph has only one type of edges.
Da Zheng's avatar
Da Zheng committed
2933
2934
2935

        Returns
        -------
2936
2937
        Tensor
            The successors of :attr:`v` with the specified edge type.
Da Zheng's avatar
Da Zheng committed
2938
2939
2940
2941
2942

        Examples
        --------
        The following example uses PyTorch backend.

2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
        >>> import dgl
        >>> import torch

        Create a homogeneous graph.

        >>> g = dgl.graph((torch.tensor([0, 0, 1, 1]), torch.tensor([1, 1, 2, 3])))

        Query for node 1.

        >>> g.successors(1)
        tensor([2, 3])

        For a graph of multiple edge types, it is required to specify the edge type in query.

        >>> hg = dgl.heterograph({
        ...     ('user', 'follows', 'user'): (torch.tensor([0, 1]), torch.tensor([1, 2])),
        ...     ('user', 'plays', 'game'): (torch.tensor([3, 4]), torch.tensor([5, 6]))
        ... })
        >>> hg.successors(1, etype='follows')
        tensor([2])
Da Zheng's avatar
Da Zheng committed
2963
2964
2965
2966
2967

        See Also
        --------
        predecessors
        """
2968
2969
        if not self.has_nodes(v, self.to_canonical_etype(etype)[0]):
            raise DGLError('Non-existing node ID {}'.format(v))
2970
        return self._graph.successors(self.get_etype_id(etype), v)
Da Zheng's avatar
Da Zheng committed
2971

2972
    def edge_id(self, u, v, force_multi=None, return_uv=False, etype=None):
Da Zheng's avatar
Da Zheng committed
2973
        """Return the edge ID, or an array of edge IDs, between source node
Mufei Li's avatar
Mufei Li committed
2974
        `u` and destination node `v`, with the specified edge type
Da Zheng's avatar
Da Zheng committed
2975

2976
2977
2978
2979
2980
2981
2982
        **DEPRECATED**: See edge_ids
        """
        dgl_warning("DGLGraph.edge_id is deprecated. Please use DGLGraph.edge_ids.")
        return self.edge_ids(u, v, force_multi=force_multi,
                             return_uv=return_uv, etype=etype)

    def edge_ids(self, u, v, force_multi=None, return_uv=False, etype=None):
2983
        """Return the edge ID(s) given the two endpoints of the edge(s).
2984

Da Zheng's avatar
Da Zheng committed
2985
2986
        Parameters
        ----------
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
        u : node IDs
            The source node IDs of the edges. The allowed formats are:

            * ``int``: A single node.
            * Int Tensor: Each element is a node ID. The tensor must have the same device type
              and ID data type as the graph's.
            * iterable[int]: Each element is a node ID.

        v : node IDs
            The destination node IDs of the edges. The allowed formats are:

            * ``int``: A single node.
            * Int Tensor: Each element is a node ID. The tensor must have the same device type
              and ID data type as the graph's.
            * iterable[int]: Each element is a node ID.
Minjie Wang's avatar
Minjie Wang committed
3002
        force_multi : bool, optional
3003
            **DEPRECATED**, use :attr:`return_uv` instead. Whether to allow the graph to be a
3004
3005
3006
3007
3008
3009
            multigraph, i.e. there can be multiple edges from one node to another.
        return_uv : bool, optional
            Whether to return the source and destination node IDs along with the edges. If
            False (default), it assumes that the graph is a simple graph and there is only
            one edge from one node to another. If True, there can be multiple edges found
            from one node to another.
3010
3011
3012
3013
3014
3015
3016
3017
        etype : str or (str, str, str), optional
            The type names of the edges. The allowed type name formats are:

            * ``(str, str, str)`` for source node type, edge type and destination node type.
            * or one ``str`` edge type name if the name can uniquely identify a
              triplet format in the graph.

            Can be omitted if the graph has only one type of edges.
Da Zheng's avatar
Da Zheng committed
3018
3019
3020

        Returns
        -------
3021
        Tensor, or (Tensor, Tensor, Tensor)
Mufei Li's avatar
Mufei Li committed
3022

3023
3024
            * If ``return_uv=False``, it returns the edge IDs in a tensor, where the i-th
              element is the ID of the edge ``(u[i], v[i])``.
3025
3026
            * If ``return_uv=True``, it returns a tuple of three 1D tensors ``(eu, ev, e)``.
              ``e[i]`` is the ID of an edge from ``eu[i]`` to ``ev[i]``. It returns all edges
3027
              (including parallel edges) from ``eu[i]`` to ``ev[i]`` in this case.
Da Zheng's avatar
Da Zheng committed
3028
3029
3030

        Notes
        -----
3031
3032
        If the graph is a simple graph, ``return_uv=False``, and there are no edges
        between some pairs of node(s), it will raise an error.
Da Zheng's avatar
Da Zheng committed
3033

3034
3035
        If the graph is a multigraph, ``return_uv=False``, and there are multiple edges
        between some pairs of node(s), it returns an arbitrary one from them.
3036

Da Zheng's avatar
Da Zheng committed
3037
3038
3039
3040
        Examples
        --------
        The following example uses PyTorch backend.

3041
3042
        >>> import dgl
        >>> import torch
Mufei Li's avatar
Mufei Li committed
3043

3044
        Create a homogeneous graph.
Mufei Li's avatar
Mufei Li committed
3045

3046
        >>> g = dgl.graph((torch.tensor([0, 0, 1, 1, 1]), torch.tensor([1, 0, 2, 3, 2])))
Mufei Li's avatar
Mufei Li committed
3047

3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
        Query for the edges.

        >>> g.edge_ids(0, 0)
        1
        >>> g.edge_ids(torch.tensor([1, 0]), torch.tensor([3, 1]))
        tensor([3, 0])

        Get all edges for pairs of nodes.

        >>> g.edge_ids(torch.tensor([1, 0]), torch.tensor([3, 1]), return_uv=True)
        (tensor([1, 0]), tensor([3, 1]), tensor([3, 0]))

        If the graph has multiple edge types, one need to specify the edge type.

        >>> g = dgl.heterograph({
        ...     ('user', 'follows', 'user'): (torch.tensor([0, 1]), torch.tensor([1, 2])),
        ...     ('user', 'follows', 'game'): (torch.tensor([0, 1, 2]), torch.tensor([1, 2, 3])),
        ...     ('user', 'plays', 'game'): (torch.tensor([1, 3]), torch.tensor([2, 3]))
        ... })
        >>> g.edge_ids(torch.tensor([1]), torch.tensor([2]), etype='plays')
        tensor([0])

        Use a canonical edge type instead when there is ambiguity for an edge type.

        >>> g.edge_ids(torch.tensor([0, 1]), torch.tensor([1, 2]),
        ...            etype=('user', 'follows', 'user'))
        tensor([0, 1])
        >>> g.edge_ids(torch.tensor([1, 2]), torch.tensor([2, 3]),
        ...            etype=('user', 'follows', 'game'))
        tensor([1, 2])
Da Zheng's avatar
Da Zheng committed
3078
        """
3079
        is_int = isinstance(u, numbers.Integral) and isinstance(v, numbers.Integral)
3080
        srctype, _, dsttype = self.to_canonical_etype(etype)
3081
        u = utils.prepare_tensor(self, u, 'u')
3082
3083
        if F.as_scalar(F.sum(self.has_nodes(u, ntype=srctype), dim=0)) != len(u):
            raise DGLError('u contains invalid node IDs')
3084
        v = utils.prepare_tensor(self, v, 'v')
3085
3086
        if F.as_scalar(F.sum(self.has_nodes(v, ntype=dsttype), dim=0)) != len(v):
            raise DGLError('v contains invalid node IDs')
3087
3088
3089
3090
3091
3092
        if force_multi is not None:
            dgl_warning("force_multi will be deprecated, " \
                        "Please use return_uv instead")
            return_uv = force_multi

        if return_uv:
3093
            return self._graph.edge_ids_all(self.get_etype_id(etype), u, v)
3094
        else:
3095
3096
3097
3098
3099
3100
3101
3102
3103
            eid = self._graph.edge_ids_one(self.get_etype_id(etype), u, v)
            is_neg_one = F.equal(eid, -1)
            if F.as_scalar(F.sum(is_neg_one, 0)):
                # Raise error since some (u, v) pair is not a valid edge.
                idx = F.nonzero_1d(is_neg_one)
                raise DGLError("Error: (%d, %d) does not form a valid edge." % (
                    F.as_scalar(F.gather_row(u, idx)),
                    F.as_scalar(F.gather_row(v, idx))))
            return F.as_scalar(eid) if is_int else eid
Da Zheng's avatar
Da Zheng committed
3104

Minjie Wang's avatar
Minjie Wang committed
3105
    def find_edges(self, eid, etype=None):
3106
        """Return the source and destination node ID(s) given the edge ID(s).
Da Zheng's avatar
Da Zheng committed
3107
3108
3109

        Parameters
        ----------
3110
        eid : edge ID(s)
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
            The edge IDs. The allowed formats are:

            * ``int``: A single ID.
            * Int Tensor: Each element is an ID. The tensor must have the same device type
              and ID data type as the graph's.
            * iterable[int]: Each element is an ID.

        etype : str or (str, str, str), optional
            The type names of the edges. The allowed type name formats are:

            * ``(str, str, str)`` for source node type, edge type and destination node type.
            * or one ``str`` edge type name if the name can uniquely identify a
              triplet format in the graph.

            Can be omitted if the graph has only one type of edges.
Da Zheng's avatar
Da Zheng committed
3126
3127
3128

        Returns
        -------
3129
        Tensor
3130
3131
            The source node IDs of the edges. The i-th element is the source node ID of
            the i-th edge.
3132
        Tensor
3133
3134
            The destination node IDs of the edges. The i-th element is the destination node
            ID of the i-th edge.
Da Zheng's avatar
Da Zheng committed
3135
3136
3137
3138
3139

        Examples
        --------
        The following example uses PyTorch backend.

3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
        >>> import dgl
        >>> import torch

        Create a homogeneous graph.

        >>> g = dgl.graph((torch.tensor([0, 0, 1, 1]), torch.tensor([1, 0, 2, 3])))

        Find edges of IDs 0 and 2.

        >>> g.find_edges(torch.tensor([0, 2]))
        (tensor([0, 1]), tensor([1, 2]))

        For a graph of multiple edge types, it is required to specify the edge type in query.

        >>> hg = dgl.heterograph({
        ...     ('user', 'follows', 'user'): (torch.tensor([0, 1]), torch.tensor([1, 2])),
        ...     ('user', 'plays', 'game'): (torch.tensor([3, 4]), torch.tensor([5, 6]))
        ... })
        >>> hg.find_edges(torch.tensor([1, 0]), 'plays')
        (tensor([4, 3]), tensor([6, 5]))
Da Zheng's avatar
Da Zheng committed
3160
        """
3161
        eid = utils.prepare_tensor(self, eid, 'eid')
3162
3163
3164
3165
3166
3167
3168
3169
        if len(eid) > 0:
            min_eid = F.as_scalar(F.min(eid, 0))
            if min_eid < 0:
                raise DGLError('Invalid edge ID {:d}'.format(min_eid))
            max_eid = F.as_scalar(F.max(eid, 0))
            if max_eid >= self.num_edges(etype):
                raise DGLError('Invalid edge ID {:d}'.format(max_eid))

3170
        if len(eid) == 0:
3171
3172
            empty = F.copy_to(F.tensor([], self.idtype), self.device)
            return empty, empty
Minjie Wang's avatar
Minjie Wang committed
3173
        src, dst, _ = self._graph.find_edges(self.get_etype_id(etype), eid)
3174
        return src, dst
Da Zheng's avatar
Da Zheng committed
3175

Minjie Wang's avatar
Minjie Wang committed
3176
    def in_edges(self, v, form='uv', etype=None):
3177
        """Return the incoming edges of the given nodes.
Da Zheng's avatar
Da Zheng committed
3178
3179
3180

        Parameters
        ----------
3181
3182
        v : node ID(s)
            The node IDs. The allowed formats are:
3183

3184
3185
3186
3187
            * ``int``: A single node.
            * Int Tensor: Each element is a node ID. The tensor must have the same device type
              and ID data type as the graph's.
            * iterable[int]: Each element is a node ID.
Da Zheng's avatar
Da Zheng committed
3188
        form : str, optional
3189
            The result format, which can be one of the following:
3190
3191
3192
3193
3194
3195
3196
3197
3198

            - ``'eid'``: The returned result is a 1D tensor :math:`EID`, representing
              the IDs of all edges.
            - ``'uv'`` (default): The returned result is a 2-tuple of 1D tensors :math:`(U, V)`,
              representing the source and destination nodes of all edges. For each :math:`i`,
              :math:`(U[i], V[i])` forms an edge.
            - ``'all'``: The returned result is a 3-tuple of 1D tensors :math:`(U, V, EID)`,
              representing the source nodes, destination nodes and IDs of all edges.
              For each :math:`i`, :math:`(U[i], V[i])` forms an edge with ID :math:`EID[i]`.
3199
3200
3201
3202
3203
3204
3205
3206
        etype : str or (str, str, str), optional
            The type names of the edges. The allowed type name formats are:

            * ``(str, str, str)`` for source node type, edge type and destination node type.
            * or one ``str`` edge type name if the name can uniquely identify a
              triplet format in the graph.

            Can be omitted if the graph has only one type of edges.
Da Zheng's avatar
Da Zheng committed
3207
3208
3209

        Returns
        -------
3210
3211
3212
        Tensor or (Tensor, Tensor) or (Tensor, Tensor, Tensor)
            All incoming edges of the nodes with the specified type. For a description of the
            returned result, see the description of :attr:`form`.
Da Zheng's avatar
Da Zheng committed
3213
3214
3215
3216
3217

        Examples
        --------
        The following example uses PyTorch backend.

3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
        >>> import dgl
        >>> import torch

        Create a homogeneous graph.

        >>> g = dgl.graph((torch.tensor([0, 0, 1, 1]), torch.tensor([1, 0, 2, 3])))

        Query for the nodes 1 and 0.

        >>> g.in_edges(torch.tensor([1, 0]))
        (tensor([0, 0]), tensor([1, 0]))

        Specify a different value for :attr:`form`.

        >>> g.in_edges(torch.tensor([1, 0]), form='all')
        (tensor([0, 0]), tensor([1, 0]), tensor([0, 1]))

        For a graph of multiple edge types, it is required to specify the edge type in query.

        >>> hg = dgl.heterograph({
        ...     ('user', 'follows', 'user'): (torch.tensor([0, 1]), torch.tensor([1, 2])),
        ...     ('user', 'plays', 'game'): (torch.tensor([3, 4]), torch.tensor([5, 6]))
        ... })
        >>> hg.in_edges(torch.tensor([1, 0]), etype='follows')
        (tensor([0]), tensor([1]))

        See Also
        --------
        edges
        out_edges
Da Zheng's avatar
Da Zheng committed
3248
        """
3249
        v = utils.prepare_tensor(self, v, 'v')
Minjie Wang's avatar
Minjie Wang committed
3250
        src, dst, eid = self._graph.in_edges(self.get_etype_id(etype), v)
3251
        if form == 'all':
3252
            return src, dst, eid
3253
        elif form == 'uv':
3254
            return src, dst
3255
        elif form == 'eid':
3256
            return eid
3257
        else:
3258
            raise DGLError('Invalid form: {}. Must be "all", "uv" or "eid".'.format(form))
3259

Mufei Li's avatar
Mufei Li committed
3260
    def out_edges(self, u, form='uv', etype=None):
3261
        """Return the outgoing edges of the given nodes.
Da Zheng's avatar
Da Zheng committed
3262
3263
3264

        Parameters
        ----------
3265
3266
        u : node ID(s)
            The node IDs. The allowed formats are:
3267

3268
3269
3270
3271
            * ``int``: A single node.
            * Int Tensor: Each element is a node ID. The tensor must have the same device type
              and ID data type as the graph's.
            * iterable[int]: Each element is a node ID.
Da Zheng's avatar
Da Zheng committed
3272
        form : str, optional
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
            The return form, which can be one of the following:

            - ``'eid'``: The returned result is a 1D tensor :math:`EID`, representing
              the IDs of all edges.
            - ``'uv'`` (default): The returned result is a 2-tuple of 1D tensors :math:`(U, V)`,
              representing the source and destination nodes of all edges. For each :math:`i`,
              :math:`(U[i], V[i])` forms an edge.
            - ``'all'``: The returned result is a 3-tuple of 1D tensors :math:`(U, V, EID)`,
              representing the source nodes, destination nodes and IDs of all edges.
              For each :math:`i`, :math:`(U[i], V[i])` forms an edge with ID :math:`EID[i]`.
3283
3284
3285
3286
3287
3288
3289
3290
        etype : str or (str, str, str), optional
            The type names of the edges. The allowed type name formats are:

            * ``(str, str, str)`` for source node type, edge type and destination node type.
            * or one ``str`` edge type name if the name can uniquely identify a
              triplet format in the graph.

            Can be omitted if the graph has only one type of edges.
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317

        Returns
        -------
        Tensor or (Tensor, Tensor) or (Tensor, Tensor, Tensor)
            All outgoing edges of the nodes with the specified type. For a description of the
            returned result, see the description of :attr:`form`.

        Examples
        --------
        The following example uses PyTorch backend.

        >>> import dgl
        >>> import torch

        Create a homogeneous graph.

        >>> g = dgl.graph((torch.tensor([0, 0, 1, 1]), torch.tensor([1, 0, 2, 3])))

        Query for the nodes 1 and 2.

        >>> g.out_edges(torch.tensor([1, 2]))
        (tensor([1, 1]), tensor([2, 3]))

        Specify a different value for :attr:`form`.

        >>> g.out_edges(torch.tensor([1, 2]), form='all')
        (tensor([1, 1]), tensor([2, 3]), tensor([2, 3]))
Da Zheng's avatar
Da Zheng committed
3318

3319
        For a graph of multiple edge types, it is required to specify the edge type in query.
Mufei Li's avatar
Mufei Li committed
3320

3321
3322
3323
3324
3325
3326
        >>> hg = dgl.heterograph({
        ...     ('user', 'follows', 'user'): (torch.tensor([0, 1]), torch.tensor([1, 2])),
        ...     ('user', 'plays', 'game'): (torch.tensor([3, 4]), torch.tensor([5, 6]))
        ... })
        >>> hg.out_edges(torch.tensor([1, 2]), etype='follows')
        (tensor([1]), tensor([2]))
Da Zheng's avatar
Da Zheng committed
3327

3328
        See Also
Da Zheng's avatar
Da Zheng committed
3329
        --------
3330
3331
        edges
        in_edges
Da Zheng's avatar
Da Zheng committed
3332
        """
3333
        u = utils.prepare_tensor(self, u, 'u')
3334
3335
3336
        srctype, _, _ = self.to_canonical_etype(etype)
        if F.as_scalar(F.sum(self.has_nodes(u, ntype=srctype), dim=0)) != len(u):
            raise DGLError('u contains invalid node IDs')
Mufei Li's avatar
Mufei Li committed
3337
        src, dst, eid = self._graph.out_edges(self.get_etype_id(etype), u)
3338
        if form == 'all':
3339
            return src, dst, eid
3340
        elif form == 'uv':
3341
            return src, dst
3342
        elif form == 'eid':
3343
            return eid
3344
        else:
3345
            raise DGLError('Invalid form: {}. Must be "all", "uv" or "eid".'.format(form))
3346

3347
3348
    def all_edges(self, form='uv', order='eid', etype=None):
        """Return all edges with the specified edge type.
Da Zheng's avatar
Da Zheng committed
3349
3350
3351
3352

        Parameters
        ----------
        form : str, optional
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
            The return form, which can be one of the following:

            - ``'eid'``: The returned result is a 1D tensor :math:`EID`, representing
              the IDs of all edges.
            - ``'uv'`` (default): The returned result is a 2-tuple of 1D tensors :math:`(U, V)`,
              representing the source and destination nodes of all edges. For each :math:`i`,
              :math:`(U[i], V[i])` forms an edge.
            - ``'all'``: The returned result is a 3-tuple of 1D tensors :math:`(U, V, EID)`,
              representing the source nodes, destination nodes and IDs of all edges.
              For each :math:`i`, :math:`(U[i], V[i])` forms an edge with ID :math:`EID[i]`.
        order : str, optional
            The order of the returned edges, which can be one of the following:

            - ``'srcdst'``: The edges are sorted first by their source node IDs and then
              by their destination node IDs to break ties.
            - ``'eid'`` (default): The edges are sorted by their IDs.
Minjie Wang's avatar
Minjie Wang committed
3369
        etype : str or tuple of str, optional
3370
3371
3372
3373
            The edge type for query, which can be an edge type (str) or a canonical edge type
            (3-tuple of str). When an edge type appears in multiple canonical edge types, one
            must use a canonical edge type. If the graph has multiple edge types, one must
            specify the argument. Otherwise, it can be omitted.
Da Zheng's avatar
Da Zheng committed
3374
3375
3376

        Returns
        -------
3377
3378
3379
        Tensor or (Tensor, Tensor) or (Tensor, Tensor, Tensor)
            All edges of the specified edge type. For a description of the returned result,
            see the description of :attr:`form`.
Da Zheng's avatar
Da Zheng committed
3380
3381
3382
3383
3384

        Examples
        --------
        The following example uses PyTorch backend.

3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
        >>> import dgl
        >>> import torch

        Create a homogeneous graph.

        >>> g = dgl.graph((torch.tensor([0, 0, 1, 1]), torch.tensor([1, 0, 2, 3])))

        Query for edges.

        >>> g.all_edges()
        (tensor([0, 0, 1, 1]), tensor([1, 0, 2, 3]))

        Specify a different value for :attr:`form` and :attr:`order`.

Mufei Li's avatar
Mufei Li committed
3399
        >>> g.all_edges(form='all', order='srcdst')
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
        (tensor([0, 0, 1, 1]), tensor([0, 1, 2, 3]), tensor([1, 0, 2, 3]))

        For a graph of multiple edge types, it is required to specify the edge type in query.

        >>> hg = dgl.heterograph({
        ...     ('user', 'follows', 'user'): (torch.tensor([0, 1]), torch.tensor([1, 2])),
        ...     ('user', 'plays', 'game'): (torch.tensor([3, 4]), torch.tensor([5, 6]))
        ... })
        >>> hg.all_edges(etype='plays')
        (tensor([3, 4]), tensor([5, 6]))

        See Also
        --------
        edges
        in_edges
        out_edges
Da Zheng's avatar
Da Zheng committed
3416
        """
Minjie Wang's avatar
Minjie Wang committed
3417
        src, dst, eid = self._graph.edges(self.get_etype_id(etype), order)
3418
        if form == 'all':
3419
            return src, dst, eid
3420
        elif form == 'uv':
3421
            return src, dst
3422
        elif form == 'eid':
3423
            return eid
3424
        else:
3425
            raise DGLError('Invalid form: {}. Must be "all", "uv" or "eid".'.format(form))
3426

Minjie Wang's avatar
Minjie Wang committed
3427
    def in_degree(self, v, etype=None):
Mufei Li's avatar
Mufei Li committed
3428
        """Return the in-degree of node ``v`` with edges of type ``etype``.
Da Zheng's avatar
Da Zheng committed
3429

3430
        **DEPRECATED**: Please use in_degrees
Da Zheng's avatar
Da Zheng committed
3431
        """
3432
3433
        dgl_warning("DGLGraph.in_degree is deprecated. Please use DGLGraph.in_degrees")
        return self.in_degrees(v, etype)
Da Zheng's avatar
Da Zheng committed
3434

Minjie Wang's avatar
Minjie Wang committed
3435
    def in_degrees(self, v=ALL, etype=None):
3436
3437
3438
        """Return the in-degree(s) of the given nodes.

        It computes the in-degree(s) w.r.t. to the edges of the given edge type.
Da Zheng's avatar
Da Zheng committed
3439
3440
3441

        Parameters
        ----------
3442
3443
        v : node IDs
            The node IDs. The allowed formats are:
3444

3445
3446
3447
3448
            * ``int``: A single node.
            * Int Tensor: Each element is a node ID. The tensor must have the same device type
              and ID data type as the graph's.
            * iterable[int]: Each element is a node ID.
3449

3450
3451
3452
3453
3454
3455
3456
3457
3458
            If not given, return the in-degrees of all the nodes.
        etype : str or (str, str, str), optional
            The type name of the edges. The allowed type name formats are:

            * ``(str, str, str)`` for source node type, edge type and destination node type.
            * or one ``str`` edge type name if the name can uniquely identify a
              triplet format in the graph.

            Can be omitted if the graph has only one type of edges.
Da Zheng's avatar
Da Zheng committed
3459
3460
3461

        Returns
        -------
3462
3463
3464
        int or Tensor
            The in-degree(s) of the node(s) in a Tensor. The i-th element is the in-degree
            of the i-th input node. If :attr:`v` is an ``int``, return an ``int`` too.
Da Zheng's avatar
Da Zheng committed
3465
3466
3467
3468
3469

        Examples
        --------
        The following example uses PyTorch backend.

3470
3471
        >>> import dgl
        >>> import torch
Mufei Li's avatar
Mufei Li committed
3472

3473
        Create a homogeneous graph.
Mufei Li's avatar
Mufei Li committed
3474

3475
        >>> g = dgl.graph((torch.tensor([0, 0, 1, 1]), torch.tensor([1, 1, 2, 3])))
Mufei Li's avatar
Mufei Li committed
3476

3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
        Query for all nodes.

        >>> g.in_degrees()
        tensor([0, 2, 1, 1])

        Query for nodes 1 and 2.

        >>> g.in_degrees(torch.tensor([1, 2]))
        tensor([2, 1])

        For a graph of multiple edge types, it is required to specify the edge type in query.

        >>> hg = dgl.heterograph({
        ...     ('user', 'follows', 'user'): (torch.tensor([0, 1]), torch.tensor([1, 2])),
        ...     ('user', 'plays', 'game'): (torch.tensor([3, 4]), torch.tensor([5, 6]))
        ... })
        >>> hg.in_degrees(torch.tensor([1, 0]), etype='follows')
        tensor([1, 0])

        See Also
        --------
        out_degrees
Da Zheng's avatar
Da Zheng committed
3499
        """
3500
        dsttype = self.to_canonical_etype(etype)[2]
Minjie Wang's avatar
Minjie Wang committed
3501
        etid = self.get_etype_id(etype)
3502
        if is_all(v):
3503
            v = self.dstnodes(dsttype)
3504
3505
        v_tensor = utils.prepare_tensor(self, v, 'v')
        deg = self._graph.in_degrees(etid, v_tensor)
3506
3507
        if isinstance(v, numbers.Integral):
            return F.as_scalar(deg)
3508
        else:
3509
            return deg
Da Zheng's avatar
Da Zheng committed
3510

Mufei Li's avatar
Mufei Li committed
3511
3512
    def out_degree(self, u, etype=None):
        """Return the out-degree of node `u` with edges of type ``etype``.
Da Zheng's avatar
Da Zheng committed
3513

3514
        DEPRECATED: please use DGL.out_degrees
3515
        """
3516
3517
        dgl_warning("DGLGraph.out_degree is deprecated. Please use DGLGraph.out_degrees")
        return self.out_degrees(u, etype)
3518

Mufei Li's avatar
Mufei Li committed
3519
    def out_degrees(self, u=ALL, etype=None):
3520
3521
3522
        """Return the out-degree(s) of the given nodes.

        It computes the out-degree(s) w.r.t. to the edges of the given edge type.
3523
3524
3525

        Parameters
        ----------
3526
3527
        u : node IDs
            The node IDs. The allowed formats are:
3528

3529
3530
3531
3532
            * ``int``: A single node.
            * Int Tensor: Each element is a node ID. The tensor must have the same device type
              and ID data type as the graph's.
            * iterable[int]: Each element is a node ID.
3533

3534
3535
3536
3537
3538
3539
3540
3541
3542
            If not given, return the in-degrees of all the nodes.
        etype : str or (str, str, str), optional
            The type names of the edges. The allowed type name formats are:

            * ``(str, str, str)`` for source node type, edge type and destination node type.
            * or one ``str`` edge type name if the name can uniquely identify a
              triplet format in the graph.

            Can be omitted if the graph has only one type of edges.
3543
3544
3545

        Returns
        -------
3546
3547
3548
        int or Tensor
            The out-degree(s) of the node(s) in a Tensor. The i-th element is the out-degree
            of the i-th input node. If :attr:`v` is an ``int``, return an ``int`` too.
3549
3550
3551
3552
3553

        Examples
        --------
        The following example uses PyTorch backend.

3554
3555
        >>> import dgl
        >>> import torch
Mufei Li's avatar
Mufei Li committed
3556

3557
        Create a homogeneous graph.
Mufei Li's avatar
Mufei Li committed
3558

3559
        >>> g = dgl.graph((torch.tensor([0, 0, 1, 1]), torch.tensor([1, 1, 2, 3])))
Mufei Li's avatar
Mufei Li committed
3560

3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
        Query for all nodes.

        >>> g.out_degrees()
        tensor([2, 2, 0, 0])

        Query for nodes 1 and 2.

        >>> g.out_degrees(torch.tensor([1, 2]))
        tensor([2, 0])

        For a graph of multiple edge types, it is required to specify the edge type in query.

        >>> hg = dgl.heterograph({
        ...     ('user', 'follows', 'user'): (torch.tensor([0, 1]), torch.tensor([1, 2])),
        ...     ('user', 'plays', 'game'): (torch.tensor([3, 4]), torch.tensor([5, 6]))
        ... })
        >>> hg.out_degrees(torch.tensor([1, 0]), etype='follows')
        tensor([1, 1])
3579
3580
3581

        See Also
        --------
3582
        in_degrees
3583
        """
3584
        srctype = self.to_canonical_etype(etype)[0]
Minjie Wang's avatar
Minjie Wang committed
3585
        etid = self.get_etype_id(etype)
Mufei Li's avatar
Mufei Li committed
3586
        if is_all(u):
3587
            u = self.srcnodes(srctype)
3588
3589
3590
        u_tensor = utils.prepare_tensor(self, u, 'u')
        if F.as_scalar(F.sum(self.has_nodes(u_tensor, ntype=srctype), dim=0)) != len(u_tensor):
            raise DGLError('u contains invalid node IDs')
3591
3592
3593
        deg = self._graph.out_degrees(etid, utils.prepare_tensor(self, u, 'u'))
        if isinstance(u, numbers.Integral):
            return F.as_scalar(deg)
3594
        else:
3595
            return deg
Minjie Wang's avatar
Minjie Wang committed
3596

3597
    def adjacency_matrix(self, transpose=False, ctx=F.cpu(), scipy_fmt=None, etype=None):
3598
        """Alias of :meth:`adj`"""
3599
3600
        return self.adj(transpose, ctx, scipy_fmt, etype)

3601
    def adj(self, transpose=False, ctx=F.cpu(), scipy_fmt=None, etype=None):
Minjie Wang's avatar
Minjie Wang committed
3602
        """Return the adjacency matrix of edges of the given edge type.
3603

Minjie Wang's avatar
Minjie Wang committed
3604
        By default, a row of returned adjacency matrix represents the
3605
        source of an edge and the column represents the destination.
3606

3607
3608
        When transpose is True, a row represents the destination and a column
        represents the source.
3609
3610
3611

        Parameters
        ----------
Mufei Li's avatar
Mufei Li committed
3612
        transpose : bool, optional
3613
            A flag to transpose the returned adjacency matrix. (Default: False)
Mufei Li's avatar
Mufei Li committed
3614
3615
3616
        ctx : context, optional
            The context of returned adjacency matrix. (Default: cpu)
        scipy_fmt : str, optional
Minjie Wang's avatar
Minjie Wang committed
3617
            If specified, return a scipy sparse matrix in the given format.
Mufei Li's avatar
Mufei Li committed
3618
            Otherwise, return a backend dependent sparse tensor. (Default: None)
3619
3620
3621
3622
3623
3624
3625
3626
3627
        etype : str or (str, str, str), optional
            The type names of the edges. The allowed type name formats are:

            * ``(str, str, str)`` for source node type, edge type and destination node type.
            * or one ``str`` edge type name if the name can uniquely identify a
              triplet format in the graph.

            Can be omitted if the graph has only one type of edges.

3628

Minjie Wang's avatar
Minjie Wang committed
3629
3630
3631
3632
        Returns
        -------
        SparseTensor or scipy.sparse.spmatrix
            Adjacency matrix.
Mufei Li's avatar
Mufei Li committed
3633
3634
3635
3636

        Examples
        --------

3637
3638
3639
3640
3641
        The following example uses PyTorch backend.

        >>> import dgl
        >>> import torch

Mufei Li's avatar
Mufei Li committed
3642
3643
        Instantiate a heterogeneous graph.

3644
3645
3646
3647
        >>> g = dgl.heterograph({
        ...     ('user', 'follows', 'user'): ([0, 1], [0, 1]),
        ...     ('developer', 'develops', 'game'): ([0, 1], [0, 2])
        ... })
Mufei Li's avatar
Mufei Li committed
3648
3649
3650

        Get a backend dependent sparse tensor. Here we use PyTorch for example.

3651
        >>> g.adj(etype='develops')
3652
3653
        tensor(indices=tensor([[0, 1],
                               [0, 2]]),
Mufei Li's avatar
Mufei Li committed
3654
               values=tensor([1., 1.]),
3655
               size=(2, 3), nnz=2, layout=torch.sparse_coo)
Mufei Li's avatar
Mufei Li committed
3656
3657
3658

        Get a scipy coo sparse matrix.

3659
        >>> g.adj(scipy_fmt='coo', etype='develops')
3660
        <2x3 sparse matrix of type '<class 'numpy.int64'>'
3661
           with 2 stored elements in COOrdinate format>
3662
        """
Minjie Wang's avatar
Minjie Wang committed
3663
3664
3665
3666
3667
        etid = self.get_etype_id(etype)
        if scipy_fmt is None:
            return self._graph.adjacency_matrix(etid, transpose, ctx)[0]
        else:
            return self._graph.adjacency_matrix_scipy(etid, transpose, scipy_fmt, False)
3668

3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
    def adj_sparse(self, fmt, etype=None):
        """Return the adjacency matrix of edges of the given edge type as tensors of
        a sparse matrix representation.

        By default, a row of returned adjacency matrix represents the
        source of an edge and the column represents the destination.

        Parameters
        ----------
        fmt : str
            Either ``coo``, ``csr`` or ``csc``.
        etype : str or (str, str, str), optional
            The type names of the edges. The allowed type name formats are:

            * ``(str, str, str)`` for source node type, edge type and destination node type.
            * or one ``str`` edge type name if the name can uniquely identify a
              triplet format in the graph.

            Can be omitted if the graph has only one type of edges.

        Returns
        -------
        tuple[Tensor]
            If :attr:`fmt` is ``coo``, returns a pair of source and destination node ID
            tensors.

            If :attr:`fmt` is ``csr`` or ``csc``, return the CSR or CSC representation
            of the adjacency matrix as a triplet of tensors
            ``(indptr, indices, edge_ids)``.  Namely ``edge_ids`` could be an empty
            tensor with 0 elements, in which case the edge IDs are consecutive
            integers starting from 0.

        Examples
        --------
        >>> g = dgl.graph(([0, 1, 2], [1, 2, 3]))
        >>> g.adj_sparse('coo')
3705
        (tensor([0, 1, 2]), tensor([1, 2, 3]))
3706
        >>> g.adj_sparse('csr')
3707
        (tensor([0, 1, 2, 3, 3]), tensor([1, 2, 3]), tensor([0, 1, 2]))
3708
3709
3710
3711
3712
3713
3714
        """
        etid = self.get_etype_id(etype)
        if fmt == 'csc':
            # The first two elements are number of rows and columns
            return self._graph.adjacency_matrix_tensors(etid, True, 'csr')[2:]
        else:
            return self._graph.adjacency_matrix_tensors(etid, False, fmt)[2:]
3715

3716
    def adjacency_matrix_scipy(self, transpose=False, fmt='csr', return_edge_ids=None):
3717
3718
3719
3720
3721
3722
3723
3724
        """DEPRECATED: please use ``dgl.adjacency_matrix(transpose, scipy_fmt=fmt)``.
        """
        dgl_warning('DGLGraph.adjacency_matrix_scipy is deprecated. '
                    'Please replace it with:\n\n\t'
                    'DGLGraph.adjacency_matrix(transpose, scipy_fmt="{}").\n'.format(fmt))

        return self.adjacency_matrix(transpose=transpose, scipy_fmt=fmt)

3725
    def inc(self, typestr, ctx=F.cpu(), etype=None):
Minjie Wang's avatar
Minjie Wang committed
3726
3727
        """Return the incidence matrix representation of edges with the given
        edge type.
3728

Mufei Li's avatar
Mufei Li committed
3729
        An incidence matrix is an n-by-m sparse matrix, where n is
Minjie Wang's avatar
Minjie Wang committed
3730
3731
3732
        the number of nodes and m is the number of edges. Each nnz
        value indicating whether the edge is incident to the node
        or not.
3733

Mufei Li's avatar
Mufei Li committed
3734
        There are three types of incidence matrices :math:`I`:
Da Zheng's avatar
Da Zheng committed
3735

Minjie Wang's avatar
Minjie Wang committed
3736
        * ``in``:
Da Zheng's avatar
Da Zheng committed
3737

Minjie Wang's avatar
Minjie Wang committed
3738
3739
3740
            - :math:`I[v, e] = 1` if :math:`e` is the in-edge of :math:`v`
              (or :math:`v` is the dst node of :math:`e`);
            - :math:`I[v, e] = 0` otherwise.
Da Zheng's avatar
Da Zheng committed
3741

Minjie Wang's avatar
Minjie Wang committed
3742
        * ``out``:
Da Zheng's avatar
Da Zheng committed
3743

Minjie Wang's avatar
Minjie Wang committed
3744
3745
3746
3747
3748
3749
3750
3751
3752
            - :math:`I[v, e] = 1` if :math:`e` is the out-edge of :math:`v`
              (or :math:`v` is the src node of :math:`e`);
            - :math:`I[v, e] = 0` otherwise.

        * ``both`` (only if source and destination node type are the same):

            - :math:`I[v, e] = 1` if :math:`e` is the in-edge of :math:`v`;
            - :math:`I[v, e] = -1` if :math:`e` is the out-edge of :math:`v`;
            - :math:`I[v, e] = 0` otherwise (including self-loop).
Da Zheng's avatar
Da Zheng committed
3753
3754
3755

        Parameters
        ----------
Minjie Wang's avatar
Minjie Wang committed
3756
3757
        typestr : str
            Can be either ``in``, ``out`` or ``both``
Mufei Li's avatar
Mufei Li committed
3758
3759
        ctx : context, optional
            The context of returned incidence matrix. (Default: cpu)
3760
3761
3762
3763
3764
3765
3766
3767
        etype : str or (str, str, str), optional
            The type names of the edges. The allowed type name formats are:

            * ``(str, str, str)`` for source node type, edge type and destination node type.
            * or one ``str`` edge type name if the name can uniquely identify a
              triplet format in the graph.

            Can be omitted if the graph has only one type of edges.
Minjie Wang's avatar
Minjie Wang committed
3768
3769
3770

        Returns
        -------
Mufei Li's avatar
Mufei Li committed
3771
        Framework SparseTensor
Minjie Wang's avatar
Minjie Wang committed
3772
            The incidence matrix.
Mufei Li's avatar
Mufei Li committed
3773
3774
3775
3776

        Examples
        --------

3777
3778
3779
3780
3781
3782
        The following example uses PyTorch backend.

        >>> import dgl

        >>> g = dgl.graph(([0, 1], [0, 2]))
        >>> g.inc('in')
Mufei Li's avatar
Mufei Li committed
3783
3784
3785
3786
        tensor(indices=tensor([[0, 2],
                               [0, 1]]),
               values=tensor([1., 1.]),
               size=(3, 2), nnz=2, layout=torch.sparse_coo)
3787
        >>> g.inc('out')
Mufei Li's avatar
Mufei Li committed
3788
3789
3790
3791
        tensor(indices=tensor([[0, 1],
                               [0, 1]]),
               values=tensor([1., 1.]),
               size=(3, 2), nnz=2, layout=torch.sparse_coo)
3792
        >>> g.inc('both')
Mufei Li's avatar
Mufei Li committed
3793
3794
3795
3796
        tensor(indices=tensor([[1, 2],
                               [1, 1]]),
               values=tensor([-1.,  1.]),
               size=(3, 2), nnz=2, layout=torch.sparse_coo)
Da Zheng's avatar
Da Zheng committed
3797
        """
Minjie Wang's avatar
Minjie Wang committed
3798
3799
3800
        etid = self.get_etype_id(etype)
        return self._graph.incidence_matrix(etid, typestr, ctx)[0]

3801
3802
    incidence_matrix = inc

Minjie Wang's avatar
Minjie Wang committed
3803
3804
3805
3806
3807
    #################################################################
    # Features
    #################################################################

    def node_attr_schemes(self, ntype=None):
Mufei Li's avatar
Mufei Li committed
3808
        """Return the node feature schemes for the specified type.
Da Zheng's avatar
Da Zheng committed
3809

3810
        The scheme of a feature describes the shape and data type of it.
Da Zheng's avatar
Da Zheng committed
3811
3812
3813

        Parameters
        ----------
Minjie Wang's avatar
Minjie Wang committed
3814
        ntype : str, optional
3815
3816
            The node type name. Can be omitted if there is only one type of nodes
            in the graph.
Da Zheng's avatar
Da Zheng committed
3817
3818
3819

        Returns
        -------
3820
3821
        dict[str, Scheme]
            A dictionary mapping a feature name to its associated feature scheme.
3822
3823
3824

        Examples
        --------
3825
3826
3827
3828
3829
3830
        The following example uses PyTorch backend.

        >>> import dgl
        >>> import torch

        Query for a homogeneous graph.
3831

3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
        >>> g = dgl.graph((torch.tensor([0, 1]), torch.tensor([1, 2])))
        >>> g.ndata['h1'] = torch.randn(3, 1)
        >>> g.ndata['h2'] = torch.randn(3, 2)
        >>> g.node_attr_schemes()
        {'h1': Scheme(shape=(1,), dtype=torch.float32),
         'h2': Scheme(shape=(2,), dtype=torch.float32)}

        Query for a heterogeneous graph of multiple node types.

        >>> g = dgl.heterograph({('user', 'plays', 'game'):
        ...                      (torch.tensor([1, 2]), torch.tensor([3, 4]))})
        >>> g.nodes['user'].data['h1'] = torch.randn(3, 1)
        >>> g.nodes['user'].data['h2'] = torch.randn(3, 2)
3845
        >>> g.node_attr_schemes('user')
3846
3847
        {'h1': Scheme(shape=(1,), dtype=torch.float32),
         'h2': Scheme(shape=(2,), dtype=torch.float32)}
Mufei Li's avatar
Mufei Li committed
3848
3849
3850
3851

        See Also
        --------
        edge_attr_schemes
Da Zheng's avatar
Da Zheng committed
3852
        """
Minjie Wang's avatar
Minjie Wang committed
3853
        return self._node_frames[self.get_ntype_id(ntype)].schemes
Da Zheng's avatar
Da Zheng committed
3854

Minjie Wang's avatar
Minjie Wang committed
3855
    def edge_attr_schemes(self, etype=None):
Mufei Li's avatar
Mufei Li committed
3856
        """Return the edge feature schemes for the specified type.
Da Zheng's avatar
Da Zheng committed
3857

3858
        The scheme of a feature describes the shape and data type of it.
Da Zheng's avatar
Da Zheng committed
3859
3860
3861

        Parameters
        ----------
3862
3863
3864
3865
3866
3867
3868
3869
3870
        etype : str or (str, str, str), optional
            The type names of the edges. The allowed type name formats are:

            * ``(str, str, str)`` for source node type, edge type and destination node type.
            * or one ``str`` edge type name if the name can uniquely identify a
              triplet format in the graph.

            Can be omitted if the graph has only one type of edges.

Da Zheng's avatar
Da Zheng committed
3871
3872
3873

        Returns
        -------
3874
3875
        dict[str, Scheme]
            A dictionary mapping a feature name to its associated feature scheme.
Da Zheng's avatar
Da Zheng committed
3876

3877
3878
        Examples
        --------
3879
3880
3881
3882
3883
3884
        The following example uses PyTorch backend.

        >>> import dgl
        >>> import torch

        Query for a homogeneous graph.
Da Zheng's avatar
Da Zheng committed
3885

3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
        >>> g = dgl.graph((torch.tensor([0, 1]), torch.tensor([1, 2])))
        >>> g.edata['h1'] = torch.randn(2, 1)
        >>> g.edata['h2'] = torch.randn(2, 2)
        >>> g.edge_attr_schemes()
        {'h1': Scheme(shape=(1,), dtype=torch.float32),
         'h2': Scheme(shape=(2,), dtype=torch.float32)}

        Query for a heterogeneous graph of multiple edge types.

        >>> g = dgl.heterograph({('user', 'plays', 'game'):
        ...                      (torch.tensor([1, 2]), torch.tensor([3, 4])),
        ...                      ('user', 'follows', 'user'):
        ...                      (torch.tensor([3, 4]), torch.tensor([5, 6]))})
        >>> g.edges['plays'].data['h1'] = torch.randn(2, 1)
        >>> g.edges['plays'].data['h2'] = torch.randn(2, 2)
        >>> g.edge_attr_schemes('plays')
        {'h1': Scheme(shape=(1,), dtype=torch.float32),
         'h2': Scheme(shape=(2,), dtype=torch.float32)}
Mufei Li's avatar
Mufei Li committed
3904
3905
3906
3907

        See Also
        --------
        node_attr_schemes
Da Zheng's avatar
Da Zheng committed
3908
        """
Minjie Wang's avatar
Minjie Wang committed
3909
        return self._edge_frames[self.get_etype_id(etype)].schemes
Da Zheng's avatar
Da Zheng committed
3910

Minjie Wang's avatar
Minjie Wang committed
3911
    def set_n_initializer(self, initializer, field=None, ntype=None):
3912
        """Set the initializer for node features.
Da Zheng's avatar
Da Zheng committed
3913

3914
3915
3916
        When only part of the nodes have a feature (e.g. new nodes are added,
        features are set for a subset of nodes), the initializer initializes
        features for the rest nodes.
Minjie Wang's avatar
Minjie Wang committed
3917
3918
3919
3920

        Parameters
        ----------
        initializer : callable
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
            A function of signature ``func(shape, dtype, ctx, id_range) -> Tensor``.
            The tensor will be the initialized features. The arguments are:

            - ``shape``: The shape of the tensor to return, which is a tuple of int.
              The first dimension is the number of nodes for feature initialization.
            - ``dtype``: The data type of the tensor to return, which is a
              framework-specific data type object.
            - ``ctx``: The device of the tensor to return, which is a framework-specific
              device object.
            - ``id_range``: The start and end ID of the nodes for feature initialization,
              which is a slice.
Minjie Wang's avatar
Minjie Wang committed
3932
        field : str, optional
3933
3934
            The name of the feature that the initializer applies. If not given, the
            initializer applies to all features.
Minjie Wang's avatar
Minjie Wang committed
3935
        ntype : str, optional
3936
            The type name of the nodes. Can be omitted if the graph has only one type of nodes.
Da Zheng's avatar
Da Zheng committed
3937

3938
        Notes
Minjie Wang's avatar
Minjie Wang committed
3939
        -----
3940
3941
        Without setting a node feature initializer, zero tensors are generated
        for nodes without a feature.
Da Zheng's avatar
Da Zheng committed
3942

3943
        Examples
Mufei Li's avatar
Mufei Li committed
3944
        --------
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994

        The following example uses PyTorch backend.

        >>> import dgl
        >>> import torch

        Define a function for initializer.

        >>> def init_feats(shape, dtype, device, id_range):
        ...     return torch.ones(shape, dtype=dtype, device=device)

        An example for a homogeneous graph.

        >>> g = dgl.graph((torch.tensor([0]), torch.tensor([1])))
        >>> g.ndata['h1'] = torch.zeros(2, 2)
        >>> g.ndata['h2'] = torch.ones(2, 1)
        >>> # Apply the initializer to feature 'h2' only.
        >>> g.set_n_initializer(init_feats, field='h2')
        >>> g.add_nodes(1)
        >>> print(g.ndata['h1'])
        tensor([[0., 0.],
                [0., 0.],
                [0., 0.]])
        >>> print(g.ndata['h2'])
        tensor([[1.], [1.], [1.]])

        An example for a heterogeneous graph of multiple node types.

        >>> g = dgl.heterograph({
        ...     ('user', 'plays', 'game'): (torch.tensor([0, 1, 1, 2]),
        ...                                 torch.tensor([0, 0, 1, 1])),
        ...     ('developer', 'develops', 'game'): (torch.tensor([0, 1]),
        ...                                         torch.tensor([0, 1]))
        ...     })
        >>> g.nodes['user'].data['h'] = torch.zeros(3, 2)
        >>> g.nodes['game'].data['w'] = torch.ones(2, 2)
        >>> g.set_n_initializer(init_feats, ntype='game')
        >>> g.add_nodes(1, ntype='user')
        >>> # Initializer not set for 'user', use zero tensors by default
        >>> g.nodes['user'].data['h']
        tensor([[0., 0.],
                [0., 0.],
                [0., 0.],
                [0., 0.]])
        >>> # Initializer set for 'game'
        >>> g.add_nodes(1, ntype='game')
        >>> g.nodes['game'].data['w']
        tensor([[1., 1.],
                [1., 1.],
                [1., 1.]])
Da Zheng's avatar
Da Zheng committed
3995
        """
Minjie Wang's avatar
Minjie Wang committed
3996
3997
        ntid = self.get_ntype_id(ntype)
        self._node_frames[ntid].set_initializer(initializer, field)
Da Zheng's avatar
Da Zheng committed
3998

Minjie Wang's avatar
Minjie Wang committed
3999
    def set_e_initializer(self, initializer, field=None, etype=None):
4000
        """Set the initializer for edge features.
Da Zheng's avatar
Da Zheng committed
4001

4002
4003
4004
        When only part of the edges have a feature (e.g. new edges are added,
        features are set for a subset of edges), the initializer initializes
        features for the rest edges.
Minjie Wang's avatar
Minjie Wang committed
4005
4006
4007
4008

        Parameters
        ----------
        initializer : callable
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
            A function of signature ``func(shape, dtype, ctx, id_range) -> Tensor``.
            The tensor will be the initialized features. The arguments are:

            - ``shape``: The shape of the tensor to return, which is a tuple of int.
              The first dimension is the number of edges for feature initialization.
            - ``dtype``: The data type of the tensor to return, which is a
              framework-specific data type object.
            - ``ctx``: The device of the tensor to return, which is a framework-specific
              device object.
            - ``id_range``: The start and end ID of the edges for feature initialization,
              which is a slice.
Minjie Wang's avatar
Minjie Wang committed
4020
        field : str, optional
4021
4022
            The name of the feature that the initializer applies. If not given, the
            initializer applies to all features.
4023
4024
4025
4026
4027
4028
4029
4030
4031
        etype : str or (str, str, str), optional
            The type names of the edges. The allowed type name formats are:

            * ``(str, str, str)`` for source node type, edge type and destination node type.
            * or one ``str`` edge type name if the name can uniquely identify a
              triplet format in the graph.

            Can be omitted if the graph has only one type of edges.

Minjie Wang's avatar
Minjie Wang committed
4032

4033
        Notes
Minjie Wang's avatar
Minjie Wang committed
4034
        -----
4035
4036
        Without setting an edge feature initializer, zero tensors are generated
        for edges without a feature.
Mufei Li's avatar
Mufei Li committed
4037

4038
        Examples
Mufei Li's avatar
Mufei Li committed
4039
        --------
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087

        The following example uses PyTorch backend.

        >>> import dgl
        >>> import torch

        Define a function for initializer.

        >>> def init_feats(shape, dtype, device, id_range):
        ...     return torch.ones(shape, dtype=dtype, device=device)

        An example for a homogeneous graph.

        >>> g = dgl.graph((torch.tensor([0]), torch.tensor([1])))
        >>> g.edata['h1'] = torch.zeros(1, 2)
        >>> g.edata['h2'] = torch.ones(1, 1)
        >>> # Apply the initializer to feature 'h2' only.
        >>> g.set_e_initializer(init_feats, field='h2')
        >>> g.add_edges(torch.tensor([1]), torch.tensor([1]))
        >>> print(g.edata['h1'])
        tensor([[0., 0.],
                [0., 0.]])
        >>> print(g.edata['h2'])
        tensor([[1.], [1.]])

        An example for a heterogeneous graph of multiple edge types.

        >>> g = dgl.heterograph({
        ...     ('user', 'plays', 'game'): (torch.tensor([0, 1]),
        ...                                 torch.tensor([0, 0])),
        ...     ('developer', 'develops', 'game'): (torch.tensor([0, 1]),
        ...                                         torch.tensor([0, 1]))
        ...     })
        >>> g.edges['plays'].data['h'] = torch.zeros(2, 2)
        >>> g.edges['develops'].data['w'] = torch.ones(2, 2)
        >>> g.set_e_initializer(init_feats, etype='plays')
        >>> # Initializer not set for 'develops', use zero tensors by default
        >>> g.add_edges(torch.tensor([1]), torch.tensor([1]), etype='develops')
        >>> g.edges['develops'].data['w']
        tensor([[1., 1.],
                [1., 1.],
                [0., 0.]])
        >>> # Initializer set for 'plays'
        >>> g.add_edges(torch.tensor([1]), torch.tensor([1]), etype='plays')
        >>> g.edges['plays'].data['h']
        tensor([[0., 0.],
                [0., 0.],
                [1., 1.]])
Da Zheng's avatar
Da Zheng committed
4088
        """
Minjie Wang's avatar
Minjie Wang committed
4089
4090
        etid = self.get_etype_id(etype)
        self._edge_frames[etid].set_initializer(initializer, field)
Da Zheng's avatar
Da Zheng committed
4091

4092
    def _set_n_repr(self, ntid, u, data):
Minjie Wang's avatar
Minjie Wang committed
4093
        """Internal API to set node features.
Da Zheng's avatar
Da Zheng committed
4094
4095
4096
4097
4098
4099

        `data` is a dictionary from the feature name to feature tensor. Each tensor
        is of shape (B, D1, D2, ...), where B is the number of nodes to be updated,
        and (D1, D2, ...) be the shape of the node representation tensor. The
        length of the given node ids must match B (i.e, len(u) == B).

4100
        All updates will be done out of place to work with autograd.
Da Zheng's avatar
Da Zheng committed
4101
4102
4103

        Parameters
        ----------
Minjie Wang's avatar
Minjie Wang committed
4104
4105
        ntid : int
            Node type id.
Da Zheng's avatar
Da Zheng committed
4106
4107
        u : node, container or tensor
            The node(s).
Minjie Wang's avatar
Minjie Wang committed
4108
4109
        data : dict of tensor
            Node representation.
Da Zheng's avatar
Da Zheng committed
4110
        """
4111
        if is_all(u):
Minjie Wang's avatar
Minjie Wang committed
4112
            num_nodes = self._graph.number_of_nodes(ntid)
4113
        else:
4114
            u = utils.prepare_tensor(self, u, 'u')
4115
4116
4117
4118
4119
4120
            num_nodes = len(u)
        for key, val in data.items():
            nfeats = F.shape(val)[0]
            if nfeats != num_nodes:
                raise DGLError('Expect number of features to match number of nodes (len(u)).'
                               ' Got %d and %d instead.' % (nfeats, num_nodes))
4121
4122
4123
4124
            if F.context(val) != self.device:
                raise DGLError('Cannot assign node feature "{}" on device {} to a graph on'
                               ' device {}. Call DGLGraph.to() to copy the graph to the'
                               ' same device.'.format(key, F.context(val), self.device))
4125
4126
4127
4128
4129
4130
4131
4132
4133
            # To prevent users from doing things like:
            #
            #     g.pin_memory_()
            #     g.ndata['x'] = torch.randn(...)
            #     sg = g.sample_neighbors(torch.LongTensor([...]).cuda())
            #     sg.ndata['x']    # Becomes a CPU tensor even if sg is on GPU due to lazy slicing
            if self.is_pinned() and F.context(val) == 'cpu' and not F.is_pinned(val):
                raise DGLError('Pinned graph requires the node data to be pinned as well. '
                               'Please pin the node data before assignment.')
4134
4135

        if is_all(u):
4136
            self._node_frames[ntid].update(data)
4137
        else:
4138
            self._node_frames[ntid].update_row(u, data)
Da Zheng's avatar
Da Zheng committed
4139

Minjie Wang's avatar
Minjie Wang committed
4140
    def _get_n_repr(self, ntid, u):
Da Zheng's avatar
Da Zheng committed
4141
4142
4143
4144
4145
4146
        """Get node(s) representation of a single node type.

        The returned feature tensor batches multiple node features on the first dimension.

        Parameters
        ----------
Minjie Wang's avatar
Minjie Wang committed
4147
4148
        ntid : int
            Node type id.
Da Zheng's avatar
Da Zheng committed
4149
4150
4151
4152
4153
4154
4155
4156
        u : node, container or tensor
            The node(s).

        Returns
        -------
        dict
            Representation dict from feature name to feature tensor.
        """
4157
        if is_all(u):
4158
            return self._node_frames[ntid]
4159
        else:
4160
            u = utils.prepare_tensor(self, u, 'u')
4161
            return self._node_frames[ntid].subframe(u)
Da Zheng's avatar
Da Zheng committed
4162

Minjie Wang's avatar
Minjie Wang committed
4163
4164
    def _pop_n_repr(self, ntid, key):
        """Internal API to get and remove the specified node feature.
Da Zheng's avatar
Da Zheng committed
4165
4166
4167

        Parameters
        ----------
Minjie Wang's avatar
Minjie Wang committed
4168
4169
        ntid : int
            Node type id.
Da Zheng's avatar
Da Zheng committed
4170
4171
4172
4173
4174
4175
4176
4177
        key : str
            The attribute name.

        Returns
        -------
        Tensor
            The popped representation
        """
Minjie Wang's avatar
Minjie Wang committed
4178
        return self._node_frames[ntid].pop(key)
Da Zheng's avatar
Da Zheng committed
4179

4180
    def _set_e_repr(self, etid, edges, data):
Minjie Wang's avatar
Minjie Wang committed
4181
        """Internal API to set edge(s) features.
Da Zheng's avatar
Da Zheng committed
4182
4183
4184
4185
4186

        `data` is a dictionary from the feature name to feature tensor. Each tensor
        is of shape (B, D1, D2, ...), where B is the number of edges to be updated,
        and (D1, D2, ...) be the shape of the edge representation tensor.

4187
        All update will be done out of place to work with autograd.
Da Zheng's avatar
Da Zheng committed
4188
4189
4190

        Parameters
        ----------
Minjie Wang's avatar
Minjie Wang committed
4191
4192
        etid : int
            Edge type id.
Da Zheng's avatar
Da Zheng committed
4193
4194
4195
4196
4197
4198
4199
4200
        edges : edges
            Edges can be either

            * A pair of endpoint nodes (u, v), where u is the node ID of source
              node type and v is that of destination node type.
            * A tensor of edge ids of the given type.

            The default value is all the edges.
Minjie Wang's avatar
Minjie Wang committed
4201
4202
        data : tensor or dict of tensor
            Edge representation.
Da Zheng's avatar
Da Zheng committed
4203
        """
4204
        # parse argument
4205
4206
        if not is_all(edges):
            eid = utils.parse_edges_arg_to_eid(self, edges, etid, 'edges')
4207
4208
4209
4210
4211
4212

        # sanity check
        if not utils.is_dict_like(data):
            raise DGLError('Expect dictionary type for feature data.'
                           ' Got "%s" instead.' % type(data))

4213
        if is_all(edges):
Minjie Wang's avatar
Minjie Wang committed
4214
            num_edges = self._graph.number_of_edges(etid)
4215
4216
4217
4218
4219
4220
4221
        else:
            num_edges = len(eid)
        for key, val in data.items():
            nfeats = F.shape(val)[0]
            if nfeats != num_edges:
                raise DGLError('Expect number of features to match number of edges.'
                               ' Got %d and %d instead.' % (nfeats, num_edges))
4222
4223
4224
4225
            if F.context(val) != self.device:
                raise DGLError('Cannot assign edge feature "{}" on device {} to a graph on'
                               ' device {}. Call DGLGraph.to() to copy the graph to the'
                               ' same device.'.format(key, F.context(val), self.device))
4226
4227
4228
4229
4230
4231
4232
4233
4234
            # To prevent users from doing things like:
            #
            #     g.pin_memory_()
            #     g.edata['x'] = torch.randn(...)
            #     sg = g.sample_neighbors(torch.LongTensor([...]).cuda())
            #     sg.edata['x']    # Becomes a CPU tensor even if sg is on GPU due to lazy slicing
            if self.is_pinned() and F.context(val) == 'cpu' and not F.is_pinned(val):
                raise DGLError('Pinned graph requires the edge data to be pinned as well. '
                               'Please pin the edge data before assignment.')
4235

4236
        # set
4237
4238
        if is_all(edges):
            self._edge_frames[etid].update(data)
4239
        else:
4240
            self._edge_frames[etid].update_row(eid, data)
Da Zheng's avatar
Da Zheng committed
4241

Minjie Wang's avatar
Minjie Wang committed
4242
4243
    def _get_e_repr(self, etid, edges):
        """Internal API to get edge features.
Da Zheng's avatar
Da Zheng committed
4244
4245
4246

        Parameters
        ----------
Minjie Wang's avatar
Minjie Wang committed
4247
4248
        etid : int
            Edge type id.
Da Zheng's avatar
Da Zheng committed
4249
4250
4251
4252
4253
4254
4255
4256
4257
        edges : edges
            Edges can be a pair of endpoint nodes (u, v), or a
            tensor of edge ids. The default value is all the edges.

        Returns
        -------
        dict
            Representation dict
        """
4258
4259
        # parse argument
        if is_all(edges):
4260
            return self._edge_frames[etid]
4261
        else:
4262
4263
            eid = utils.parse_edges_arg_to_eid(self, edges, etid, 'edges')
            return self._edge_frames[etid].subframe(eid)
Da Zheng's avatar
Da Zheng committed
4264

Minjie Wang's avatar
Minjie Wang committed
4265
    def _pop_e_repr(self, etid, key):
Da Zheng's avatar
Da Zheng committed
4266
4267
4268
4269
        """Get and remove the specified edge repr of a single edge type.

        Parameters
        ----------
Minjie Wang's avatar
Minjie Wang committed
4270
4271
        etid : int
            Edge type id.
Da Zheng's avatar
Da Zheng committed
4272
4273
4274
4275
4276
4277
4278
4279
        key : str
          The attribute name.

        Returns
        -------
        Tensor
            The popped representation
        """
Minjie Wang's avatar
Minjie Wang committed
4280
        self._edge_frames[etid].pop(key)
Da Zheng's avatar
Da Zheng committed
4281

Minjie Wang's avatar
Minjie Wang committed
4282
4283
4284
4285
4286
    #################################################################
    # Message passing
    #################################################################

    def apply_nodes(self, func, v=ALL, ntype=None, inplace=False):
4287
        """Update the features of the specified nodes by the provided function.
Da Zheng's avatar
Da Zheng committed
4288
4289
4290

        Parameters
        ----------
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
        func : callable
            The function to update node features. It must be
            a :ref:`apiudf`.
        v : node IDs
            The node IDs. The allowed formats are:

            * ``int``: A single node.
            * Int Tensor: Each element is a node ID. The tensor must have the same device type
              and ID data type as the graph's.
            * iterable[int]: Each element is a node ID.

            If not given (default), use all the nodes in the graph.
Minjie Wang's avatar
Minjie Wang committed
4303
        ntype : str, optional
4304
4305
            The node type name. Can be omitted if there is
            only one type of nodes in the graph.
Minjie Wang's avatar
Minjie Wang committed
4306
        inplace : bool, optional
4307
            **DEPRECATED**.
Da Zheng's avatar
Da Zheng committed
4308
4309
4310

        Examples
        --------
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330

        The following example uses PyTorch backend.

        >>> import dgl
        >>> import torch

        **Homogeneous graph**

        >>> g = dgl.graph(([0, 1, 2, 3], [1, 2, 3, 4]))
        >>> g.ndata['h'] = torch.ones(5, 2)
        >>> g.apply_nodes(lambda nodes: {'x' : nodes.data['h'] * 2})
        >>> g.ndata['x']
        tensor([[2., 2.],
                [2., 2.],
                [2., 2.],
                [2., 2.],
                [2., 2.]])

        **Heterogeneous graph**

4331
        >>> g = dgl.heterograph({('user', 'follows', 'user'): ([0, 1], [1, 2])})
Minjie Wang's avatar
Minjie Wang committed
4332
4333
4334
        >>> g.nodes['user'].data['h'] = torch.ones(3, 5)
        >>> g.apply_nodes(lambda nodes: {'h': nodes.data['h'] * 2}, ntype='user')
        >>> g.nodes['user'].data['h']
Da Zheng's avatar
Da Zheng committed
4335
4336
4337
        tensor([[2., 2., 2., 2., 2.],
                [2., 2., 2., 2., 2.],
                [2., 2., 2., 2., 2.]])
Mufei Li's avatar
Mufei Li committed
4338
4339
4340
4341

        See Also
        --------
        apply_edges
Da Zheng's avatar
Da Zheng committed
4342
        """
4343
4344
        if inplace:
            raise DGLError('The `inplace` option is removed in v0.5.')
Minjie Wang's avatar
Minjie Wang committed
4345
        ntid = self.get_ntype_id(ntype)
4346
        ntype = self.ntypes[ntid]
Minjie Wang's avatar
Minjie Wang committed
4347
        if is_all(v):
4348
            v_id = self.nodes(ntype)
Minjie Wang's avatar
Minjie Wang committed
4349
        else:
4350
4351
            v_id = utils.prepare_tensor(self, v, 'v')
        ndata = core.invoke_node_udf(self, v_id, ntype, func, orig_nid=v_id)
4352
        self._set_n_repr(ntid, v, ndata)
Minjie Wang's avatar
Minjie Wang committed
4353
4354

    def apply_edges(self, func, edges=ALL, etype=None, inplace=False):
4355
        """Update the features of the specified edges by the provided function.
Da Zheng's avatar
Da Zheng committed
4356
4357
4358

        Parameters
        ----------
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
        func : dgl.function.BuiltinFunction or callable
            The function to generate new edge features. It must be either
            a :ref:`api-built-in` or a :ref:`apiudf`.
        edges : edges
            The edges to update features on. The allowed input formats are:

            * ``int``: A single edge ID.
            * Int Tensor: Each element is an edge ID.  The tensor must have the same device type
              and ID data type as the graph's.
            * iterable[int]: Each element is an edge ID.
            * (Tensor, Tensor): The node-tensors format where the i-th elements
              of the two tensors specify an edge.
            * (iterable[int], iterable[int]): Similar to the node-tensors format but
              stores edge endpoints in python iterables.

            Default value specifies all the edges in the graph.

        etype : str or (str, str, str), optional
            The type name of the edges. The allowed type name formats are:

            * ``(str, str, str)`` for source node type, edge type and destination node type.
            * or one ``str`` edge type name if the name can uniquely identify a
              triplet format in the graph.

            Can be omitted if the graph has only one type of edges.

Da Zheng's avatar
Da Zheng committed
4385
        inplace: bool, optional
4386
4387
4388
4389
4390
4391
4392
            **DEPRECATED**.

        Notes
        -----
        DGL recommends using DGL's bulit-in function for the :attr:`func` argument,
        because DGL will invoke efficient kernels that avoids copying node features to
        edge features in this case.
Da Zheng's avatar
Da Zheng committed
4393
4394
4395

        Examples
        --------
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424

        The following example uses PyTorch backend.

        >>> import dgl
        >>> import torch

        **Homogeneous graph**

        >>> g = dgl.graph(([0, 1, 2, 3], [1, 2, 3, 4]))
        >>> g.ndata['h'] = torch.ones(5, 2)
        >>> g.apply_edges(lambda edges: {'x' : edges.src['h'] + edges.dst['h']})
        >>> g.edata['x']
        tensor([[2., 2.],
                [2., 2.],
                [2., 2.],
                [2., 2.]])

        Use built-in function

        >>> import dgl.function as fn
        >>> g.apply_edges(fn.u_add_v('h', 'h', 'x'))
        >>> g.edata['x']
        tensor([[2., 2.],
                [2., 2.],
                [2., 2.],
                [2., 2.]])

        **Heterogeneous graph**

4425
        >>> g = dgl.heterograph({('user', 'plays', 'game'): ([0, 1, 1, 2], [0, 0, 2, 1])})
Minjie Wang's avatar
Minjie Wang committed
4426
4427
4428
        >>> g.edges[('user', 'plays', 'game')].data['h'] = torch.ones(4, 5)
        >>> g.apply_edges(lambda edges: {'h': edges.data['h'] * 2})
        >>> g.edges[('user', 'plays', 'game')].data['h']
Da Zheng's avatar
Da Zheng committed
4429
        tensor([[2., 2., 2., 2., 2.],
4430
                [2., 2., 2., 2., 2.],
Da Zheng's avatar
Da Zheng committed
4431
4432
                [2., 2., 2., 2., 2.],
                [2., 2., 2., 2., 2.]])
Mufei Li's avatar
Mufei Li committed
4433
4434
4435
4436

        See Also
        --------
        apply_nodes
Da Zheng's avatar
Da Zheng committed
4437
        """
4438
4439
        if inplace:
            raise DGLError('The `inplace` option is removed in v0.5.')
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
        # Graph with one relation type
        if self._graph.number_of_etypes() == 1 or etype is not None:
            etid = self.get_etype_id(etype)
            etype = self.canonical_etypes[etid]
            g = self if etype is None else self[etype]
        else:   # heterogeneous graph with number of relation types > 1
            if not core.is_builtin(func):
                raise DGLError("User defined functions are not yet "
                               "supported in apply_edges for heterogeneous graphs. "
                               "Please use (apply_edges(func), etype = rel) instead.")
            g = self
Minjie Wang's avatar
Minjie Wang committed
4451
        if is_all(edges):
4452
            eid = ALL
Minjie Wang's avatar
Minjie Wang committed
4453
        else:
4454
4455
4456
            eid = utils.parse_edges_arg_to_eid(self, edges, etid, 'edges')
        if core.is_builtin(func):
            if not is_all(eid):
4457
                g = g.edge_subgraph(eid, relabel_nodes=False)
4458
4459
4460
            edata = core.invoke_gsddmm(g, func)
        else:
            edata = core.invoke_edge_udf(g, eid, etype, func)
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472

        if self._graph.number_of_etypes() == 1 or etype is not None:
            self._set_e_repr(etid, eid, edata)
        else:
            edata_tensor = {}
            key = list(edata.keys())[0]
            out_tensor_tuples = edata[key]
            for etid in range(self._graph.number_of_etypes()):
                # TODO (Israt): Check the logic why some output tensor is None
                if out_tensor_tuples[etid] is not None:
                    edata_tensor[key] = out_tensor_tuples[etid]
                    self._set_e_repr(etid, eid, edata_tensor)
Minjie Wang's avatar
Minjie Wang committed
4473

4474
4475
4476
4477
4478
4479
4480
    def send_and_recv(self,
                      edges,
                      message_func,
                      reduce_func,
                      apply_node_func=None,
                      etype=None,
                      inplace=False):
4481
4482
        """Send messages along the specified edges and reduce them on
        the destination nodes to update their features.
4483

Da Zheng's avatar
Da Zheng committed
4484
4485
        Parameters
        ----------
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
        edges : edges
            The edges to send and receive messages on. The allowed input formats are:

            * ``int``: A single edge ID.
            * Int Tensor: Each element is an edge ID.  The tensor must have the same device type
              and ID data type as the graph's.
            * iterable[int]: Each element is an edge ID.
            * (Tensor, Tensor): The node-tensors format where the i-th elements
              of the two tensors specify an edge.
            * (iterable[int], iterable[int]): Similar to the node-tensors format but
              stores edge endpoints in python iterables.

        message_func : dgl.function.BuiltinFunction or callable
            The message function to generate messages along the edges.
            It must be either a :ref:`api-built-in` or a :ref:`apiudf`.
        reduce_func : dgl.function.BuiltinFunction or callable
            The reduce function to aggregate the messages.
            It must be either a :ref:`api-built-in` or a :ref:`apiudf`.
4504
        apply_node_func : callable, optional
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
            An optional apply function to further update the node features
            after the message reduction. It must be a :ref:`apiudf`.
        etype : str or (str, str, str), optional
            The type name of the edges. The allowed type name formats are:

            * ``(str, str, str)`` for source node type, edge type and destination node type.
            * or one ``str`` edge type name if the name can uniquely identify a
              triplet format in the graph.

            Can be omitted if the graph has only one type of edges.

Da Zheng's avatar
Da Zheng committed
4516
        inplace: bool, optional
4517
4518
4519
4520
4521
4522
4523
4524
            **DEPRECATED**.

        Notes
        -----
        DGL recommends using DGL's bulit-in function for the :attr:`message_func`
        and the :attr:`reduce_func` arguments,
        because DGL will invoke efficient kernels that avoids copying node features to
        edge features in this case.
Mufei Li's avatar
Mufei Li committed
4525
4526
4527
4528
4529
4530
4531
4532

        Examples
        --------

        >>> import dgl
        >>> import dgl.function as fn
        >>> import torch

4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
        **Homogeneous graph**

        >>> g = dgl.graph(([0, 1, 2, 3], [1, 2, 3, 4]))
        >>> g.ndata['x'] = torch.ones(5, 2)
        >>> # Specify edges using (Tensor, Tensor).
        >>> g.send_and_recv(([1, 2], [2, 3]), fn.copy_u('x', 'm'), fn.sum('m', 'h'))
        >>> g.ndata['h']
        tensor([[0., 0.],
                [0., 0.],
                [1., 1.],
                [1., 1.],
                [0., 0.]])
        >>> # Specify edges using IDs.
        >>> g.send_and_recv([0, 2, 3], fn.copy_u('x', 'm'), fn.sum('m', 'h'))
        >>> g.ndata['h']
        tensor([[0., 0.],
                [1., 1.],
                [0., 0.],
                [1., 1.],
                [1., 1.]])

        **Heterogeneous graph**

4556
4557
4558
4559
        >>> g = dgl.heterograph({
        ...     ('user', 'follows', 'user'): ([0, 1], [1, 2]),
        ...     ('user', 'plays', 'game'): ([0, 1, 1, 2], [0, 0, 1, 1])
        ... })
Mufei Li's avatar
Mufei Li committed
4560
4561
        >>> g.nodes['user'].data['h'] = torch.tensor([[0.], [1.], [2.]])
        >>> g.send_and_recv(g['follows'].edges(), fn.copy_src('h', 'm'),
4562
        ...                 fn.sum('m', 'h'), etype='follows')
Mufei Li's avatar
Mufei Li committed
4563
4564
4565
4566
        >>> g.nodes['user'].data['h']
        tensor([[0.],
                [0.],
                [1.]])
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589

        **``send_and_recv`` using user-defined functions**

        >>> import torch as th
        >>> g = dgl.graph(([0, 1], [1, 2]))
        >>> g.ndata['x'] = th.tensor([[1.], [2.], [3.]])

        >>> # Define the function for sending node features as messages.
        >>> def send_source(edges):
        ...     return {'m': edges.src['x']}
        >>> # Sum the messages received and use this to replace the original node feature.
        >>> def simple_reduce(nodes):
        ...     return {'x': nodes.mailbox['m'].sum(1)}

        Send and receive messages.

        >>> g.send_and_recv(g.edges())
        >>> g.ndata['x']
        tensor([[1.],
                [1.],
                [2.]])

        Note that the feature of node 0 remains the same as it has no incoming edges.
Da Zheng's avatar
Da Zheng committed
4590
        """
4591
4592
4593
        if inplace:
            raise DGLError('The `inplace` option is removed in v0.5.')
        # edge type
Minjie Wang's avatar
Minjie Wang committed
4594
        etid = self.get_etype_id(etype)
4595
4596
4597
4598
4599
4600
        _, dtid = self._graph.metagraph.find_edge(etid)
        etype = self.canonical_etypes[etid]
        # edge IDs
        eid = utils.parse_edges_arg_to_eid(self, edges, etid, 'edges')
        if len(eid) == 0:
            # no computation
4601
            return
4602
4603
        u, v = self.find_edges(eid, etype=etype)
        # call message passing onsubgraph
4604
        g = self if etype is None else self[etype]
4605
4606
4607
        compute_graph, _, dstnodes, _ = _create_compute_graph(g, u, v, eid)
        ndata = core.message_passing(
            compute_graph, message_func, reduce_func, apply_node_func)
4608
        self._set_n_repr(dtid, dstnodes, ndata)
Minjie Wang's avatar
Minjie Wang committed
4609

Da Zheng's avatar
Da Zheng committed
4610
4611
    def pull(self,
             v,
Minjie Wang's avatar
Minjie Wang committed
4612
4613
             message_func,
             reduce_func,
4614
             apply_node_func=None,
Minjie Wang's avatar
Minjie Wang committed
4615
             etype=None,
Da Zheng's avatar
Da Zheng committed
4616
             inplace=False):
4617
4618
        """Pull messages from the specified node(s)' predecessors along the
        specified edge type, aggregate them to update the node features.
4619

Da Zheng's avatar
Da Zheng committed
4620
4621
        Parameters
        ----------
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
        v : node IDs
            The node IDs. The allowed formats are:

            * ``int``: A single node.
            * Int Tensor: Each element is a node ID. The tensor must have the same device type
              and ID data type as the graph's.
            * iterable[int]: Each element is a node ID.

        message_func : dgl.function.BuiltinFunction or callable
            The message function to generate messages along the edges.
            It must be either a :ref:`api-built-in` or a :ref:`apiudf`.
        reduce_func : dgl.function.BuiltinFunction or callable
            The reduce function to aggregate the messages.
            It must be either a :ref:`api-built-in` or a :ref:`apiudf`.
4636
        apply_node_func : callable, optional
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
            An optional apply function to further update the node features
            after the message reduction. It must be a :ref:`apiudf`.
        etype : str or (str, str, str), optional
            The type name of the edges. The allowed type name formats are:

            * ``(str, str, str)`` for source node type, edge type and destination node type.
            * or one ``str`` edge type name if the name can uniquely identify a
              triplet format in the graph.

            Can be omitted if the graph has only one type of edges.

Minjie Wang's avatar
Minjie Wang committed
4648
        inplace: bool, optional
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
            **DEPRECATED**.

        Notes
        -----
        * If some of the given nodes :attr:`v` has no in-edges, DGL does not invoke
          message and reduce functions for these nodes and fill their aggregated messages
          with zero. Users can control the filled values via :meth:`set_n_initializer`.
          DGL still invokes :attr:`apply_node_func` if provided.
        * DGL recommends using DGL's bulit-in function for the :attr:`message_func`
          and the :attr:`reduce_func` arguments,
          because DGL will invoke efficient kernels that avoids copying node features to
          edge features in this case.
Mufei Li's avatar
Mufei Li committed
4661
4662
4663
4664
4665
4666
4667
4668

        Examples
        --------

        >>> import dgl
        >>> import dgl.function as fn
        >>> import torch

4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
        **Homogeneous graph**

        >>> g = dgl.graph(([0, 1, 2, 3], [1, 2, 3, 4]))
        >>> g.ndata['x'] = torch.ones(5, 2)
        >>> g.pull([0, 3, 4], fn.copy_u('x', 'm'), fn.sum('m', 'h'))
        >>> g.ndata['h']
        tensor([[0., 0.],
                [0., 0.],
                [0., 0.],
                [1., 1.],
                [1., 1.]])

        **Heterogeneous graph**
Mufei Li's avatar
Mufei Li committed
4682

4683
4684
4685
4686
        >>> g = dgl.heterograph({
        ...     ('user', 'follows', 'user'): ([0, 1], [1, 2]),
        ...     ('user', 'plays', 'game'): ([0, 2], [0, 1])
        ... })
Mufei Li's avatar
Mufei Li committed
4687
4688
4689
4690
4691
4692
4693
4694
4695
        >>> g.nodes['user'].data['h'] = torch.tensor([[0.], [1.], [2.]])

        Pull.

        >>> g['follows'].pull(2, fn.copy_src('h', 'm'), fn.sum('m', 'h'), etype='follows')
        >>> g.nodes['user'].data['h']
        tensor([[0.],
                [1.],
                [1.]])
Da Zheng's avatar
Da Zheng committed
4696
        """
4697
4698
        if inplace:
            raise DGLError('The `inplace` option is removed in v0.5.')
4699
        v = utils.prepare_tensor(self, v, 'v')
4700
        if len(v) == 0:
4701
            # no computation
4702
            return
4703
4704
4705
4706
4707
4708
        etid = self.get_etype_id(etype)
        _, dtid = self._graph.metagraph.find_edge(etid)
        etype = self.canonical_etypes[etid]
        g = self if etype is None else self[etype]
        # call message passing on subgraph
        src, dst, eid = g.in_edges(v, form='all')
4709
4710
4711
4712
        compute_graph, _, dstnodes, _ = _create_compute_graph(g, src, dst, eid, v)
        ndata = core.message_passing(
            compute_graph, message_func, reduce_func, apply_node_func)
        self._set_n_repr(dtid, dstnodes, ndata)
Minjie Wang's avatar
Minjie Wang committed
4713

Da Zheng's avatar
Da Zheng committed
4714
4715
    def push(self,
             u,
Minjie Wang's avatar
Minjie Wang committed
4716
4717
             message_func,
             reduce_func,
4718
             apply_node_func=None,
Minjie Wang's avatar
Minjie Wang committed
4719
             etype=None,
Da Zheng's avatar
Da Zheng committed
4720
             inplace=False):
4721
4722
        """Send message from the specified node(s) to their successors
        along the specified edge type and update their node features.
4723

Da Zheng's avatar
Da Zheng committed
4724
4725
        Parameters
        ----------
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
        v : node IDs
            The node IDs. The allowed formats are:

            * ``int``: A single node.
            * Int Tensor: Each element is a node ID. The tensor must have the same device type
              and ID data type as the graph's.
            * iterable[int]: Each element is a node ID.

        message_func : dgl.function.BuiltinFunction or callable
            The message function to generate messages along the edges.
            It must be either a :ref:`api-built-in` or a :ref:`apiudf`.
        reduce_func : dgl.function.BuiltinFunction or callable
            The reduce function to aggregate the messages.
            It must be either a :ref:`api-built-in` or a :ref:`apiudf`.
4740
        apply_node_func : callable, optional
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
            An optional apply function to further update the node features
            after the message reduction. It must be a :ref:`apiudf`.
        etype : str or (str, str, str), optional
            The type name of the edges. The allowed type name formats are:

            * ``(str, str, str)`` for source node type, edge type and destination node type.
            * or one ``str`` edge type name if the name can uniquely identify a
              triplet format in the graph.

            Can be omitted if the graph has only one type of edges.

Da Zheng's avatar
Da Zheng committed
4752
        inplace: bool, optional
4753
4754
4755
4756
4757
4758
4759
4760
            **DEPRECATED**.

        Notes
        -----
        DGL recommends using DGL's bulit-in function for the :attr:`message_func`
        and the :attr:`reduce_func` arguments,
        because DGL will invoke efficient kernels that avoids copying node features to
        edge features in this case.
Mufei Li's avatar
Mufei Li committed
4761
4762
4763
4764
4765
4766
4767
4768

        Examples
        --------

        >>> import dgl
        >>> import dgl.function as fn
        >>> import torch

4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
        **Homogeneous graph**

        >>> g = dgl.graph(([0, 1, 2, 3], [1, 2, 3, 4]))
        >>> g.ndata['x'] = torch.ones(5, 2)
        >>> g.push([0, 1], fn.copy_u('x', 'm'), fn.sum('m', 'h'))
        >>> g.ndata['h']
        tensor([[0., 0.],
                [1., 1.],
                [1., 1.],
                [0., 0.],
                [0., 0.]])

        **Heterogeneous graph**
Mufei Li's avatar
Mufei Li committed
4782

4783
        >>> g = dgl.heterograph({('user', 'follows', 'user'): ([0, 0], [1, 2])})
Mufei Li's avatar
Mufei Li committed
4784
4785
4786
4787
4788
4789
4790
4791
4792
        >>> g.nodes['user'].data['h'] = torch.tensor([[0.], [1.], [2.]])

        Push.

        >>> g['follows'].push(0, fn.copy_src('h', 'm'), fn.sum('m', 'h'), etype='follows')
        >>> g.nodes['user'].data['h']
        tensor([[0.],
                [0.],
                [0.]])
Da Zheng's avatar
Da Zheng committed
4793
        """
4794
4795
4796
4797
        if inplace:
            raise DGLError('The `inplace` option is removed in v0.5.')
        edges = self.out_edges(u, form='eid', etype=etype)
        self.send_and_recv(edges, message_func, reduce_func, apply_node_func, etype=etype)
Da Zheng's avatar
Da Zheng committed
4798
4799

    def update_all(self,
Minjie Wang's avatar
Minjie Wang committed
4800
4801
4802
4803
                   message_func,
                   reduce_func,
                   apply_node_func=None,
                   etype=None):
4804
4805
        """Send messages along all the edges of the specified type
        and update all the nodes of the corresponding destination type.
4806

4807
4808
4809
4810
        For heterogeneous graphs with number of relation types > 1, send messages
        along all the edges, reduce them by type-wisely and across different types
        at the same time. Then, update the node features of all the nodes.

Da Zheng's avatar
Da Zheng committed
4811
4812
        Parameters
        ----------
4813
4814
4815
4816
4817
4818
        message_func : dgl.function.BuiltinFunction or callable
            The message function to generate messages along the edges.
            It must be either a :ref:`api-built-in` or a :ref:`apiudf`.
        reduce_func : dgl.function.BuiltinFunction or callable
            The reduce function to aggregate the messages.
            It must be either a :ref:`api-built-in` or a :ref:`apiudf`.
4819
        apply_node_func : callable, optional
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
            An optional apply function to further update the node features
            after the message reduction. It must be a :ref:`apiudf`.
        etype : str or (str, str, str), optional
            The type name of the edges. The allowed type name formats are:

            * ``(str, str, str)`` for source node type, edge type and destination node type.
            * or one ``str`` edge type name if the name can uniquely identify a
              triplet format in the graph.

            Can be omitted if the graph has only one type of edges.

        Notes
        -----
        * If some of the nodes in the graph has no in-edges, DGL does not invoke
          message and reduce functions for these nodes and fill their aggregated messages
          with zero. Users can control the filled values via :meth:`set_n_initializer`.
          DGL still invokes :attr:`apply_node_func` if provided.
        * DGL recommends using DGL's bulit-in function for the :attr:`message_func`
          and the :attr:`reduce_func` arguments,
          because DGL will invoke efficient kernels that avoids copying node features to
          edge features in this case.
Mufei Li's avatar
Mufei Li committed
4841
4842
4843
4844
4845

        Examples
        --------
        >>> import dgl
        >>> import dgl.function as fn
4846
        >>> import torch
Mufei Li's avatar
Mufei Li committed
4847

4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
        **Homogeneous graph**

        >>> g = dgl.graph(([0, 1, 2, 3], [1, 2, 3, 4]))
        >>> g.ndata['x'] = torch.ones(5, 2)
        >>> g.update_all(fn.copy_u('x', 'm'), fn.sum('m', 'h'))
        >>> g.ndata['h']
        tensor([[0., 0.],
                [1., 1.],
                [1., 1.],
                [1., 1.],
                [1., 1.]])

        **Heterogeneous graph**
Mufei Li's avatar
Mufei Li committed
4861

4862
        >>> g = dgl.heterograph({('user', 'follows', 'user'): ([0, 1, 2], [1, 2, 2])})
Mufei Li's avatar
Mufei Li committed
4863
4864
4865
4866
4867
4868
4869
4870
4871

        Update all.

        >>> g.nodes['user'].data['h'] = torch.tensor([[0.], [1.], [2.]])
        >>> g['follows'].update_all(fn.copy_src('h', 'm'), fn.sum('m', 'h'), etype='follows')
        >>> g.nodes['user'].data['h']
        tensor([[0.],
                [0.],
                [3.]])
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887

        **Heterogenenous graph (number relation types > 1)**

        >>> g = dgl.heterograph({
        ...     ('user', 'follows', 'user'): ([0, 1], [1, 1]),
        ...     ('game', 'attracts', 'user'): ([0], [1])
        ... })

        Update all.

        >>> g.nodes['user'].data['h'] = torch.tensor([[1.], [2.]])
        >>> g.nodes['game'].data['h'] = torch.tensor([[1.]])
        >>> g.update_all(fn.copy_src('h', 'm'), fn.sum('m', 'h'))
        >>> g.nodes['user'].data['h']
        tensor([[0.],
                [4.]])
Da Zheng's avatar
Da Zheng committed
4888
        """
4889
4890
4891
4892
4893
4894
4895
        # Graph with one relation type
        if self._graph.number_of_etypes() == 1 or etype is not None:
            etid = self.get_etype_id(etype)
            etype = self.canonical_etypes[etid]
            _, dtid = self._graph.metagraph.find_edge(etid)
            g = self if etype is None else self[etype]
            ndata = core.message_passing(g, message_func, reduce_func, apply_node_func)
4896
4897
4898
4899
            if core.is_builtin(reduce_func) and reduce_func.name in ['min', 'max'] and ndata:
                # Replace infinity with zero for isolated nodes
                key = list(ndata.keys())[0]
                ndata[key] = F.replace_inf_with_zero(ndata[key])
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
            self._set_n_repr(dtid, ALL, ndata)
        else:   # heterogeneous graph with number of relation types > 1
            if not core.is_builtin(message_func) or not core.is_builtin(reduce_func):
                raise DGLError("User defined functions are not yet "
                               "supported in update_all for heterogeneous graphs. "
                               "Please use multi_update_all instead.")
            if reduce_func.name in ['mean']:
                raise NotImplementedError("Cannot set both intra-type and inter-type reduce "
                                          "operators as 'mean' using update_all. Please use "
                                          "multi_update_all instead.")
            g = self
            all_out = core.message_passing(g, message_func, reduce_func, apply_node_func)
            key = list(all_out.keys())[0]
            out_tensor_tuples = all_out[key]

            dst_tensor = {}
            for _, _, dsttype in g.canonical_etypes:
                dtid = g.get_ntype_id(dsttype)
                dst_tensor[key] = out_tensor_tuples[dtid]
4919
4920
                if core.is_builtin(reduce_func) and reduce_func.name in ['min', 'max']:
                    dst_tensor[key] = F.replace_inf_with_zero(dst_tensor[key])
4921
                self._node_frames[dtid].update(dst_tensor)
4922

4923
4924
4925
    #################################################################
    # Message passing on heterograph
    #################################################################
Da Zheng's avatar
Da Zheng committed
4926

Mufei Li's avatar
Mufei Li committed
4927
    def multi_update_all(self, etype_dict, cross_reducer, apply_node_func=None):
4928
4929
4930
        r"""Send messages along all the edges, reduce them by first type-wisely
        then across different types, and then update the node features of all
        the nodes.
Da Zheng's avatar
Da Zheng committed
4931
4932
4933

        Parameters
        ----------
Mufei Li's avatar
Mufei Li committed
4934
        etype_dict : dict
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
            Arguments for edge-type-wise message passing. The keys are edge types
            while the values are message passing arguments.

            The allowed key formats are:

            * ``(str, str, str)`` for source node type, edge type and destination node type.
            * or one ``str`` edge type name if the name can uniquely identify a
              triplet format in the graph.

            The value must be a tuple ``(message_func, reduce_func, [apply_node_func])``, where

            * message_func : dgl.function.BuiltinFunction or callable
                The message function to generate messages along the edges.
                It must be either a :ref:`api-built-in` or a :ref:`apiudf`.
            * reduce_func : dgl.function.BuiltinFunction or callable
                The reduce function to aggregate the messages.
                It must be either a :ref:`api-built-in` or a :ref:`apiudf`.
Mufei Li's avatar
Mufei Li committed
4952
            * apply_node_func : callable, optional
4953
4954
4955
                An optional apply function to further update the node features
                after the message reduction. It must be a :ref:`apiudf`.

4956
4957
4958
4959
4960
        cross_reducer : str or callable function
            Cross type reducer. One of ``"sum"``, ``"min"``, ``"max"``, ``"mean"``, ``"stack"``
            or a callable function. If a callable function is provided, the input argument must be
            a single list of tensors containing aggregation results from each edge type, and the
            output of function must be a single tensor.
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
        apply_node_func : callable, optional
            An optional apply function after the messages are reduced both
            type-wisely and across different types.
            It must be a :ref:`apiudf`.

        Notes
        -----
        DGL recommends using DGL's bulit-in function for the message_func
        and the reduce_func in the type-wise message passing arguments,
        because DGL will invoke efficient kernels that avoids copying node features to
        edge features in this case.

Mufei Li's avatar
Mufei Li committed
4973
4974
4975
4976
4977
4978
4979
4980
4981

        Examples
        --------
        >>> import dgl
        >>> import dgl.function as fn
        >>> import torch

        Instantiate a heterograph.

4982
4983
4984
4985
        >>> g = dgl.heterograph({
        ...     ('user', 'follows', 'user'): ([0, 1], [1, 1]),
        ...     ('game', 'attracts', 'user'): ([0], [1])
        ... })
Mufei Li's avatar
Mufei Li committed
4986
4987
4988
4989
4990
4991
        >>> g.nodes['user'].data['h'] = torch.tensor([[1.], [2.]])
        >>> g.nodes['game'].data['h'] = torch.tensor([[1.]])

        Update all.

        >>> g.multi_update_all(
4992
4993
4994
        ...     {'follows': (fn.copy_src('h', 'm'), fn.sum('m', 'h')),
        ...      'attracts': (fn.copy_src('h', 'm'), fn.sum('m', 'h'))},
        ... "sum")
Mufei Li's avatar
Mufei Li committed
4995
4996
4997
        >>> g.nodes['user'].data['h']
        tensor([[0.],
                [4.]])
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009

        User-defined cross reducer equivalent to "sum".

        >>> def cross_sum(flist):
        ...     return torch.sum(torch.stack(flist, dim=0), dim=0) if len(flist) > 1 else flist[0]

        Use the user-defined cross reducer.

        >>> g.multi_update_all(
        ...     {'follows': (fn.copy_src('h', 'm'), fn.sum('m', 'h')),
        ...      'attracts': (fn.copy_src('h', 'm'), fn.sum('m', 'h'))},
        ... cross_sum)
Mufei Li's avatar
Mufei Li committed
5010
        """
Minjie Wang's avatar
Minjie Wang committed
5011
        all_out = defaultdict(list)
5012
        merge_order = defaultdict(list)
5013
        for etype, args in etype_dict.items():
5014

5015
5016
5017
5018
5019
5020
5021
            etid = self.get_etype_id(etype)
            _, dtid = self._graph.metagraph.find_edge(etid)
            args = pad_tuple(args, 3)
            if args is None:
                raise DGLError('Invalid arguments for edge type "{}". Should be '
                               '(msg_func, reduce_func, [apply_node_func])'.format(etype))
            mfunc, rfunc, afunc = args
5022
5023
            g = self if etype is None else self[etype]
            all_out[dtid].append(core.message_passing(g, mfunc, rfunc, afunc))
5024
            merge_order[dtid].append(etid)  # use edge type id as merge order hint
Minjie Wang's avatar
Minjie Wang committed
5025
5026
        for dtid, frames in all_out.items():
            # merge by cross_reducer
5027
5028
5029
5030
5031
5032
            out = reduce_dict_data(frames, cross_reducer, merge_order[dtid])
            # Replace infinity with zero for isolated nodes when reducer is min/max
            if  core.is_builtin(rfunc) and rfunc.name in ['min', 'max']:
                key = list(out.keys())[0]
                out[key] = F.replace_inf_with_zero(out[key]) if out[key] is not None else None
            self._node_frames[dtid].update(out)
Minjie Wang's avatar
Minjie Wang committed
5033
            # apply
Mufei Li's avatar
Mufei Li committed
5034
            if apply_node_func is not None:
5035
5036
                self.apply_nodes(apply_node_func, ALL, self.ntypes[dtid])

5037

5038

5039
5040
5041
    #################################################################
    # Message propagation
    #################################################################
Minjie Wang's avatar
Minjie Wang committed
5042
5043
5044
5045
5046
5047
5048

    def prop_nodes(self,
                   nodes_generator,
                   message_func,
                   reduce_func,
                   apply_node_func=None,
                   etype=None):
Mufei Li's avatar
Mufei Li committed
5049
        """Propagate messages using graph traversal by sequentially triggering
Minjie Wang's avatar
Minjie Wang committed
5050
5051
5052
5053
5054
5055
        :func:`pull()` on nodes.

        The traversal order is specified by the ``nodes_generator``. It generates
        node frontiers, which is a list or a tensor of nodes. The nodes in the
        same frontier will be triggered together, while nodes in different frontiers
        will be triggered according to the generating order.
Da Zheng's avatar
Da Zheng committed
5056
5057
5058

        Parameters
        ----------
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
        nodes_generator : iterable[node IDs]
            The generator of node frontiers. Each frontier is a set of node IDs
            stored in Tensor or python iterables.
            It specifies which nodes perform :func:`pull` at each step.
        message_func : dgl.function.BuiltinFunction or callable
            The message function to generate messages along the edges.
            It must be either a :ref:`api-built-in` or a :ref:`apiudf`.
        reduce_func : dgl.function.BuiltinFunction or callable
            The reduce function to aggregate the messages.
            It must be either a :ref:`api-built-in` or a :ref:`apiudf`.
Minjie Wang's avatar
Minjie Wang committed
5069
        apply_node_func : callable, optional
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
            An optional apply function to further update the node features
            after the message reduction. It must be a :ref:`apiudf`.
        etype : str or (str, str, str), optional
            The type name of the edges. The allowed type name formats are:

            * ``(str, str, str)`` for source node type, edge type and destination node type.
            * or one ``str`` edge type name if the name can uniquely identify a
              triplet format in the graph.

            Can be omitted if the graph has only one type of edges.
Mufei Li's avatar
Mufei Li committed
5080
5081
5082
5083
5084
5085
5086
5087
5088

        Examples
        --------
        >>> import torch
        >>> import dgl
        >>> import dgl.function as fn

        Instantiate a heterogrph and perform multiple rounds of message passing.

5089
        >>> g = dgl.heterograph({('user', 'follows', 'user'): ([0, 1, 2, 3], [2, 3, 4, 4])})
Mufei Li's avatar
Mufei Li committed
5090
5091
        >>> g.nodes['user'].data['h'] = torch.tensor([[1.], [2.], [3.], [4.], [5.]])
        >>> g['follows'].prop_nodes([[2, 3], [4]], fn.copy_src('h', 'm'),
5092
        ...                         fn.sum('m', 'h'), etype='follows')
Mufei Li's avatar
Mufei Li committed
5093
5094
5095
5096
5097
        tensor([[1.],
                [2.],
                [1.],
                [2.],
                [3.]])
Da Zheng's avatar
Da Zheng committed
5098

Minjie Wang's avatar
Minjie Wang committed
5099
5100
5101
        See Also
        --------
        prop_edges
Da Zheng's avatar
Da Zheng committed
5102
        """
Minjie Wang's avatar
Minjie Wang committed
5103
5104
        for node_frontier in nodes_generator:
            self.pull(node_frontier, message_func, reduce_func, apply_node_func, etype=etype)
Da Zheng's avatar
Da Zheng committed
5105

Minjie Wang's avatar
Minjie Wang committed
5106
5107
5108
5109
5110
5111
    def prop_edges(self,
                   edges_generator,
                   message_func,
                   reduce_func,
                   apply_node_func=None,
                   etype=None):
Mufei Li's avatar
Mufei Li committed
5112
        """Propagate messages using graph traversal by sequentially triggering
Minjie Wang's avatar
Minjie Wang committed
5113
        :func:`send_and_recv()` on edges.
Da Zheng's avatar
Da Zheng committed
5114

Minjie Wang's avatar
Minjie Wang committed
5115
5116
5117
        The traversal order is specified by the ``edges_generator``. It generates
        edge frontiers. The edge frontiers should be of *valid edges type*.
        See :func:`send` for more details.
Da Zheng's avatar
Da Zheng committed
5118

Mufei Li's avatar
Mufei Li committed
5119
        Edges in the same frontier will be triggered together, and edges in
Minjie Wang's avatar
Minjie Wang committed
5120
        different frontiers will be triggered according to the generating order.
Da Zheng's avatar
Da Zheng committed
5121
5122
5123

        Parameters
        ----------
Minjie Wang's avatar
Minjie Wang committed
5124
5125
        edges_generator : generator
            The generator of edge frontiers.
5126
5127
5128
5129
5130
5131
        message_func : dgl.function.BuiltinFunction or callable
            The message function to generate messages along the edges.
            It must be either a :ref:`api-built-in` or a :ref:`apiudf`.
        reduce_func : dgl.function.BuiltinFunction or callable
            The reduce function to aggregate the messages.
            It must be either a :ref:`api-built-in` or a :ref:`apiudf`.
Minjie Wang's avatar
Minjie Wang committed
5132
        apply_node_func : callable, optional
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
            An optional apply function to further update the node features
            after the message reduction. It must be a :ref:`apiudf`.
        etype : str or (str, str, str), optional
            The type name of the edges. The allowed type name formats are:

            * ``(str, str, str)`` for source node type, edge type and destination node type.
            * or one ``str`` edge type name if the name can uniquely identify a
              triplet format in the graph.

            Can be omitted if the graph has only one type of edges.
Mufei Li's avatar
Mufei Li committed
5143
5144
5145
5146
5147
5148
5149
5150
5151

        Examples
        --------
        >>> import torch
        >>> import dgl
        >>> import dgl.function as fn

        Instantiate a heterogrph and perform multiple rounds of message passing.

5152
        >>> g = dgl.heterograph({('user', 'follows', 'user'): ([0, 1, 2, 3], [2, 3, 4, 4])})
Mufei Li's avatar
Mufei Li committed
5153
5154
        >>> g.nodes['user'].data['h'] = torch.tensor([[1.], [2.], [3.], [4.], [5.]])
        >>> g['follows'].prop_edges([[0, 1], [2, 3]], fn.copy_src('h', 'm'),
5155
        ...                         fn.sum('m', 'h'), etype='follows')
Mufei Li's avatar
Mufei Li committed
5156
5157
5158
5159
5160
5161
        >>> g.nodes['user'].data['h']
        tensor([[1.],
                [2.],
                [1.],
                [2.],
                [3.]])
Da Zheng's avatar
Da Zheng committed
5162

Minjie Wang's avatar
Minjie Wang committed
5163
5164
5165
        See Also
        --------
        prop_nodes
Da Zheng's avatar
Da Zheng committed
5166
        """
Minjie Wang's avatar
Minjie Wang committed
5167
5168
5169
        for edge_frontier in edges_generator:
            self.send_and_recv(edge_frontier, message_func, reduce_func,
                               apply_node_func, etype=etype)
Da Zheng's avatar
Da Zheng committed
5170

Minjie Wang's avatar
Minjie Wang committed
5171
5172
5173
    #################################################################
    # Misc
    #################################################################
Da Zheng's avatar
Da Zheng committed
5174

Minjie Wang's avatar
Minjie Wang committed
5175
    def filter_nodes(self, predicate, nodes=ALL, ntype=None):
5176
        """Return the IDs of the nodes with the given node type that satisfy
Da Zheng's avatar
Da Zheng committed
5177
5178
5179
5180
5181
        the given predicate.

        Parameters
        ----------
        predicate : callable
5182
5183
5184
            A function of signature ``func(nodes) -> Tensor``.
            ``nodes`` are :class:`dgl.NodeBatch` objects.
            Its output tensor should be a 1D boolean tensor with
Da Zheng's avatar
Da Zheng committed
5185
5186
            each element indicating whether the corresponding node in
            the batch satisfies the predicate.
5187
5188
5189
5190
5191
5192
5193
5194
5195
        nodes : node ID(s), optional
            The node(s) for query. The allowed formats are:

            - Tensor: A 1D tensor that contains the node(s) for query, whose data type
              and device should be the same as the :py:attr:`idtype` and device of the graph.
            - iterable[int] : Similar to the tensor, but stores node IDs in a sequence
              (e.g. list, tuple, numpy.ndarray).

            By default, it considers all nodes.
Minjie Wang's avatar
Minjie Wang committed
5196
        ntype : str, optional
5197
5198
            The node type for query. If the graph has multiple node types, one must
            specify the argument. Otherwise, it can be omitted.
Da Zheng's avatar
Da Zheng committed
5199
5200
5201

        Returns
        -------
5202
        Tensor
5203
            A 1D tensor that contains the ID(s) of the node(s) that satisfy the predicate.
Mufei Li's avatar
Mufei Li committed
5204
5205
5206

        Examples
        --------
5207
5208
5209

        The following example uses PyTorch backend.

Mufei Li's avatar
Mufei Li committed
5210
        >>> import dgl
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
        >>> import torch

        Define a predicate function.

        >>> def nodes_with_feature_one(nodes):
        ...     # Whether a node has feature 1
        ...     return (nodes.data['h'] == 1.).squeeze(1)

        Filter nodes for a homogeneous graph.

        >>> g = dgl.graph((torch.tensor([0, 1, 2]), torch.tensor([1, 2, 3])))
        >>> g.ndata['h'] = torch.tensor([[0.], [1.], [1.], [0.]])
        >>> print(g.filter_nodes(nodes_with_feature_one))
        tensor([1, 2])

        Filter on nodes with IDs 0 and 1

        >>> print(g.filter_nodes(nodes_with_feature_one, nodes=torch.tensor([0, 1])))
        tensor([1])

        Filter nodes for a heterogeneous graph.

        >>> g = dgl.heterograph({
        ...     ('user', 'plays', 'game'): (torch.tensor([0, 1, 1, 2]),
        ...                                 torch.tensor([0, 0, 1, 1]))})
        >>> g.nodes['user'].data['h'] = torch.tensor([[0.], [1.], [1.]])
        >>> g.nodes['game'].data['h'] = torch.tensor([[0.], [1.]])
        >>> # Filter for 'user' nodes
        >>> print(g.filter_nodes(nodes_with_feature_one, ntype='user'))
Mufei Li's avatar
Mufei Li committed
5240
        tensor([1, 2])
Da Zheng's avatar
Da Zheng committed
5241
        """
5242
5243
5244
5245
5246
5247
        if is_all(nodes):
            nodes = self.nodes(ntype)
        v = utils.prepare_tensor(self, nodes, 'nodes')
        if F.as_scalar(F.sum(self.has_nodes(v, ntype=ntype), dim=0)) != len(v):
            raise DGLError('v contains invalid node IDs')

5248
5249
5250
5251
5252
5253
5254
        with self.local_scope():
            self.apply_nodes(lambda nbatch: {'_mask' : predicate(nbatch)}, nodes, ntype)
            ntype = self.ntypes[0] if ntype is None else ntype
            mask = self.nodes[ntype].data['_mask']
            if is_all(nodes):
                return F.nonzero_1d(mask)
            else:
5255
                return F.boolean_mask(v, F.gather_row(mask, v))
Minjie Wang's avatar
Minjie Wang committed
5256
5257

    def filter_edges(self, predicate, edges=ALL, etype=None):
5258
        """Return the IDs of the edges with the given edge type that satisfy
Da Zheng's avatar
Da Zheng committed
5259
5260
5261
5262
5263
        the given predicate.

        Parameters
        ----------
        predicate : callable
5264
5265
5266
            A function of signature ``func(edges) -> Tensor``.
            ``edges`` are :class:`dgl.EdgeBatch` objects.
            Its output tensor should be a 1D boolean tensor with
Da Zheng's avatar
Da Zheng committed
5267
5268
            each element indicating whether the corresponding edge in
            the batch satisfies the predicate.
5269
5270
        edges : edges
            The edges to send and receive messages on. The allowed input formats are:
5271

5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
            * ``int``: A single edge ID.
            * Int Tensor: Each element is an edge ID.  The tensor must have the same device type
              and ID data type as the graph's.
            * iterable[int]: Each element is an edge ID.
            * (Tensor, Tensor): The node-tensors format where the i-th elements
              of the two tensors specify an edge.
            * (iterable[int], iterable[int]): Similar to the node-tensors format but
              stores edge endpoints in python iterables.

            By default, it considers all the edges.
        etype : str or (str, str, str), optional
            The type name of the edges. The allowed type name formats are:

            * ``(str, str, str)`` for source node type, edge type and destination node type.
            * or one ``str`` edge type name if the name can uniquely identify a
              triplet format in the graph.

            Can be omitted if the graph has only one type of edges.
Da Zheng's avatar
Da Zheng committed
5290
5291
5292

        Returns
        -------
5293
        Tensor
5294
            A 1D tensor that contains the ID(s) of the edge(s) that satisfy the predicate.
Mufei Li's avatar
Mufei Li committed
5295
5296
5297

        Examples
        --------
5298
5299
5300

        The following example uses PyTorch backend.

Mufei Li's avatar
Mufei Li committed
5301
        >>> import dgl
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
        >>> import torch

        Define a predicate function.

        >>> def edges_with_feature_one(edges):
        ...     # Whether an edge has feature 1
        ...     return (edges.data['h'] == 1.).squeeze(1)

        Filter edges for a homogeneous graph.

        >>> g = dgl.graph((torch.tensor([0, 1, 2]), torch.tensor([1, 2, 3])))
        >>> g.edata['h'] = torch.tensor([[0.], [1.], [1.]])
        >>> print(g.filter_edges(edges_with_feature_one))
        tensor([1, 2])

        Filter on edges with IDs 0 and 1

        >>> print(g.filter_edges(edges_with_feature_one, edges=torch.tensor([0, 1])))
        tensor([1])

        Filter edges for a heterogeneous graph.

        >>> g = dgl.heterograph({
        ...     ('user', 'plays', 'game'): (torch.tensor([0, 1, 1, 2]),
        ...                                 torch.tensor([0, 0, 1, 1])),
        ...     ('user', 'follows', 'user'): (torch.tensor([0, 1]), torch.tensor([1, 2]))})
        >>> g.edges['plays'].data['h'] = torch.tensor([[0.], [1.], [1.], [0.]])
        >>> # Filter for 'plays' nodes
        >>> print(g.filter_edges(edges_with_feature_one, etype='plays'))
Mufei Li's avatar
Mufei Li committed
5331
        tensor([1, 2])
Da Zheng's avatar
Da Zheng committed
5332
        """
5333
5334
5335
5336
5337
5338
5339
5340
5341
5342
5343
5344
5345
5346
5347
5348
5349
5350
5351
5352
5353
5354
        if is_all(edges):
            pass
        elif isinstance(edges, tuple):
            u, v = edges
            srctype, _, dsttype = self.to_canonical_etype(etype)
            u = utils.prepare_tensor(self, u, 'u')
            if F.as_scalar(F.sum(self.has_nodes(u, ntype=srctype), dim=0)) != len(u):
                raise DGLError('edges[0] contains invalid node IDs')
            v = utils.prepare_tensor(self, v, 'v')
            if F.as_scalar(F.sum(self.has_nodes(v, ntype=dsttype), dim=0)) != len(v):
                raise DGLError('edges[1] contains invalid node IDs')
        elif isinstance(edges, Iterable) or F.is_tensor(edges):
            edges = utils.prepare_tensor(self, edges, 'edges')
            min_eid = F.as_scalar(F.min(edges, 0))
            if len(edges) > 0 > min_eid:
                raise DGLError('Invalid edge ID {:d}'.format(min_eid))
            max_eid = F.as_scalar(F.max(edges, 0))
            if len(edges) > 0 and max_eid >= self.num_edges(etype):
                raise DGLError('Invalid edge ID {:d}'.format(max_eid))
        else:
            raise ValueError('Unsupported type of edges:', type(edges))

5355
5356
5357
5358
5359
5360
5361
5362
5363
5364
5365
        with self.local_scope():
            self.apply_edges(lambda ebatch: {'_mask' : predicate(ebatch)}, edges, etype)
            etype = self.canonical_etypes[0] if etype is None else etype
            mask = self.edges[etype].data['_mask']
            if is_all(edges):
                return F.nonzero_1d(mask)
            else:
                if isinstance(edges, tuple):
                    e = self.edge_ids(edges[0], edges[1], etype=etype)
                else:
                    e = utils.prepare_tensor(self, edges, 'edges')
5366
                return F.boolean_mask(e, F.gather_row(mask, e))
Minjie Wang's avatar
Minjie Wang committed
5367

5368
5369
    @property
    def device(self):
5370
5371
5372
5373
5374
5375
5376
        """Get the device of the graph.

        Returns
        -------
        device context
            The device of the graph, which should be a framework-specific device object
            (e.g., ``torch.device``).
5377
5378
5379
5380
5381

        Examples
        --------
        The following example uses PyTorch backend.

5382
5383
5384
5385
5386
5387
        >>> import dgl
        >>> import torch

        Create a homogeneous graph for demonstration.

        >>> g = dgl.graph((torch.tensor([0, 1]), torch.tensor([1, 2])))
5388
5389
5390
        >>> print(g.device)
        device(type='cpu')

5391
        The case of heterogeneous graphs is the same.
5392
5393
5394
        """
        return F.to_backend_ctx(self._graph.ctx)

5395
5396
    def to(self, device, **kwargs):  # pylint: disable=invalid-name
        """Move ndata, edata and graph structure to the targeted device (cpu/gpu).
Da Zheng's avatar
Da Zheng committed
5397

5398
5399
5400
        If the graph is already on the specified device, the function directly returns it.
        Otherwise, it returns a cloned graph on the specified device.

Da Zheng's avatar
Da Zheng committed
5401
5402
        Parameters
        ----------
5403
        device : Framework-specific device context object
5404
            The context to move data to (e.g., ``torch.device``).
5405
5406
        kwargs : Key-word arguments.
            Key-word arguments fed to the framework copy function.
Minjie Wang's avatar
Minjie Wang committed
5407

5408
5409
        Returns
        -------
5410
5411
        DGLGraph
            The graph on the specified device.
5412

Minjie Wang's avatar
Minjie Wang committed
5413
5414
5415
5416
        Examples
        --------
        The following example uses PyTorch backend.

5417
        >>> import dgl
Minjie Wang's avatar
Minjie Wang committed
5418
        >>> import torch
5419
5420
5421
5422

        >>> g = dgl.graph((torch.tensor([1, 0]), torch.tensor([1, 2])))
        >>> g.ndata['h'] = torch.ones(3, 1)
        >>> g.edata['h'] = torch.zeros(2, 2)
5423
5424
5425
        >>> g1 = g.to(torch.device('cuda:0'))
        >>> print(g1.device)
        device(type='cuda', index=0)
5426
5427
5428
5429
5430
5431
5432
        >>> print(g1.ndata['h'].device)
        device(type='cuda', index=0)
        >>> print(g1.nodes().device)
        device(type='cuda', index=0)

        The original graph is still on CPU.

5433
5434
        >>> print(g.device)
        device(type='cpu')
5435
5436
5437
5438
5439
5440
        >>> print(g.ndata['h'].device)
        device(type='cpu')
        >>> print(g.nodes().device)
        device(type='cpu')

        The case of heterogeneous graphs is the same.
Da Zheng's avatar
Da Zheng committed
5441
        """
5442
        if device is None or self.device == device:
5443
            return self
5444
5445
5446
5447
5448
5449
5450
5451

        ret = copy.copy(self)

        # 1. Copy graph structure
        ret._graph = self._graph.copy_to(utils.to_dgl_context(device))

        # 2. Copy features
        # TODO(minjie): handle initializer
5452
5453
        new_nframes = []
        for nframe in self._node_frames:
5454
            new_nframes.append(nframe.to(device, **kwargs))
5455
5456
        ret._node_frames = new_nframes

5457
5458
        new_eframes = []
        for eframe in self._edge_frames:
5459
            new_eframes.append(eframe.to(device, **kwargs))
5460
5461
5462
5463
5464
5465
5466
5467
5468
5469
5470
5471
5472
5473
5474
5475
5476
5477
5478
        ret._edge_frames = new_eframes

        # 2. Copy misc info
        if self._batch_num_nodes is not None:
            new_bnn = {k : F.copy_to(num, device, **kwargs)
                       for k, num in self._batch_num_nodes.items()}
            ret._batch_num_nodes = new_bnn
        if self._batch_num_edges is not None:
            new_bne = {k : F.copy_to(num, device, **kwargs)
                       for k, num in self._batch_num_edges.items()}
            ret._batch_num_edges = new_bne

        return ret

    def cpu(self):
        """Return a new copy of this graph on CPU.

        Returns
        -------
peizhou001's avatar
peizhou001 committed
5479
        DGLGraph
5480
5481
5482
5483
5484
5485
5486
5487
            Graph on CPU.

        See Also
        --------
        to
        """
        return self.to(F.cpu())

5488
    def pin_memory_(self):
5489
5490
        """Pin the graph structure and node/edge data to the page-locked memory for
        GPU zero-copy access.
5491
5492
5493
5494
5495
5496

        This is an **inplace** method. The graph structure must be on CPU to be pinned.
        If the graph struture is already pinned, the function directly returns it.

        Materialization of new sparse formats for pinned graphs is not allowed.
        To avoid implicit formats materialization during training,
5497
        you should create all the needed formats before pinning.
5498
5499
5500
5501
5502
5503
5504
5505
5506
5507
5508
5509
5510
5511
5512
5513
5514
5515
5516
5517
5518
5519
5520
5521
5522
        But cloning and materialization is fine. See the examples below.

        Returns
        -------
        DGLGraph
            The pinned graph.

        Examples
        --------
        The following example uses PyTorch backend.

        >>> import dgl
        >>> import torch

        >>> g = dgl.graph((torch.tensor([1, 0]), torch.tensor([1, 2])))
        >>> g.pin_memory_()

        Materialization of new sparse formats is not allowed for pinned graphs.

        >>> g.create_formats_()  # This would raise an error! You should do this before pinning.

        Cloning and materializing new formats is allowed. The returned graph is **not** pinned.

        >>> g1 = g.formats(['csc'])
        >>> assert not g1.is_pinned()
5523
5524
5525
5526
5527
5528
5529
5530
5531
5532
5533
5534
5535
5536
5537
5538
5539
5540
5541
5542
5543
5544
5545
5546

        The pinned graph can be access from both CPU and GPU. The concrete device depends
        on the context of ``query``. For example, ``eid`` in ``find_edges()`` is a query.
        When ``eid`` is on CPU, ``find_edges()`` is executed on CPU, and the returned
        values are CPU tensors

        >>> g.unpin_memory_()
        >>> g.create_formats_()
        >>> g.pin_memory_()
        >>> eid = torch.tensor([1])
        >>> g.find_edges(eids)
        (tensor([0]), tensor([2]))

        Moving ``eid`` to GPU, ``find_edges()`` will be executed on GPU, and the returned
        values are GPU tensors.

        >>> eid = eid.to('cuda:0')
        >>> g.find_edges(eids)
        (tensor([0], device='cuda:0'), tensor([2], device='cuda:0'))

        If you don't provide a ``query``, methods will be executed on CPU by default.

        >>> g.in_degrees()
        tensor([0, 1, 1])
5547
        """
5548
5549
5550
5551
        if not self._graph.is_pinned():
            if F.device_type(self.device) != 'cpu':
                raise DGLError("The graph structure must be on CPU to be pinned.")
            self._graph.pin_memory_()
5552
5553
5554
        for frame in itertools.chain(self._node_frames, self._edge_frames):
            for col in frame._columns.values():
                col.pin_memory_()
5555

5556
5557
5558
        return self

    def unpin_memory_(self):
5559
        """Unpin the graph structure and node/edge data from the page-locked memory.
5560

5561
        This is an **inplace** method. If the graph struture is not pinned,
5562
5563
5564
5565
5566
5567
5568
        e.g., on CPU or GPU, the function directly returns it.

        Returns
        -------
        DGLGraph
            The unpinned graph.
        """
5569
5570
        if self._graph.is_pinned():
            self._graph.unpin_memory_()
5571
5572
5573
        for frame in itertools.chain(self._node_frames, self._edge_frames):
            for col in frame._columns.values():
                col.unpin_memory_()
5574

5575
5576
5577
5578
5579
5580
5581
5582
5583
5584
5585
5586
        return self

    def is_pinned(self):
        """Check if the graph structure is pinned to the page-locked memory.

        Returns
        -------
        bool
            True if the graph structure is pinned.
        """
        return self._graph.is_pinned()

5587
5588
5589
5590
5591
5592
5593
5594
5595
5596
5597
5598
5599
5600
5601
5602
5603
5604
5605
5606
5607
5608
5609
5610
5611
    def record_stream(self, stream):
        """Record the stream that is using this graph.
        This method only supports the PyTorch backend and requires graphs on the GPU.

        Parameters
        ----------
        stream : torch.cuda.Stream
            The stream that is using this graph.

        Returns
        -------
        DGLGraph
            self.
        """
        if F.get_preferred_backend() != 'pytorch':
            raise DGLError("record_stream only support the PyTorch backend.")
        if F.device_type(self.device) != 'cuda':
            raise DGLError("The graph must be on GPU to be recorded.")
        self._graph.record_stream(stream)
        for frame in itertools.chain(self._node_frames, self._edge_frames):
            for col in frame._columns.values():
                col.record_stream(stream)

        return self

5612
5613
5614
5615
5616
    def clone(self):
        """Return a heterograph object that is a clone of current graph.

        Returns
        -------
peizhou001's avatar
peizhou001 committed
5617
        DGLGraph
5618
5619
5620
5621
5622
5623
5624
5625
5626
5627
5628
5629
5630
5631
5632
5633
5634
5635
5636
5637
5638
5639
5640
            The graph object that is a clone of current graph.
        """
        # XXX(minjie): Do a shallow copy first to clone some internal metagraph information.
        #   Not a beautiful solution though.
        ret = copy.copy(self)

        # Clone the graph structure
        meta_edges = []
        for s_ntype, _, d_ntype in self.canonical_etypes:
            meta_edges.append((self.get_ntype_id(s_ntype), self.get_ntype_id(d_ntype)))

        metagraph = graph_index.from_edge_list(meta_edges, True)
        # rebuild graph idx
        num_nodes_per_type = [self.number_of_nodes(c_ntype) for c_ntype in self.ntypes]
        relation_graphs = [self._graph.get_relation_graph(self.get_etype_id(c_etype))
                           for c_etype in self.canonical_etypes]
        ret._graph = heterograph_index.create_heterograph_from_relations(
            metagraph, relation_graphs, utils.toindex(num_nodes_per_type, "int64"))

        # Clone the frames
        ret._node_frames = [fr.clone() for fr in self._node_frames]
        ret._edge_frames = [fr.clone() for fr in self._edge_frames]

5641
5642
5643
5644
        # Copy the batch information
        ret._batch_num_nodes = copy.copy(self._batch_num_nodes)
        ret._batch_num_edges = copy.copy(self._batch_num_edges)

5645
        return ret
Da Zheng's avatar
Da Zheng committed
5646

Minjie Wang's avatar
Minjie Wang committed
5647
    def local_var(self):
5648
        """Return a graph object for usage in a local function scope.
Minjie Wang's avatar
Minjie Wang committed
5649
5650
5651

        The returned graph object shares the feature data and graph structure of this graph.
        However, any out-place mutation to the feature data will not reflect to this graph,
5652
        thus making it easier to use in a function scope (e.g. forward computation of a model).
Minjie Wang's avatar
Minjie Wang committed
5653
5654
5655
5656

        If set, the local graph object will use same initializers for node features and
        edge features.

Mufei Li's avatar
Mufei Li committed
5657
5658
        Returns
        -------
5659
5660
        DGLGraph
            The graph object for a local variable.
Mufei Li's avatar
Mufei Li committed
5661
5662
5663

        Notes
        -----
5664
5665
        Inplace operations do reflect to the original graph. This function also has little
        overhead when the number of feature tensors in this graph is small.
Mufei Li's avatar
Mufei Li committed
5666

Minjie Wang's avatar
Minjie Wang committed
5667
5668
        Examples
        --------
5669

Minjie Wang's avatar
Minjie Wang committed
5670
5671
        The following example uses PyTorch backend.

5672
5673
5674
5675
        >>> import dgl
        >>> import torch

        Create a function for computation on graphs.
Minjie Wang's avatar
Minjie Wang committed
5676
5677

        >>> def foo(g):
5678
5679
5680
5681
5682
5683
5684
5685
5686
5687
        ...     g = g.local_var()
        ...     g.edata['h'] = torch.ones((g.num_edges(), 3))
        ...     g.edata['h2'] = torch.ones((g.num_edges(), 3))
        ...     return g.edata['h']

        ``local_var`` avoids changing the graph features when exiting the function.

        >>> g = dgl.graph((torch.tensor([0, 1, 1]), torch.tensor([0, 0, 2])))
        >>> g.edata['h'] = torch.zeros((g.num_edges(), 3))
        >>> newh = foo(g)
Mufei Li's avatar
Mufei Li committed
5688
        >>> print(g.edata['h'])  # still get tensor of all zeros
5689
5690
5691
5692
5693
        tensor([[0., 0., 0.],
                [0., 0., 0.],
                [0., 0., 0.]])
        >>> 'h2' in g.edata      # new feature set in the function scope is not found
        False
Minjie Wang's avatar
Minjie Wang committed
5694

5695
        In-place operations will still reflect to the original graph.
Minjie Wang's avatar
Minjie Wang committed
5696
5697

        >>> def foo(g):
5698
5699
5700
5701
5702
5703
5704
5705
5706
5707
5708
5709
        ...     g = g.local_var()
        ...     # in-place operation
        ...     g.edata['h'] += 1
        ...     return g.edata['h']

        >>> g = dgl.graph((torch.tensor([0, 1, 1]), torch.tensor([0, 0, 2])))
        >>> g.edata['h'] = torch.zeros((g.num_edges(), 1))
        >>> newh = foo(g)
        >>> print(g.edata['h'])  # the result changes
        tensor([[1.],
                [1.],
                [1.]])
Minjie Wang's avatar
Minjie Wang committed
5710
5711
5712

        See Also
        --------
5713
        local_scope
Minjie Wang's avatar
Minjie Wang committed
5714
        """
5715
        ret = copy.copy(self)
5716
5717
        ret._node_frames = [fr.clone() for fr in self._node_frames]
        ret._edge_frames = [fr.clone() for fr in self._edge_frames]
5718
        return ret
Minjie Wang's avatar
Minjie Wang committed
5719
5720
5721

    @contextmanager
    def local_scope(self):
5722
        """Enter a local scope context for the graph.
Minjie Wang's avatar
Minjie Wang committed
5723
5724

        By entering a local scope, any out-place mutation to the feature data will
5725
5726
        not reflect to the original graph, thus making it easier to use in a function scope
        (e.g. forward computation of a model).
Minjie Wang's avatar
Minjie Wang committed
5727
5728
5729
5730

        If set, the local scope will use same initializers for node features and
        edge features.

5731
5732
5733
5734
5735
        Notes
        -----
        Inplace operations do reflect to the original graph. This function also has little
        overhead when the number of feature tensors in this graph is small.

Minjie Wang's avatar
Minjie Wang committed
5736
5737
        Examples
        --------
5738

Minjie Wang's avatar
Minjie Wang committed
5739
5740
        The following example uses PyTorch backend.

5741
5742
5743
5744
        >>> import dgl
        >>> import torch

        Create a function for computation on graphs.
Minjie Wang's avatar
Minjie Wang committed
5745
5746

        >>> def foo(g):
5747
5748
5749
5750
5751
5752
5753
5754
5755
5756
        ...     with g.local_scope():
        ...         g.edata['h'] = torch.ones((g.num_edges(), 3))
        ...         g.edata['h2'] = torch.ones((g.num_edges(), 3))
        ...         return g.edata['h']

        ``local_scope`` avoids changing the graph features when exiting the function.

        >>> g = dgl.graph((torch.tensor([0, 1, 1]), torch.tensor([0, 0, 2])))
        >>> g.edata['h'] = torch.zeros((g.num_edges(), 3))
        >>> newh = foo(g)
Mufei Li's avatar
Mufei Li committed
5757
        >>> print(g.edata['h'])  # still get tensor of all zeros
5758
5759
5760
5761
5762
        tensor([[0., 0., 0.],
                [0., 0., 0.],
                [0., 0., 0.]])
        >>> 'h2' in g.edata      # new feature set in the function scope is not found
        False
Minjie Wang's avatar
Minjie Wang committed
5763

5764
        In-place operations will still reflect to the original graph.
Minjie Wang's avatar
Minjie Wang committed
5765
5766

        >>> def foo(g):
5767
5768
5769
5770
5771
5772
5773
5774
5775
5776
5777
5778
        ...     with g.local_scope():
        ...         # in-place operation
        ...         g.edata['h'] += 1
        ...         return g.edata['h']

        >>> g = dgl.graph((torch.tensor([0, 1, 1]), torch.tensor([0, 0, 2])))
        >>> g.edata['h'] = torch.zeros((g.num_edges(), 1))
        >>> newh = foo(g)
        >>> print(g.edata['h'])  # the result changes
        tensor([[1.],
                [1.],
                [1.]])
Minjie Wang's avatar
Minjie Wang committed
5779
5780
5781
5782
5783
5784
5785

        See Also
        --------
        local_var
        """
        old_nframes = self._node_frames
        old_eframes = self._edge_frames
5786
5787
        self._node_frames = [fr.clone() for fr in self._node_frames]
        self._edge_frames = [fr.clone() for fr in self._edge_frames]
Minjie Wang's avatar
Minjie Wang committed
5788
5789
5790
5791
        yield
        self._node_frames = old_nframes
        self._edge_frames = old_eframes

5792
5793
5794
5795
5796
5797
5798
5799
    def formats(self, formats=None):
        r"""Get a cloned graph with the specified sparse format(s) or query
        for the usage status of sparse formats

        The API copies both the graph structure and the features.

        If the input graph has multiple edge types, they will have the same
        sparse format.
5800

5801
5802
        Parameters
        ----------
5803
5804
5805
5806
        formats : str or list of str or None

            * If formats is None, return the usage status of sparse formats
            * Otherwise, it can be ``'coo'``/``'csr'``/``'csc'`` or a sublist of
5807
              them, specifying the sparse formats to use.
5808

5809
5810
        Returns
        -------
5811
5812
5813
5814
5815
5816
        dict or DGLGraph

            * If formats is None, the result will be a dict recording the usage
              status of sparse formats.
            * Otherwise, a DGLGraph will be returned, which is a clone of the
              original graph with the specified sparse format(s) ``formats``.
5817

5818
5819
5820
        Examples
        --------

5821
        The following example uses PyTorch backend.
5822

5823
5824
        >>> import dgl
        >>> import torch
5825

5826
5827
        **Homographs or Heterographs with A Single Edge Type**

5828
        >>> g = dgl.graph(([0, 0, 1], [2, 3, 2]))
5829
5830
5831
5832
5833
5834
5835
5836
5837
5838
5839
5840
5841
5842
5843
        >>> g.ndata['h'] = torch.ones(4, 1)
        >>> # Check status of format usage
        >>> g.formats()
        {'created': ['coo'], 'not created': ['csr', 'csc']}
        >>> # Get a clone of the graph with 'csr' format
        >>> csr_g = g.formats('csr')
        >>> # Only allowed formats will be displayed in the status query
        >>> csr_g.formats()
        {'created': ['csr'], 'not created': []}
        >>> # Features are copied as well
        >>> csr_g.ndata['h']
        tensor([[1.],
                [1.],
                [1.],
                [1.]])
5844

5845
        **Heterographs with Multiple Edge Types**
5846

5847
        >>> g = dgl.heterograph({
5848
5849
5850
5851
5852
        ...     ('user', 'plays', 'game'): (torch.tensor([0, 1, 1, 2]),
        ...                                 torch.tensor([0, 0, 1, 1])),
        ...     ('developer', 'develops', 'game'): (torch.tensor([0, 1]),
        ...                                         torch.tensor([0, 1]))
        ...     })
5853
5854
5855
5856
5857
5858
5859
        >>> g.formats()
        {'created': ['coo'], 'not created': ['csr', 'csc']}
        >>> # Get a clone of the graph with 'csr' format
        >>> csr_g = g.formats('csr')
        >>> # Only allowed formats will be displayed in the status query
        >>> csr_g.formats()
        {'created': ['csr'], 'not created': []}
5860
        """
5861
5862
5863
5864
5865
5866
5867
5868
        if formats is None:
            # Return the format information
            return self._graph.formats()
        else:
            # Convert the graph to use another format
            ret = copy.copy(self)
            ret._graph = self._graph.formats(formats)
            return ret
5869

5870
    def create_formats_(self):
5871
        r"""Create all sparse matrices allowed for the graph.
5872

5873
5874
5875
        By default, we create sparse matrices for a graph only when necessary.
        In some cases we may want to create them immediately (e.g. in a
        multi-process data loader), which can be achieved via this API.
5876
5877
5878
5879

        Examples
        --------

5880
        The following example uses PyTorch backend.
5881

5882
5883
        >>> import dgl
        >>> import torch
5884

5885
        **Homographs or Heterographs with A Single Edge Type**
5886

5887
        >>> g = dgl.graph(([0, 0, 1], [2, 3, 2]))
5888
5889
        >>> g.format()
        {'created': ['coo'], 'not created': ['csr', 'csc']}
5890
        >>> g.create_formats_()
5891
5892
        >>> g.format()
        {'created': ['coo', 'csr', 'csc'], 'not created': []}
5893

5894
        **Heterographs with Multiple Edge Types**
5895
5896

        >>> g = dgl.heterograph({
5897
5898
5899
5900
5901
        ...     ('user', 'plays', 'game'): (torch.tensor([0, 1, 1, 2]),
        ...                                 torch.tensor([0, 0, 1, 1])),
        ...     ('developer', 'develops', 'game'): (torch.tensor([0, 1]),
        ...                                         torch.tensor([0, 1]))
        ...     })
5902
5903
        >>> g.format()
        {'created': ['coo'], 'not created': ['csr', 'csc']}
5904
        >>> g.create_formats_()
5905
5906
        >>> g.format()
        {'created': ['coo', 'csr', 'csc'], 'not created': []}
5907
        """
5908
        return self._graph.create_formats_()
5909

5910
5911
    def astype(self, idtype):
        """Cast this graph to use another ID type.
5912

5913
        Features are copied (shallow copy) to the new graph.
5914
5915
5916

        Parameters
        ----------
5917
5918
        idtype : Data type object.
            New ID type. Can only be int32 or int64.
5919
5920
5921

        Returns
        -------
peizhou001's avatar
peizhou001 committed
5922
        DGLGraph
5923
            Graph in the new ID type.
5924
        """
5925
5926
        if idtype is None:
            return self
5927
        utils.check_valid_idtype(idtype)
5928
5929
5930
5931
5932
5933
        if self.idtype == idtype:
            return self
        bits = 32 if idtype == F.int32 else 64
        ret = copy.copy(self)
        ret._graph = self._graph.asbits(bits)
        return ret
5934

5935
5936
5937
5938
    # TODO: Formats should not be specified, just saving all the materialized formats
    def shared_memory(self, name, formats=('coo', 'csr', 'csc')):
        """Return a copy of this graph in shared memory, without node data or edge data.

peizhou001's avatar
peizhou001 committed
5939
        It moves the graph index to shared memory and returns a DGLGraph object which
5940
5941
5942
5943
5944
5945
5946
        has the same graph structure, node types and edge types but does not contain node data
        or edge data.

        Parameters
        ----------
        name : str
            The name of the shared memory.
5947
        formats : str or a list of str (optional)
5948
5949
5950
5951
            Desired formats to be materialized.

        Returns
        -------
peizhou001's avatar
peizhou001 committed
5952
        DGLGraph
5953
5954
5955
5956
            The graph in shared memory
        """
        assert len(name) > 0, "The name of shared memory cannot be empty"
        assert len(formats) > 0
5957
5958
        if isinstance(formats, str):
            formats = [formats]
5959
        for fmt in formats:
5960
            assert fmt in ("coo", "csr", "csc"), '{} is not coo, csr or csc'.format(fmt)
5961
        gidx = self._graph.shared_memory(name, self.ntypes, self.etypes, formats)
peizhou001's avatar
peizhou001 committed
5962
        return DGLGraph(gidx, self.ntypes, self.etypes)
5963

5964

5965
    def long(self):
5966
        """Cast the graph to one with idtype int64
5967

5968
5969
        If the graph already has idtype int64, the function directly returns it. Otherwise,
        it returns a cloned graph of idtype int64 with features copied (shallow copy).
5970
5971
5972

        Returns
        -------
5973
5974
        DGLGraph
            The graph of idtype int64.
5975
5976
5977
5978

        Examples
        --------

5979
5980
5981
5982
5983
5984
5985
5986
5987
5988
5989
5990
5991
5992
5993
5994
5995
5996
5997
5998
5999
6000
6001
6002
6003
6004
6005
6006
        The following example uses PyTorch backend.

        >>> import dgl
        >>> import torch

        Create a graph of idtype int32.

        >>> # (0, 1), (0, 2), (1, 2)
        >>> g = dgl.graph((torch.tensor([0, 0, 1]).int(), torch.tensor([1, 2, 2]).int()))
        >>> g.ndata['feat'] = torch.ones(3, 1)
        >>> g.idtype
        torch.int32

        Cast the graph to one of idtype int64.

        >>> # A cloned graph with an idtype of int64
        >>> g_long = g.long()
        >>> g_long.idtype
        torch.int64
        >>> # The idtype of the original graph does not change.
        >>> g.idtype
        torch.int32
        >>> g_long.edges()
        (tensor([0, 0, 1]), tensor([1, 2, 2]))
        >>> g_long.ndata
        {'feat': tensor([[1.],
                         [1.],
                         [1.]])}
6007
6008
6009
6010

        See Also
        --------
        int
6011
        idtype
6012
        """
6013
        return self.astype(F.int64)
6014
6015

    def int(self):
6016
6017
6018
6019
        """Cast the graph to one with idtype int32

        If the graph already has idtype int32, the function directly returns it. Otherwise,
        it returns a cloned graph of idtype int32 with features copied (shallow copy).
6020
6021
6022

        Returns
        -------
6023
6024
        DGLGraph
            The graph of idtype int32.
6025
6026
6027
6028

        Examples
        --------

6029
6030
6031
6032
6033
6034
6035
6036
6037
6038
6039
6040
6041
6042
6043
6044
6045
6046
6047
6048
6049
6050
6051
6052
6053
6054
6055
6056
        The following example uses PyTorch backend.

        >>> import dgl
        >>> import torch

        Create a graph of idtype int64.

        >>> # (0, 1), (0, 2), (1, 2)
        >>> g = dgl.graph((torch.tensor([0, 0, 1]), torch.tensor([1, 2, 2])))
        >>> g.ndata['feat'] = torch.ones(3, 1)
        >>> g.idtype
        torch.int64

        Cast the graph to one of idtype int32.

        >>> # A cloned graph with an idtype of int32
        >>> g_int = g.int()
        >>> g_int.idtype
        torch.int32
        >>> # The idtype of the original graph does not change.
        >>> g.idtype
        torch.int64
        >>> g_int.edges()
        (tensor([0, 0, 1], dtype=torch.int32), tensor([1, 2, 2], dtype=torch.int32))
        >>> g_int.ndata
        {'feat': tensor([[1.],
                         [1.],
                         [1.]])}
6057
6058
6059
6060

        See Also
        --------
        long
6061
        idtype
6062
        """
6063
        return self.astype(F.int32)
6064

6065
6066
6067
6068
6069
6070
6071
6072
6073
6074
6075
6076
6077
6078
6079
6080
6081
6082
6083
6084
6085
6086
6087
6088
6089
6090
6091
6092
6093
6094
6095
6096
6097
6098
6099
6100
6101
6102
6103
6104
6105
6106
6107
6108
6109
6110
6111
6112
6113
6114
6115
6116
6117
6118
6119
6120
6121
6122
6123
6124
6125
6126
6127
6128
6129
6130
6131
6132
6133
6134
6135
6136
6137
6138
6139
6140
6141
6142
6143
6144
6145
6146
6147
6148
6149
6150
6151
6152
6153
6154
6155
6156
6157
6158
6159
6160
6161
6162
6163
6164
6165
6166
6167
6168
6169
6170
    #################################################################
    # DEPRECATED: from the old DGLGraph
    #################################################################

    def from_networkx(self, nx_graph, node_attrs=None, edge_attrs=None):
        """DEPRECATED: please use

            ``dgl.from_networkx(nx_graph, node_attrs, edge_attrs)``

        which will return a new graph created from the networkx graph.
        """
        raise DGLError('DGLGraph.from_networkx is deprecated. Please call the following\n\n'
                       '\t dgl.from_networkx(nx_graph, node_attrs, edge_attrs)\n\n'
                       ', which creates a new DGLGraph from the networkx graph.')

    def from_scipy_sparse_matrix(self, spmat, multigraph=None):
        """DEPRECATED: please use

            ``dgl.from_scipy(spmat)``

        which will return a new graph created from the scipy matrix.
        """
        raise DGLError('DGLGraph.from_scipy_sparse_matrix is deprecated. '
                       'Please call the following\n\n'
                       '\t dgl.from_scipy(spmat)\n\n'
                       ', which creates a new DGLGraph from the scipy matrix.')

    def register_apply_node_func(self, func):
        """Deprecated: please directly call :func:`apply_nodes` with ``func``
        as argument.
        """
        raise DGLError('DGLGraph.register_apply_node_func is deprecated.'
                       ' Please directly call apply_nodes with func as the argument.')

    def register_apply_edge_func(self, func):
        """Deprecated: please directly call :func:`apply_edges` with ``func``
        as argument.
        """
        raise DGLError('DGLGraph.register_apply_edge_func is deprecated.'
                       ' Please directly call apply_edges with func as the argument.')

    def register_message_func(self, func):
        """Deprecated: please directly call :func:`update_all` with ``func``
        as argument.
        """
        raise DGLError('DGLGraph.register_message_func is deprecated.'
                       ' Please directly call update_all with func as the argument.')

    def register_reduce_func(self, func):
        """Deprecated: please directly call :func:`update_all` with ``func``
        as argument.
        """
        raise DGLError('DGLGraph.register_reduce_func is deprecated.'
                       ' Please directly call update_all with func as the argument.')

    def group_apply_edges(self, group_by, func, edges=ALL, etype=None, inplace=False):
        """**DEPRECATED**: The API is removed in 0.5."""
        raise DGLError('DGLGraph.group_apply_edges is removed in 0.5.')

    def send(self, edges, message_func, etype=None):
        """Send messages along the given edges with the same edge type.

        DEPRECATE: please use send_and_recv, update_all.
        """
        raise DGLError('DGLGraph.send is deprecated. As a replacement, use DGLGraph.apply_edges\n'
                       ' API to compute messages as edge data. Then use DGLGraph.send_and_recv\n'
                       ' and set the message function as dgl.function.copy_e to conduct message\n'
                       ' aggregation.')

    def recv(self, v, reduce_func, apply_node_func=None, etype=None, inplace=False):
        r"""Receive and reduce incoming messages and update the features of node(s) :math:`v`.

        DEPRECATE: please use send_and_recv, update_all.
        """
        raise DGLError('DGLGraph.recv is deprecated. As a replacement, use DGLGraph.apply_edges\n'
                       ' API to compute messages as edge data. Then use DGLGraph.send_and_recv\n'
                       ' and set the message function as dgl.function.copy_e to conduct message\n'
                       ' aggregation.')

    def multi_recv(self, v, reducer_dict, cross_reducer, apply_node_func=None, inplace=False):
        r"""Receive messages from multiple edge types and perform aggregation.

        DEPRECATE: please use multi_send_and_recv, multi_update_all.
        """
        raise DGLError('DGLGraph.multi_recv is deprecated. As a replacement,\n'
                       ' use DGLGraph.apply_edges API to compute messages as edge data.\n'
                       ' Then use DGLGraph.multi_send_and_recv and set the message function\n'
                       ' as dgl.function.copy_e to conduct message aggregation.')

    def multi_send_and_recv(self, etype_dict, cross_reducer, apply_node_func=None, inplace=False):
        r"""**DEPRECATED**: The API is removed in v0.5."""
        raise DGLError('DGLGraph.multi_pull is removed in v0.5. As a replacement,\n'
                       ' use DGLGraph.edge_subgraph to extract the subgraph first \n'
                       ' and then call DGLGraph.multi_update_all.')

    def multi_pull(self, v, etype_dict, cross_reducer, apply_node_func=None, inplace=False):
        r"""**DEPRECATED**: The API is removed in v0.5."""
        raise DGLError('DGLGraph.multi_pull is removed in v0.5. As a replacement,\n'
                       ' use DGLGraph.edge_subgraph to extract the subgraph first \n'
                       ' and then call DGLGraph.multi_update_all.')

    def readonly(self, readonly_state=True):
        """Deprecated: DGLGraph will always be mutable."""
        dgl_warning('DGLGraph.readonly is deprecated in v0.5.\n'
                    'DGLGraph now always supports mutable operations like add_nodes'
                    ' and add_edges.')
6171

Minjie Wang's avatar
Minjie Wang committed
6172
6173
6174
6175
6176
6177
6178
6179
6180
6181
6182
6183
6184
6185
6186
6187
6188
6189
6190
6191
6192
6193
6194
6195
6196
6197
6198
6199
6200
############################################################
# Internal APIs
############################################################

def make_canonical_etypes(etypes, ntypes, metagraph):
    """Internal function to convert etype name to (srctype, etype, dsttype)

    Parameters
    ----------
    etypes : list of str
        Edge type list
    ntypes : list of str
        Node type list
    metagraph : GraphIndex
        Meta graph.

    Returns
    -------
    list of tuples (srctype, etype, dsttype)
    """
    # sanity check
    if len(etypes) != metagraph.number_of_edges():
        raise DGLError('Length of edge type list must match the number of '
                       'edges in the metagraph. {} vs {}'.format(
                           len(etypes), metagraph.number_of_edges()))
    if len(ntypes) != metagraph.number_of_nodes():
        raise DGLError('Length of nodes type list must match the number of '
                       'nodes in the metagraph. {} vs {}'.format(
                           len(ntypes), metagraph.number_of_nodes()))
6201
6202
6203
    if (len(etypes) == 1 and len(ntypes) == 1):
        return [(ntypes[0], etypes[0], ntypes[0])]
    src, dst, eid = metagraph.edges(order="eid")
Minjie Wang's avatar
Minjie Wang committed
6204
6205
6206
    rst = [(ntypes[sid], etypes[eid], ntypes[did]) for sid, did, eid in zip(src, dst, eid)]
    return rst

6207
6208
6209
6210
6211
6212
6213
6214
6215
6216
6217
6218
6219
6220
6221
6222
6223
6224
6225
6226
6227
6228
6229
def find_src_dst_ntypes(ntypes, metagraph):
    """Internal function to split ntypes into SRC and DST categories.

    If the metagraph is not a uni-bipartite graph (so that the SRC and DST categories
    are not well-defined), return None.

    For node types that are isolated (i.e, no relation is associated with it), they
    are assigned to the SRC category.

    Parameters
    ----------
    ntypes : list of str
        Node type list
    metagraph : GraphIndex
        Meta graph.

    Returns
    -------
    (dict[int, str], dict[int, str]) or None
        Node types belonging to SRC and DST categories. Types are stored in
        a dictionary from type name to type id. Return None if the graph is
        not uni-bipartite.
    """
6230
6231
    ret = _CAPI_DGLFindSrcDstNtypes(metagraph)
    if ret is None:
6232
        return None
6233
6234
    else:
        src, dst = ret
6235
6236
        srctypes = {ntypes[tid] : tid for tid in src}
        dsttypes = {ntypes[tid] : tid for tid in dst}
6237
        return srctypes, dsttypes
6238

Minjie Wang's avatar
Minjie Wang committed
6239
6240
6241
6242
6243
6244
6245
6246
6247
6248
6249
6250
6251
6252
6253
def pad_tuple(tup, length, pad_val=None):
    """Pad the given tuple to the given length.

    If the input is not a tuple, convert it to a tuple of length one.
    Return None if pad fails.
    """
    if not isinstance(tup, tuple):
        tup = (tup, )
    if len(tup) > length:
        return None
    elif len(tup) == length:
        return tup
    else:
        return tup + (pad_val,) * (length - len(tup))

6254
6255
def reduce_dict_data(frames, reducer, order=None):
    """Merge tensor dictionaries into one. Resolve conflict fields using reducer.
Minjie Wang's avatar
Minjie Wang committed
6256
6257
6258

    Parameters
    ----------
6259
6260
    frames : list[dict[str, Tensor]]
        Input tensor dictionaries
6261
6262
6263
6264
6265
    reducer : str or callable function
        One of "sum", "max", "min", "mean", "stack" or a callable function.
        If a callable function is provided, the input arguments must be a single list
        of tensors containing aggregation results from each edge type, and the
        output of function must be a single tensor.
6266
6267
6268
6269
6270
6271
    order : list[Int], optional
        Merge order hint. Useful for "stack" reducer.
        If provided, each integer indicates the relative order
        of the ``frames`` list. Frames are sorted according to this list
        in ascending order. Tie is not handled so make sure the order values
        are distinct.
Minjie Wang's avatar
Minjie Wang committed
6272
6273
6274

    Returns
    -------
6275
    dict[str, Tensor]
Minjie Wang's avatar
Minjie Wang committed
6276
        Merged frame
Da Zheng's avatar
Da Zheng committed
6277
    """
6278
6279
6280
    if len(frames) == 1 and reducer != 'stack':
        # Directly return the only one input. Stack reducer requires
        # modifying tensor shape.
Minjie Wang's avatar
Minjie Wang committed
6281
        return frames[0]
6282
6283
6284
    if callable(reducer):
        merger = reducer
    elif reducer == 'stack':
6285
6286
6287
6288
6289
        # Stack order does not matter. However, it must be consistent!
        if order:
            assert len(order) == len(frames)
            sorted_with_key = sorted(zip(frames, order), key=lambda x: x[1])
            frames = list(zip(*sorted_with_key))[0]
Minjie Wang's avatar
Minjie Wang committed
6290
6291
6292
6293
6294
6295
6296
6297
        def merger(flist):
            return F.stack(flist, 1)
    else:
        redfn = getattr(F, reducer, None)
        if redfn is None:
            raise DGLError('Invalid cross type reducer. Must be one of '
                           '"sum", "max", "min", "mean" or "stack".')
        def merger(flist):
6298
            return redfn(F.stack(flist, 0), 0) if len(flist) > 1 else flist[0]
Minjie Wang's avatar
Minjie Wang committed
6299
6300
6301
    keys = set()
    for frm in frames:
        keys.update(frm.keys())
6302
    ret = {}
Minjie Wang's avatar
Minjie Wang committed
6303
6304
6305
6306
6307
    for k in keys:
        flist = []
        for frm in frames:
            if k in frm:
                flist.append(frm[k])
6308
        ret[k] = merger(flist)
Minjie Wang's avatar
Minjie Wang committed
6309
6310
    return ret

6311
def combine_frames(frames, ids, col_names=None):
Minjie Wang's avatar
Minjie Wang committed
6312
6313
6314
6315
    """Merge the frames into one frame, taking the common columns.

    Return None if there is no common columns.

Da Zheng's avatar
Da Zheng committed
6316
6317
    Parameters
    ----------
6318
    frames : List[Frame]
Minjie Wang's avatar
Minjie Wang committed
6319
6320
6321
        List of frames
    ids : List[int]
        List of frame IDs
6322
6323
    col_names : List[str], optional
        Column names to consider. If not given, it considers all columns.
Minjie Wang's avatar
Minjie Wang committed
6324
6325
6326

    Returns
    -------
6327
    Frame
Minjie Wang's avatar
Minjie Wang committed
6328
        The resulting frame
Da Zheng's avatar
Da Zheng committed
6329
    """
Minjie Wang's avatar
Minjie Wang committed
6330
    # find common columns and check if their schemes match
6331
    schemes = None
Minjie Wang's avatar
Minjie Wang committed
6332
6333
    for frame_id in ids:
        frame = frames[frame_id]
6334
6335
6336
6337
6338
6339
6340
6341
6342
6343
6344
6345
6346
6347
        if frame.num_rows == 0:
            continue
        if schemes is None:
            schemes = frame.schemes
            if col_names is not None:
                schemes = {key: frame.schemes[key] for key in col_names}
            continue
        for key, scheme in list(schemes.items()):
            if key in frame.schemes:
                if frame.schemes[key] != scheme:
                    raise DGLError('Cannot concatenate column %s with shape %s and shape %s' %
                                   (key, frame.schemes[key], scheme))
            else:
                del schemes[key]
Minjie Wang's avatar
Minjie Wang committed
6348
6349
6350
6351
6352
6353
6354

    if len(schemes) == 0:
        return None

    # concatenate the columns
    to_cat = lambda key: [frames[i][key] for i in ids if frames[i].num_rows > 0]
    cols = {key: F.cat(to_cat(key), dim=0) for key in schemes}
6355
    return Frame(cols)
Minjie Wang's avatar
Minjie Wang committed
6356
6357
6358
6359
6360
6361
6362
6363
6364
6365
6366
6367
6368
6369
6370
6371
6372
6373
6374
6375
6376

def combine_names(names, ids=None):
    """Combine the selected names into one new name.

    Parameters
    ----------
    names : list of str
        String names
    ids : numpy.ndarray, optional
        Selected index

    Returns
    -------
    str
    """
    if ids is None:
        return '+'.join(sorted(names))
    else:
        selected = sorted([names[i] for i in ids])
        return '+'.join(selected)

peizhou001's avatar
peizhou001 committed
6377
class DGLBlock(DGLGraph):
6378
6379
6380
6381
6382
6383
6384
6385
6386
6387
6388
6389
6390
6391
6392
6393
6394
6395
6396
6397
6398
6399
6400
6401
6402
    """Subclass that signifies the graph is a block created from
    :func:`dgl.to_block`.
    """
    # (BarclayII) I'm making a subclass because I don't want to make another version of
    # serialization that contains the is_block flag.
    is_block = True

    def __repr__(self):
        if len(self.srctypes) == 1 and len(self.dsttypes) == 1 and len(self.etypes) == 1:
            ret = 'Block(num_src_nodes={srcnode}, num_dst_nodes={dstnode}, num_edges={edge})'
            return ret.format(
                srcnode=self.number_of_src_nodes(),
                dstnode=self.number_of_dst_nodes(),
                edge=self.number_of_edges())
        else:
            ret = ('Block(num_src_nodes={srcnode},\n'
                   '      num_dst_nodes={dstnode},\n'
                   '      num_edges={edge},\n'
                   '      metagraph={meta})')
            nsrcnode_dict = {ntype : self.number_of_src_nodes(ntype)
                             for ntype in self.srctypes}
            ndstnode_dict = {ntype : self.number_of_dst_nodes(ntype)
                             for ntype in self.dsttypes}
            nedge_dict = {etype : self.number_of_edges(etype)
                          for etype in self.canonical_etypes}
6403
            meta = str(self.metagraph().edges(keys=True))
6404
6405
6406
            return ret.format(
                srcnode=nsrcnode_dict, dstnode=ndstnode_dict, edge=nedge_dict, meta=meta)

6407
6408
6409
6410
6411
6412
6413
6414
6415
6416
6417
6418
6419
6420
6421
6422
6423
6424
6425
6426
6427
6428
6429
6430
6431
6432
6433
6434
6435
6436
6437
6438
6439
6440
6441
6442
6443
6444
6445
6446
6447
6448
6449
6450
6451
6452
6453
6454
6455
6456
6457
6458
6459
6460
6461
6462
6463
6464
6465
6466
6467

def _create_compute_graph(graph, u, v, eid, recv_nodes=None):
    """Create a computation graph from the given edges.

    The compute graph is a uni-directional bipartite graph with only
    one edge type. Similar to subgraph extraction, it stores the original node IDs
    in the srcdata[NID] and dstdata[NID] and extracts features accordingly.
    Edges are not relabeled.

    This function is typically used during message passing to generate
    a graph that contains only the active set of edges.

    Parameters
    ----------
    graph : DGLGraph
        The input graph.
    u : Tensor
        Src nodes.
    v : Tensor
        Dst nodes.
    eid : Tensor
        Edge IDs.
    recv_nodes : Tensor
        Nodes that receive messages. If None, it is equal to unique(v).
        Otherwise, it must be a superset of v and can contain nodes
        that have no incoming edges.

    Returns
    -------
    DGLGraph
        A computation graph.
    """
    if len(u) == 0:
        # The computation graph has no edge and will not trigger message
        # passing. However, because of the apply node phase, we still construct
        # an empty graph to continue.
        unique_src = new_u = new_v = u
        assert recv_nodes is not None
        unique_dst, _ = utils.relabel(recv_nodes)
    else:
        # relabel u and v to starting from 0
        unique_src, src_map = utils.relabel(u)
        if recv_nodes is None:
            unique_dst, dst_map = utils.relabel(v)
        else:
            unique_dst, dst_map = utils.relabel(recv_nodes)
        new_u = F.gather_row(src_map, u)
        new_v = F.gather_row(dst_map, v)

    srctype, etype, dsttype = graph.canonical_etypes[0]
    # create graph
    hgidx = heterograph_index.create_unitgraph_from_coo(
        2, len(unique_src), len(unique_dst), new_u, new_v, ['coo', 'csr', 'csc'])
    # create frame
    srcframe = graph._node_frames[graph.get_ntype_id(srctype)].subframe(unique_src)
    srcframe[NID] = unique_src
    dstframe = graph._node_frames[graph.get_ntype_id(dsttype)].subframe(unique_dst)
    dstframe[NID] = unique_dst
    eframe = graph._edge_frames[0].subframe(eid)
    eframe[EID] = eid

peizhou001's avatar
peizhou001 committed
6468
    return DGLGraph(hgidx, ([srctype], [dsttype]), [etype],
6469
                          node_frames=[srcframe, dstframe],
6470
                          edge_frames=[eframe]), unique_src, unique_dst, eid
6471

6472
_init_api("dgl.heterograph")