heterograph.py 235 KB
Newer Older
Da Zheng's avatar
Da Zheng committed
1
"""Classes for heterogeneous graphs."""
2
import copy
3
import itertools
Hongzhi (Steve), Chen's avatar
Hongzhi (Steve), Chen committed
4
5
6
7
8
9
10
import numbers

# pylint: disable= too-many-lines
from collections import defaultdict
from collections.abc import Iterable, Mapping
from contextlib import contextmanager

11
import networkx as nx
Minjie Wang's avatar
Minjie Wang committed
12
13
import numpy as np

Hongzhi (Steve), Chen's avatar
Hongzhi (Steve), Chen committed
14
15
from . import backend as F, core, graph_index, heterograph_index, utils

16
from ._ffi.function import _init_api
Hongzhi (Steve), Chen's avatar
Hongzhi (Steve), Chen committed
17
18
19
20
21
22
23
24
25
26
27
from .base import (
    ALL,
    dgl_warning,
    DGLError,
    EID,
    ETYPE,
    is_all,
    NID,
    NTYPE,
    SLICE_FULL,
)
28
from .frame import Frame
Hongzhi (Steve), Chen's avatar
Hongzhi (Steve), Chen committed
29
30
31
32
33
34
35
36
37
from .ops import segment
from .view import (
    HeteroEdgeDataView,
    HeteroEdgeView,
    HeteroNodeDataView,
    HeteroNodeView,
)

__all__ = ["DGLGraph", "combine_names"]
Minjie Wang's avatar
Minjie Wang committed
38
39


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

43
    There are a few ways to create a DGLGraph:
44
45
46
47
48
49
50
51

    * 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
52
    """
Hongzhi (Steve), Chen's avatar
Hongzhi (Steve), Chen committed
53

54
55
    is_block = False

56
    # pylint: disable=unused-argument, dangerous-default-value
Hongzhi (Steve), Chen's avatar
Hongzhi (Steve), Chen committed
57
58
59
60
61
62
63
64
65
    def __init__(
        self,
        gidx=[],
        ntypes=["_N"],
        etypes=["_E"],
        node_frames=None,
        edge_frames=None,
        **deprecate_kwargs
    ):
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
        """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
87
        if isinstance(gidx, DGLGraph):
Hongzhi (Steve), Chen's avatar
Hongzhi (Steve), Chen committed
88
89
90
            raise DGLError(
                "The input is already a DGLGraph. No need to create it again."
            )
91
        if not isinstance(gidx, heterograph_index.HeteroGraphIndex):
Hongzhi (Steve), Chen's avatar
Hongzhi (Steve), Chen committed
92
93
94
95
96
97
98
99
            dgl_warning(
                "Recommend creating graphs by `dgl.graph(data)`"
                " instead of `dgl.DGLGraph(data)`."
            )
            (sparse_fmt, arrays), num_src, num_dst = utils.graphdata2tensors(
                gidx
            )
            if sparse_fmt == "coo":
100
                gidx = heterograph_index.create_unitgraph_from_coo(
Hongzhi (Steve), Chen's avatar
Hongzhi (Steve), Chen committed
101
102
103
104
105
106
107
                    1,
                    num_src,
                    num_dst,
                    arrays[0],
                    arrays[1],
                    ["coo", "csr", "csc"],
                )
108
109
            else:
                gidx = heterograph_index.create_unitgraph_from_csr(
Hongzhi (Steve), Chen's avatar
Hongzhi (Steve), Chen committed
110
111
112
113
114
115
116
117
118
                    1,
                    num_src,
                    num_dst,
                    arrays[0],
                    arrays[1],
                    arrays[2],
                    ["coo", "csr", "csc"],
                    sparse_fmt == "csc",
                )
119
        if len(deprecate_kwargs) != 0:
Hongzhi (Steve), Chen's avatar
Hongzhi (Steve), Chen committed
120
121
122
123
            dgl_warning(
                "Keyword arguments {} are deprecated in v0.5, and can be safely"
                " removed in all cases.".format(list(deprecate_kwargs.keys()))
            )
124
        self._init(gidx, ntypes, etypes, node_frames, edge_frames)
Da Zheng's avatar
Da Zheng committed
125

126
127
    def _init(self, gidx, ntypes, etypes, node_frames, edge_frames):
        """Init internal states."""
Minjie Wang's avatar
Minjie Wang committed
128
        self._graph = gidx
129
        self._canonical_etypes = None
130
131
        self._batch_num_nodes = None
        self._batch_num_edges = None
132
133
134
135

        # Handle node types
        if isinstance(ntypes, tuple):
            if len(ntypes) != 2:
Hongzhi (Steve), Chen's avatar
Hongzhi (Steve), Chen committed
136
137
138
                errmsg = "Invalid input. Expect a pair (srctypes, dsttypes) but got {}".format(
                    ntypes
                )
139
                raise TypeError(errmsg)
140
            if not self._graph.is_metagraph_unibipartite():
Hongzhi (Steve), Chen's avatar
Hongzhi (Steve), Chen committed
141
142
143
144
                raise ValueError(
                    "Invalid input. The metagraph must be a uni-directional"
                    " bipartite graph."
                )
145
            self._ntypes = ntypes[0] + ntypes[1]
Hongzhi (Steve), Chen's avatar
Hongzhi (Steve), Chen committed
146
147
148
149
            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])
            }
150
            self._is_unibipartite = True
151
            if len(ntypes[0]) == 1 and len(ntypes[1]) == 1 and len(etypes) == 1:
Hongzhi (Steve), Chen's avatar
Hongzhi (Steve), Chen committed
152
153
154
                self._canonical_etypes = [
                    (ntypes[0][0], etypes[0], ntypes[1][0])
                ]
155
156
        else:
            self._ntypes = ntypes
157
158
159
            if len(ntypes) == 1:
                src_dst_map = None
            else:
Hongzhi (Steve), Chen's avatar
Hongzhi (Steve), Chen committed
160
161
162
163
                src_dst_map = find_src_dst_ntypes(
                    self._ntypes, self._graph.metagraph
                )
            self._is_unibipartite = src_dst_map is not None
164
165
166
            if self._is_unibipartite:
                self._srctypes_invmap, self._dsttypes_invmap = src_dst_map
            else:
Hongzhi (Steve), Chen's avatar
Hongzhi (Steve), Chen committed
167
168
169
                self._srctypes_invmap = {
                    t: i for i, t in enumerate(self._ntypes)
                }
170
171
172
                self._dsttypes_invmap = self._srctypes_invmap

        # Handle edge types
173
        self._etypes = etypes
174
        if self._canonical_etypes is None:
Hongzhi (Steve), Chen's avatar
Hongzhi (Steve), Chen committed
175
            if len(etypes) == 1 and len(ntypes) == 1:
176
177
178
                self._canonical_etypes = [(ntypes[0], etypes[0], ntypes[0])]
            else:
                self._canonical_etypes = make_canonical_etypes(
Hongzhi (Steve), Chen's avatar
Hongzhi (Steve), Chen committed
179
180
                    self._etypes, self._ntypes, self._graph.metagraph
                )
181

Minjie Wang's avatar
Minjie Wang committed
182
        # An internal map from etype to canonical etype tuple.
183
184
        # If two etypes have the same name, an empty tuple is stored instead to indicate
        # ambiguity.
Minjie Wang's avatar
Minjie Wang committed
185
        self._etype2canonical = {}
186
        for i, ety in enumerate(self._etypes):
Minjie Wang's avatar
Minjie Wang committed
187
188
189
190
            if ety in self._etype2canonical:
                self._etype2canonical[ety] = tuple()
            else:
                self._etype2canonical[ety] = self._canonical_etypes[i]
Hongzhi (Steve), Chen's avatar
Hongzhi (Steve), Chen committed
191
192
193
        self._etypes_invmap = {
            t: i for i, t in enumerate(self._canonical_etypes)
        }
Da Zheng's avatar
Da Zheng committed
194

Minjie Wang's avatar
Minjie Wang committed
195
196
197
        # node and edge frame
        if node_frames is None:
            node_frames = [None] * len(self._ntypes)
Hongzhi (Steve), Chen's avatar
Hongzhi (Steve), Chen committed
198
199
200
201
202
203
        node_frames = [
            Frame(num_rows=self._graph.number_of_nodes(i))
            if frame is None
            else frame
            for i, frame in enumerate(node_frames)
        ]
Minjie Wang's avatar
Minjie Wang committed
204
        self._node_frames = node_frames
Da Zheng's avatar
Da Zheng committed
205

Minjie Wang's avatar
Minjie Wang committed
206
207
        if edge_frames is None:
            edge_frames = [None] * len(self._etypes)
Hongzhi (Steve), Chen's avatar
Hongzhi (Steve), Chen committed
208
209
210
211
212
213
        edge_frames = [
            Frame(num_rows=self._graph.number_of_edges(i))
            if frame is None
            else frame
            for i, frame in enumerate(edge_frames)
        ]
Minjie Wang's avatar
Minjie Wang committed
214
        self._edge_frames = edge_frames
Da Zheng's avatar
Da Zheng committed
215

216
    def __setstate__(self, state):
217
218
        # Compatibility check
        # TODO: version the storage
219
220
221
        if isinstance(state, dict):
            # Since 0.5 we use the default __dict__ method
            self.__dict__.update(state)
222
223
        elif isinstance(state, tuple) and len(state) == 5:
            # DGL == 0.4.3
Hongzhi (Steve), Chen's avatar
Hongzhi (Steve), Chen committed
224
225
226
227
            dgl_warning(
                "The object is pickled with DGL == 0.4.3.  "
                "Some of the original attributes are ignored."
            )
228
229
            self._init(*state)
        elif isinstance(state, dict):
230
            # DGL <= 0.4.2
Hongzhi (Steve), Chen's avatar
Hongzhi (Steve), Chen committed
231
232
233
234
235
236
237
238
239
240
241
            dgl_warning(
                "The object is pickled with DGL <= 0.4.2.  "
                "Some of the original attributes are ignored."
            )
            self._init(
                state["_graph"],
                state["_ntypes"],
                state["_etypes"],
                state["_node_frames"],
                state["_edge_frames"],
            )
242
243
        else:
            raise IOError("Unrecognized pickle format.")
Mufei Li's avatar
Mufei Li committed
244

Minjie Wang's avatar
Minjie Wang committed
245
246
    def __repr__(self):
        if len(self.ntypes) == 1 and len(self.etypes) == 1:
Hongzhi (Steve), Chen's avatar
Hongzhi (Steve), Chen committed
247
248
249
250
251
252
253
254
255
256
257
            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()),
            )
Minjie Wang's avatar
Minjie Wang committed
258
        else:
Hongzhi (Steve), Chen's avatar
Hongzhi (Steve), Chen committed
259
260
261
262
263
264
265
266
267
268
269
270
271
            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))
            }
            nedge_dict = {
                self.canonical_etypes[i]: self._graph.number_of_edges(i)
                for i in range(len(self.etypes))
            }
272
            meta = str(self.metagraph().edges(keys=True))
Minjie Wang's avatar
Minjie Wang committed
273
274
            return ret.format(node=nnode_dict, edge=nedge_dict, meta=meta)

275
276
    def __copy__(self):
        """Shallow copy implementation."""
Hongzhi (Steve), Chen's avatar
Hongzhi (Steve), Chen committed
277
        # TODO(minjie): too many states in python; should clean up and lower to C
278
279
        cls = type(self)
        obj = cls.__new__(cls)
280
        obj.__dict__.update(self.__dict__)
281
282
        return obj

Minjie Wang's avatar
Minjie Wang committed
283
284
285
286
287
    #################################################################
    # Mutation operations
    #################################################################

    def add_nodes(self, num, data=None, ntype=None):
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
        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,
305
306
          those features for the new nodes will be created by initializers
          defined with :func:`set_n_initializer` (default initializer fills zeros).
307
        * If the key of ``data`` contains new feature fields, those features for
308
309
310
311
312
313
          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.
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
348
349
350
351
352
353
354
355
356

        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({
357
358
359
360
361
        ...     ('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]))
        ...     })
362
363
364
365
366
367
368
369
        >>> 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
370

371
372
373
374
375
        See Also
        --------
        remove_nodes
        add_edges
        remove_edges
Minjie Wang's avatar
Minjie Wang committed
376
        """
377
378
379
        # TODO(xiangsx): block do not support add_nodes
        if ntype is None:
            if self._graph.number_of_ntypes() != 1:
Hongzhi (Steve), Chen's avatar
Hongzhi (Steve), Chen committed
380
381
382
383
                raise DGLError(
                    "Node type name must be specified if there are more than one "
                    "node types."
                )
384
385
386
387
388

        # nothing happen
        if num == 0:
            return

Hongzhi (Steve), Chen's avatar
Hongzhi (Steve), Chen committed
389
        assert num > 0, "Number of new nodes should be larger than one."
390
391
392
393
394
395
396
397
398
399
400
401
402
        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
Hongzhi (Steve), Chen's avatar
Hongzhi (Steve), Chen committed
403
404
405
406
407
            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)
408
409
                hgidx = heterograph_index.create_unitgraph_from_coo(
                    1 if c_etype[0] == c_etype[2] else 2,
Hongzhi (Steve), Chen's avatar
Hongzhi (Steve), Chen committed
410
411
412
413
                    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),
414
415
                    u,
                    v,
Hongzhi (Steve), Chen's avatar
Hongzhi (Steve), Chen committed
416
417
                    ["coo", "csr", "csc"],
                )
418
419
420
                relation_graphs.append(hgidx)
            else:
                # do nothing
Hongzhi (Steve), Chen's avatar
Hongzhi (Steve), Chen committed
421
422
423
                relation_graphs.append(
                    self._graph.get_relation_graph(self.get_etype_id(c_etype))
                )
424
        hgidx = heterograph_index.create_heterograph_from_relations(
Hongzhi (Steve), Chen's avatar
Hongzhi (Steve), Chen committed
425
426
427
428
            metagraph,
            relation_graphs,
            utils.toindex(num_nodes_per_type, "int64"),
        )
429
430
431
432
433
434
435
436
437
        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
438
439

    def add_edges(self, u, v, data=None, etype=None):
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
        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
462
463
464
465
          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.
466
        * If the key of ``data`` does not contain some existing feature fields,
467
468
          those features for the new edges will be created by initializers
          defined with :func:`set_n_initializer` (default initializer fills zeros).
469
        * If the key of ``data`` contains new feature fields, those features for
470
471
472
473
474
475
          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.
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

        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]),
511
        ...             {'h': torch.tensor([[1.], [2.]]), 'w': torch.ones(2, 1)})
512
513
514
515
516
517
518
519
520
521
522
523
        >>> 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({
524
525
526
527
528
        ...     ('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]))
        ...     })
529
530
531
532
533
        >>> 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
534
        >>> g.add_edges(torch.tensor([3]), torch.tensor([3]), etype='plays')
535
536
537
538
539
540
541
542
543
544
        >>> g.number_of_edges('plays')
        5

        See Also
        --------
        add_nodes
        remove_nodes
        remove_edges
        """
        # TODO(xiangsx): block do not support add_edges
Hongzhi (Steve), Chen's avatar
Hongzhi (Steve), Chen committed
545
546
        u = utils.prepare_tensor(self, u, "u")
        v = utils.prepare_tensor(self, v, "v")
547
548
549

        if etype is None:
            if self._graph.number_of_etypes() != 1:
Hongzhi (Steve), Chen's avatar
Hongzhi (Steve), Chen committed
550
551
552
553
                raise DGLError(
                    "Edge type name must be specified if there are more than one "
                    "edge types."
                )
554
555
556
557
558

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

Hongzhi (Steve), Chen's avatar
Hongzhi (Steve), Chen committed
559
560
561
562
        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."
        )
563
564

        if len(u) == 1 and len(v) > 1:
Hongzhi (Steve), Chen's avatar
Hongzhi (Steve), Chen committed
565
566
567
            u = F.full_1d(
                len(v), F.as_scalar(u), dtype=F.dtype(u), ctx=F.context(u)
            )
568
        if len(v) == 1 and len(u) > 1:
Hongzhi (Steve), Chen's avatar
Hongzhi (Steve), Chen committed
569
570
571
            v = F.full_1d(
                len(u), F.as_scalar(v), dtype=F.dtype(v), ctx=F.context(v)
            )
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600

        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):
Hongzhi (Steve), Chen's avatar
Hongzhi (Steve), Chen committed
601
                old_u, old_v = self.edges(form="uv", order="eid", etype=c_etype)
602
603
604
605
606
607
                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),
Hongzhi (Steve), Chen's avatar
Hongzhi (Steve), Chen committed
608
609
                    ["coo", "csr", "csc"],
                )
610
611
612
613
                relation_graphs.append(hgidx)
            else:
                # do nothing
                # Note: node range change has been handled in add_nodes()
Hongzhi (Steve), Chen's avatar
Hongzhi (Steve), Chen committed
614
615
616
                relation_graphs.append(
                    self._graph.get_relation_graph(self.get_etype_id(c_etype))
                )
617
618

        hgidx = heterograph_index.create_heterograph_from_relations(
Hongzhi (Steve), Chen's avatar
Hongzhi (Steve), Chen committed
619
620
621
622
            metagraph,
            relation_graphs,
            utils.toindex(num_nodes_per_type, "int64"),
        )
623
624
625
626
627
628
629
630
631
632
        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()

633
    def remove_edges(self, eids, etype=None, store_ids=False):
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
        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.
649
650
651
652
        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.
653

654
655
        Notes
        -----
656
        This function preserves the batch information.
657

658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
        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.]])

678
679
680
681
682
683
684
685
686
687
688
        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])

689
690
691
        **Heterogeneous Graphs with Multiple Edge Types**

        >>> g = dgl.heterograph({
692
693
694
695
696
        ...     ('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]))
        ...     })
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
        >>> 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:
Hongzhi (Steve), Chen's avatar
Hongzhi (Steve), Chen committed
713
714
715
716
717
                raise DGLError(
                    "Edge type name must be specified if there are more than one "
                    "edge types."
                )
        eids = utils.prepare_tensor(self, eids, "u")
718
719
720
        if len(eids) == 0:
            # no edge to delete
            return
Hongzhi (Steve), Chen's avatar
Hongzhi (Steve), Chen committed
721
722
723
724
725
        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)
        )
726
727
728
729
730
731
732

        # 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):
Hongzhi (Steve), Chen's avatar
Hongzhi (Steve), Chen committed
733
                origin_eids = self.edges(form="eid", order="eid", etype=c_etype)
734
735
                edges[c_etype] = utils.compensate(eids, origin_eids)
            else:
Hongzhi (Steve), Chen's avatar
Hongzhi (Steve), Chen committed
736
737
738
                edges[c_etype] = self.edges(
                    form="eid", order="eid", etype=c_etype
                )
739

740
741
742
743
        # 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)
Hongzhi (Steve), Chen's avatar
Hongzhi (Steve), Chen committed
744
745
746
747
748
749
750
751
            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.0, F.float32, self.device),
            )
752
            c_etype_batch_num_edges = self._batch_num_edges[c_etype]
Hongzhi (Steve), Chen's avatar
Hongzhi (Steve), Chen committed
753
754
755
756
757
758
759
760
761
762
            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
            )

        sub_g = self.edge_subgraph(
            edges, relabel_nodes=False, store_ids=store_ids
        )
763
764
765
766
        self._graph = sub_g._graph
        self._node_frames = sub_g._node_frames
        self._edge_frames = sub_g._edge_frames

767
    def remove_nodes(self, nids, ntype=None, store_ids=False):
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
        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.
783
784
785
786
        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.
787

788
789
        Notes
        -----
790
        This function preserves the batch information.
791

792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
        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.]])

813
814
815
816
817
818
819
820
821
822
823
824
825
        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])

826
827
828
        **Heterogeneous Graphs with Multiple Node Types**

        >>> g = dgl.heterograph({
829
830
831
832
833
        ...     ('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]))
        ...     })
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
        >>> 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:
Hongzhi (Steve), Chen's avatar
Hongzhi (Steve), Chen committed
854
855
856
857
                raise DGLError(
                    "Node type name must be specified if there are more than one "
                    "node types."
                )
Minjie Wang's avatar
Minjie Wang committed
858

Hongzhi (Steve), Chen's avatar
Hongzhi (Steve), Chen committed
859
        nids = utils.prepare_tensor(self, nids, "u")
860
861
862
        if len(nids) == 0:
            # no node to delete
            return
Hongzhi (Steve), Chen's avatar
Hongzhi (Steve), Chen committed
863
864
865
866
867
        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)
        )
868
869
870
871
872

        ntid = self.get_ntype_id(ntype)
        nodes = {}
        for c_ntype in self.ntypes:
            if self.get_ntype_id(c_ntype) == ntid:
873
                target_ntype = c_ntype
874
875
876
877
878
                original_nids = self.nodes(c_ntype)
                nodes[c_ntype] = utils.compensate(nids, original_nids)
            else:
                nodes[c_ntype] = self.nodes(c_ntype)

879
880
881
        # If the graph is batched, update batch_num_nodes
        batched = self._batch_num_nodes is not None
        if batched:
Hongzhi (Steve), Chen's avatar
Hongzhi (Steve), Chen committed
882
883
884
885
886
887
888
889
            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.0, F.float32, self.device),
            )
890
891
            c_ntype_batch_num_nodes = self._batch_num_nodes[target_ntype]
            batch_num_removed_nodes = segment.segment_reduce(
Hongzhi (Steve), Chen's avatar
Hongzhi (Steve), Chen committed
892
893
894
895
896
897
898
                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
            )
899
            # Record old num_edges to check later whether some edges were removed
Hongzhi (Steve), Chen's avatar
Hongzhi (Steve), Chen committed
900
901
902
903
            old_num_edges = {
                c_etype: self._graph.number_of_edges(self.get_etype_id(c_etype))
                for c_etype in self.canonical_etypes
            }
904

905
        # node_subgraph
906
907
        # If batch_num_edges is to be updated, record the original edge IDs
        sub_g = self.subgraph(nodes, store_ids=store_ids or batched)
908
909
910
911
        self._graph = sub_g._graph
        self._node_frames = sub_g._node_frames
        self._edge_frames = sub_g._edge_frames

912
913
914
        # If the graph is batched, update batch_num_edges
        if batched:
            canonical_etypes = [
Hongzhi (Steve), Chen's avatar
Hongzhi (Steve), Chen committed
915
916
917
918
919
                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]
            ]
920
921
922
923

            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(
Hongzhi (Steve), Chen's avatar
Hongzhi (Steve), Chen committed
924
925
                        (self.batch_size,), F.int64, self.device
                    )
926
927
                    continue

Hongzhi (Steve), Chen's avatar
Hongzhi (Steve), Chen committed
928
929
930
                one_hot_left_edges = F.zeros(
                    (old_num_edges[c_etype],), F.float32, self.device
                )
931
                eids = self.edges[c_etype].data[EID]
Hongzhi (Steve), Chen's avatar
Hongzhi (Steve), Chen committed
932
933
934
935
936
                one_hot_left_edges = F.scatter_row(
                    one_hot_left_edges,
                    eids,
                    F.full_1d(len(eids), 1.0, F.float32, self.device),
                )
937
                batch_num_left_edges = segment.segment_reduce(
Hongzhi (Steve), Chen's avatar
Hongzhi (Steve), Chen committed
938
939
940
941
942
943
944
                    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
                )
945
946
947
948
949
950
951

        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)

952
953
954
    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
955
        """
956
957
958
        self._batch_num_nodes = None
        self._batch_num_edges = None

Minjie Wang's avatar
Minjie Wang committed
959
960
961
    #################################################################
    # Metagraph query
    #################################################################
Da Zheng's avatar
Da Zheng committed
962

963
964
965
966
967
968
    @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
969
        can be used to get the type, data, and nodes that belong to SRC and DST sets:
970
971
972
973
974
975
976
977
978
979
980

        * :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

981
    @property
Minjie Wang's avatar
Minjie Wang committed
982
    def ntypes(self):
983
        """Return all the node type names in the graph.
Mufei Li's avatar
Mufei Li committed
984
985
986

        Returns
        -------
987
988
989
990
991
992
993
        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
994
995
996

        Examples
        --------
997
998
999
1000
        The following example uses PyTorch backend.

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

1002
1003
1004
1005
1006
        >>> 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
1007
        >>> g.ntypes
1008
        ['game', 'user']
Mufei Li's avatar
Mufei Li committed
1009
        """
1010
        return self._ntypes
Da Zheng's avatar
Da Zheng committed
1011

1012
    @property
Minjie Wang's avatar
Minjie Wang committed
1013
    def etypes(self):
1014
        """Return all the edge type names in the graph.
Mufei Li's avatar
Mufei Li committed
1015
1016
1017

        Returns
        -------
1018
1019
        list[str]
            All the edge type names in a list.
1020
1021
1022

        Notes
        -----
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
        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
1035
1036
1037

        Examples
        --------
1038
1039
1040
1041
        The following example uses PyTorch backend.

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

1043
1044
1045
1046
1047
        >>> 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
1048
        >>> g.etypes
1049
        ['follows', 'follows', 'plays']
Mufei Li's avatar
Mufei Li committed
1050
        """
1051
        return self._etypes
Da Zheng's avatar
Da Zheng committed
1052

Minjie Wang's avatar
Minjie Wang committed
1053
1054
    @property
    def canonical_etypes(self):
1055
        """Return all the canonical edge types in the graph.
Minjie Wang's avatar
Minjie Wang committed
1056

1057
1058
        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
1059
1060
1061

        Returns
        -------
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
        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
1073
1074
1075

        Examples
        --------
1076
1077
1078
1079
        The following example uses PyTorch backend.

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

1081
1082
1083
1084
1085
        >>> 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
1086
        >>> g.canonical_etypes
1087
1088
1089
        [('user', 'follows', 'user'),
         ('user', 'follows', 'game'),
         ('user', 'plays', 'game')]
Minjie Wang's avatar
Minjie Wang committed
1090
1091
1092
        """
        return self._canonical_etypes

1093
    @property
1094
    def srctypes(self):
1095
1096
1097
1098
1099
1100
1101
1102
        """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.
1103
1104
1105

        Returns
        -------
1106
1107
        list[str]
            All the source node type names in a list.
1108

1109
1110
1111
1112
        See Also
        --------
        dsttypes
        is_unibipartite
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137

        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']
1138
1139
1140
1141
1142
        """
        if self.is_unibipartite:
            return sorted(list(self._srctypes_invmap.keys()))
        else:
            return self.ntypes
1143
1144

    @property
1145
    def dsttypes(self):
1146
1147
1148
1149
1150
1151
1152
1153
        """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.
1154
1155
1156

        Returns
        -------
1157
1158
        list[str]
            All the destination node type names in a list.
1159

1160
1161
1162
1163
        See Also
        --------
        srctypes
        is_unibipartite
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188

        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']
1189
1190
1191
1192
1193
        """
        if self.is_unibipartite:
            return sorted(list(self._dsttypes_invmap.keys()))
        else:
            return self.ntypes
1194

Da Zheng's avatar
Da Zheng committed
1195
    def metagraph(self):
1196
        """Return the metagraph of the heterograph.
1197

1198
1199
1200
        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
1201
1202
1203
1204

        Returns
        -------
        networkx.MultiDiGraph
1205
            The metagraph.
Mufei Li's avatar
Mufei Li committed
1206
1207
1208

        Examples
        --------
1209
        The following example uses PyTorch backend.
Mufei Li's avatar
Mufei Li committed
1210

1211
1212
        >>> import dgl
        >>> import torch
Mufei Li's avatar
Mufei Li committed
1213

1214
1215
1216
1217
1218
1219
        >>> 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
1220
1221
1222
        >>> meta_g.nodes()
        NodeView(('user', 'game'))
        >>> meta_g.edges()
1223
        OutMultiEdgeDataView([('user', 'user'), ('user', 'game'), ('user', 'game')])
Minjie Wang's avatar
Minjie Wang committed
1224
        """
1225
1226
1227
        nx_graph = self._graph.metagraph.to_networkx()
        nx_metagraph = nx.MultiDiGraph()
        for u_v in nx_graph.edges:
Hongzhi (Steve), Chen's avatar
Hongzhi (Steve), Chen committed
1228
1229
1230
            srctype, etype, dsttype = self.canonical_etypes[
                nx_graph.edges[u_v]["id"]
            ]
1231
1232
            nx_metagraph.add_edge(srctype, dsttype, etype)
        return nx_metagraph
Minjie Wang's avatar
Minjie Wang committed
1233
1234

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

1237
1238
1239
1240
1241
        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
1242
1243
1244

        Parameters
        ----------
1245
        etype : str or (str, str, str)
1246
            If :attr:`etype` is an edge type (str), it returns the corresponding canonical edge
1247
1248
            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
1249
1250
1251

        Returns
        -------
1252
        (str, str, str)
1253
1254
            The canonical edge type corresponding to the edge type.

Mufei Li's avatar
Mufei Li committed
1255
1256
        Examples
        --------
1257
        The following example uses PyTorch backend.
Mufei Li's avatar
Mufei Li committed
1258

1259
1260
1261
1262
        >>> import dgl
        >>> import torch

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

1264
1265
1266
1267
1268
        >>> 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
1269

1270
        Map an edge type to its corresponding canonical edge type.
Mufei Li's avatar
Mufei Li committed
1271
1272
1273
1274
1275

        >>> g.to_canonical_etype('plays')
        ('user', 'plays', 'game')
        >>> g.to_canonical_etype(('user', 'plays', 'game'))
        ('user', 'plays', 'game')
1276
1277
1278
1279

        See Also
        --------
        canonical_etypes
1280
        """
1281
1282
        if etype is None:
            if len(self.etypes) != 1:
Hongzhi (Steve), Chen's avatar
Hongzhi (Steve), Chen committed
1283
1284
1285
1286
                raise DGLError(
                    "Edge type name must be specified if there are more than one "
                    "edge types."
                )
1287
            etype = self.etypes[0]
Minjie Wang's avatar
Minjie Wang committed
1288
1289
        if isinstance(etype, tuple):
            return etype
1290
        else:
Minjie Wang's avatar
Minjie Wang committed
1291
1292
1293
1294
            ret = self._etype2canonical.get(etype, None)
            if ret is None:
                raise DGLError('Edge type "{}" does not exist.'.format(etype))
            if len(ret) == 0:
Hongzhi (Steve), Chen's avatar
Hongzhi (Steve), Chen committed
1295
1296
1297
1298
                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
1299
1300
1301
            return ret

    def get_ntype_id(self, ntype):
1302
        """Return the ID of the given node type.
Minjie Wang's avatar
Minjie Wang committed
1303
1304
1305

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

Minjie Wang's avatar
Minjie Wang committed
1307
1308
1309
1310
        Parameters
        ----------
        ntype : str
            Node type
Da Zheng's avatar
Da Zheng committed
1311
1312
1313

        Returns
        -------
Minjie Wang's avatar
Minjie Wang committed
1314
1315
        int
        """
1316
        if self.is_unibipartite and ntype is not None:
1317
            # Only check 'SRC/' and 'DST/' prefix when is_unibipartite graph is True.
Hongzhi (Steve), Chen's avatar
Hongzhi (Steve), Chen committed
1318
            if ntype.startswith("SRC/"):
1319
                return self.get_ntype_id_from_src(ntype[4:])
Hongzhi (Steve), Chen's avatar
Hongzhi (Steve), Chen committed
1320
            elif ntype.startswith("DST/"):
1321
1322
1323
1324
                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
1325
        if ntype is None:
1326
            if self.is_unibipartite or len(self._srctypes_invmap) != 1:
Hongzhi (Steve), Chen's avatar
Hongzhi (Steve), Chen committed
1327
1328
1329
1330
                raise DGLError(
                    "Node type name must be specified if there are more than one "
                    "node types."
                )
Minjie Wang's avatar
Minjie Wang committed
1331
            return 0
Hongzhi (Steve), Chen's avatar
Hongzhi (Steve), Chen committed
1332
1333
1334
        ntid = self._srctypes_invmap.get(
            ntype, self._dsttypes_invmap.get(ntype, None)
        )
Minjie Wang's avatar
Minjie Wang committed
1335
1336
1337
        if ntid is None:
            raise DGLError('Node type "{}" does not exist.'.format(ntype))
        return ntid
Da Zheng's avatar
Da Zheng committed
1338

1339
    def get_ntype_id_from_src(self, ntype):
1340
        """Internal function to return the ID of the given SRC node type.
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355

        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:
Hongzhi (Steve), Chen's avatar
Hongzhi (Steve), Chen committed
1356
1357
1358
1359
                raise DGLError(
                    "SRC node type name must be specified if there are more than one "
                    "SRC node types."
                )
1360
            return next(iter(self._srctypes_invmap.values()))
1361
1362
1363
1364
1365
1366
        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):
1367
        """Internal function to return the ID of the given DST node type.
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382

        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:
Hongzhi (Steve), Chen's avatar
Hongzhi (Steve), Chen committed
1383
1384
1385
1386
                raise DGLError(
                    "DST node type name must be specified if there are more than one "
                    "DST node types."
                )
1387
            return next(iter(self._dsttypes_invmap.values()))
1388
1389
1390
1391
1392
        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
1393
1394
    def get_etype_id(self, etype):
        """Return the id of the given edge type.
1395

Minjie Wang's avatar
Minjie Wang committed
1396
1397
1398
1399
1400
1401
1402
        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
1403

1404
1405
        Returns
        -------
Minjie Wang's avatar
Minjie Wang committed
1406
1407
1408
1409
        int
        """
        if etype is None:
            if self._graph.number_of_etypes() != 1:
Hongzhi (Steve), Chen's avatar
Hongzhi (Steve), Chen committed
1410
1411
1412
1413
                raise DGLError(
                    "Edge type name must be specified if there are more than one "
                    "edge types."
                )
Minjie Wang's avatar
Minjie Wang committed
1414
1415
1416
1417
1418
            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
1419

1420
1421
1422
1423
1424
    #################################################################
    # Batching
    #################################################################
    @property
    def batch_size(self):
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
        """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
        """
1463
1464
1465
        return len(self.batch_num_nodes(self.ntypes[0]))

    def batch_num_nodes(self, ntype=None):
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
1502
1503
1504
1505
1506
1507
1508
1509
        """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:
Hongzhi (Steve), Chen's avatar
Hongzhi (Steve), Chen committed
1510
1511
1512
            raise DGLError(
                "Expect ntype in {}, got {}".format(self.ntypes, ntype)
            )
1513

1514
1515
1516
        if self._batch_num_nodes is None:
            self._batch_num_nodes = {}
            for ty in self.ntypes:
Hongzhi (Steve), Chen's avatar
Hongzhi (Steve), Chen committed
1517
1518
1519
                bnn = F.copy_to(
                    F.tensor([self.number_of_nodes(ty)], F.int64), self.device
                )
1520
1521
1522
                self._batch_num_nodes[ty] = bnn
        if ntype is None:
            if len(self.ntypes) != 1:
Hongzhi (Steve), Chen's avatar
Hongzhi (Steve), Chen committed
1523
1524
1525
1526
                raise DGLError(
                    "Node type name must be specified if there are more than one "
                    "node types."
                )
1527
1528
1529
1530
            ntype = self.ntypes[0]
        return self._batch_num_nodes[ntype]

    def set_batch_num_nodes(self, val):
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
        """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.
1557

1558
1559
1560
        >>> g = dgl.graph(([0, 1, 2, 3, 4, 5], [1, 2, 0, 4, 5, 3]))

        Manually set batch information
1561

1562
1563
        >>> g.set_batch_num_nodes(torch.tensor([3, 3]))
        >>> g.set_batch_num_edges(torch.tensor([3, 3]))
1564
1565

        Unbatch the graph.
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
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
        >>> 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
        """
1608
1609
        if not isinstance(val, Mapping):
            if len(self.ntypes) != 1:
Hongzhi (Steve), Chen's avatar
Hongzhi (Steve), Chen committed
1610
1611
1612
1613
                raise DGLError(
                    "Must provide a dictionary when there are multiple node types."
                )
            val = {self.ntypes[0]: val}
1614
1615
1616
        self._batch_num_nodes = val

    def batch_num_edges(self, etype=None):
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
        """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])
        """
1663
1664
1665
        if self._batch_num_edges is None:
            self._batch_num_edges = {}
            for ty in self.canonical_etypes:
Hongzhi (Steve), Chen's avatar
Hongzhi (Steve), Chen committed
1666
1667
1668
                bne = F.copy_to(
                    F.tensor([self.number_of_edges(ty)], F.int64), self.device
                )
1669
1670
1671
                self._batch_num_edges[ty] = bne
        if etype is None:
            if len(self.etypes) != 1:
Hongzhi (Steve), Chen's avatar
Hongzhi (Steve), Chen committed
1672
1673
1674
1675
                raise DGLError(
                    "Edge type name must be specified if there are more than one "
                    "edge types."
                )
1676
            etype = self.canonical_etypes[0]
1677
1678
        else:
            etype = self.to_canonical_etype(etype)
1679
1680
1681
        return self._batch_num_edges[etype]

    def set_batch_num_edges(self, val):
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
        """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
        -----
1694
        This API is always used together with ``set_batch_num_nodes`` to specify batching
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
        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.
1708

1709
1710
1711
        >>> g = dgl.graph(([0, 1, 2, 3, 4, 5], [1, 2, 0, 4, 5, 3]))

        Manually set batch information
1712

1713
1714
        >>> g.set_batch_num_nodes(torch.tensor([3, 3]))
        >>> g.set_batch_num_edges(torch.tensor([3, 3]))
1715
1716

        Unbatch the graph.
1717

1718
        >>> dgl.unbatch(g)
1719
1720
1721
1722
1723
        [Graph(num_nodes=3, num_edges=3,
              ndata_schemes={}
              edata_schemes={}), Graph(num_nodes=3, num_edges=3,
              ndata_schemes={}
              edata_schemes={})]
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758

        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
        """
1759
1760
        if not isinstance(val, Mapping):
            if len(self.etypes) != 1:
Hongzhi (Steve), Chen's avatar
Hongzhi (Steve), Chen committed
1761
1762
1763
1764
                raise DGLError(
                    "Must provide a dictionary when there are multiple edge types."
                )
            val = {self.canonical_etypes[0]: val}
1765
1766
        self._batch_num_edges = val

Minjie Wang's avatar
Minjie Wang committed
1767
1768
1769
    #################################################################
    # View
    #################################################################
Da Zheng's avatar
Da Zheng committed
1770

1771
1772
1773
1774
1775
1776
1777
1778
    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]

1779
    @property
Minjie Wang's avatar
Minjie Wang committed
1780
    def nodes(self):
1781
1782
1783
1784
1785
1786
        """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
1787

Minjie Wang's avatar
Minjie Wang committed
1788
1789
        Examples
        --------
Mufei Li's avatar
Mufei Li committed
1790
1791
        The following example uses PyTorch backend.

1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
        >>> 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
1813

1814
1815
1816
1817
1818
1819
1820
        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
1821
1822
1823
1824

        See Also
        --------
        ndata
1825
        """
1826
        # Todo (Mufei) Replace the syntax g.nodes[...].ndata[...] with g.nodes[...][...]
1827
1828
1829
1830
        return HeteroNodeView(self, self.get_ntype_id)

    @property
    def srcnodes(self):
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
        """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.
1841
1842
1843
1844
1845

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

1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
        >>> 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.]])
1868

1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
        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.]])
1889
1890
1891
1892
1893
1894
1895
1896
1897

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

    @property
    def dstnodes(self):
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
        """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.
1908
1909
1910
1911
1912

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

1913
1914
1915
1916
        >>> import dgl
        >>> import torch

        Create a uni-bipartite graph.
1917

1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
        >>> 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.]])
1955
1956
1957
1958
1959
1960

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

1962
    @property
Minjie Wang's avatar
Minjie Wang committed
1963
    def ndata(self):
1964
1965
1966
1967
1968
        """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
1969

1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
        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
1980
1981
1982

        Examples
        --------
Mufei Li's avatar
Mufei Li committed
1983
1984
        The following example uses PyTorch backend.

1985
1986
        >>> import dgl
        >>> import torch
Mufei Li's avatar
Mufei Li committed
1987

1988
        Set and get feature 'h' for a graph of a single node type.
1989

1990
1991
        >>> g = dgl.graph((torch.tensor([0, 1]), torch.tensor([1, 2])))
        >>> g.ndata['h'] = torch.ones(3, 1)
1992
        >>> g.ndata['h']
1993
1994
1995
        tensor([[1.],
                [1.],
                [1.]])
1996

1997
        Set and get feature 'h' for a graph of multiple node types.
1998

1999
2000
2001
2002
2003
        >>> 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)}
2004
        >>> g.ndata['h']
2005
2006
2007
        {'game': tensor([[0.], [0.]]),
         'player': tensor([[1.], [1.], [1.]])}
        >>> g.ndata['h'] = {'game': torch.ones(2, 1)}
2008
        >>> g.ndata['h']
2009
2010
        {'game': tensor([[1.], [1.]]),
         'player': tensor([[1.], [1.], [1.]])}
2011

Mufei Li's avatar
Mufei Li committed
2012
2013
2014
        See Also
        --------
        nodes
Da Zheng's avatar
Da Zheng committed
2015
        """
2016
2017
2018
2019
2020
2021
2022
2023
2024
        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)

2025
2026
    @property
    def srcdata(self):
2027
        """Return a node data view for setting/getting source node features.
2028

2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
        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.
2044
2045
2046
2047
2048

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

2049
2050
        >>> import dgl
        >>> import torch
2051

2052
        Set and get feature 'h' for a graph of a single source node type.
2053
2054

        >>> g = dgl.heterograph({
2055
2056
2057
2058
2059
        ...     ('user', 'plays', 'game'): (torch.tensor([0, 1]), torch.tensor([1, 2]))})
        >>> g.srcdata['h'] = torch.ones(2, 1)
        >>> g.srcdata['h']
        tensor([[1.],
                [1.]])
2060

2061
        Set and get feature 'h' for a graph of multiple source node types.
2062
2063

        >>> g = dgl.heterograph({
2064
2065
2066
2067
        ...     ('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)}
2068
        >>> g.srcdata['h']
2069
2070
2071
        {'player': tensor([[1.], [1.], [1.]]),
         'user': tensor([[0.], [0.], [0.]])}
        >>> g.srcdata['h'] = {'user': torch.ones(3, 1)}
2072
        >>> g.srcdata['h']
2073
2074
        {'player': tensor([[1.], [1.], [1.]]),
         'user': tensor([[1.], [1.], [1.]])}
2075
2076
2077
2078

        See Also
        --------
        nodes
2079
2080
        ndata
        srcnodes
2081
        """
2082
2083
2084
2085
2086
2087
2088
2089
        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)
2090
2091
2092

    @property
    def dstdata(self):
2093
2094
2095
2096
2097
2098
        """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.
2099

2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
        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.
2110
2111
2112
2113
2114

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

2115
2116
        >>> import dgl
        >>> import torch
2117

2118
        Set and get feature 'h' for a graph of a single destination node type.
2119
2120

        >>> g = dgl.heterograph({
2121
2122
2123
2124
2125
2126
        ...     ('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.]])
2127

2128
        Set and get feature 'h' for a graph of multiple destination node types.
2129
2130

        >>> g = dgl.heterograph({
2131
2132
2133
2134
        ...     ('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)}
2135
        >>> g.dstdata['h']
2136
2137
2138
        {'game': tensor([[0.], [0.], [0.]]),
         'movie': tensor([[1.], [1.]])}
        >>> g.dstdata['h'] = {'game': torch.ones(3, 1)}
2139
        >>> g.dstdata['h']
2140
2141
        {'game': tensor([[1.], [1.], [1.]]),
         'movie': tensor([[1.], [1.]])}
2142
2143
2144
2145

        See Also
        --------
        nodes
2146
2147
        ndata
        dstnodes
2148
        """
2149
2150
2151
2152
2153
2154
2155
2156
        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)
2157

2158
    @property
Minjie Wang's avatar
Minjie Wang committed
2159
    def edges(self):
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
        """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]``.
2192

Minjie Wang's avatar
Minjie Wang committed
2193
2194
        Examples
        --------
Mufei Li's avatar
Mufei Li committed
2195
2196
        The following example uses PyTorch backend.

2197
2198
        >>> import dgl
        >>> import torch
Mufei Li's avatar
Mufei Li committed
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
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
        **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
2238
2239
2240
2241

        See Also
        --------
        edata
2242
        """
2243
        # TODO(Mufei): Replace the syntax g.edges[...].edata[...] with g.edges[...][...]
Minjie Wang's avatar
Minjie Wang committed
2244
        return HeteroEdgeView(self)
2245
2246

    @property
Minjie Wang's avatar
Minjie Wang committed
2247
    def edata(self):
2248
2249
2250
2251
2252
        """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.
2253

2254
2255
2256
2257
2258
        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.
2259

2260
2261
2262
2263
        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
2264
2265
2266

        Examples
        --------
Mufei Li's avatar
Mufei Li committed
2267
2268
        The following example uses PyTorch backend.

2269
2270
        >>> import dgl
        >>> import torch
Mufei Li's avatar
Mufei Li committed
2271

2272
        Set and get feature 'h' for a graph of a single edge type.
2273

2274
2275
        >>> g = dgl.graph((torch.tensor([0, 1]), torch.tensor([1, 2])))
        >>> g.edata['h'] = torch.ones(2, 1)
2276
        >>> g.edata['h']
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
        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)}
2289
        >>> g.edata['h']
2290
2291
2292
        {('user', 'follows', 'user'): tensor([[0.], [0.]]),
         ('user', 'plays', 'user'): tensor([[1.], [1.]])}
        >>> g.edata['h'] = {('user', 'follows', 'user'): torch.ones(2, 1)}
2293
        >>> g.edata['h']
2294
2295
        {('user', 'follows', 'user'): tensor([[1.], [1.]]),
         ('user', 'plays', 'user'): tensor([[1.], [1.]])}
2296

Mufei Li's avatar
Mufei Li committed
2297
2298
2299
        See Also
        --------
        edges
2300
        """
2301
2302
2303
2304
        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
2305
2306
2307

    def _find_etypes(self, key):
        etypes = [
Hongzhi (Steve), Chen's avatar
Hongzhi (Steve), Chen committed
2308
2309
2310
2311
2312
2313
2314
2315
            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)
        ]
Minjie Wang's avatar
Minjie Wang committed
2316
2317
2318
2319
2320
        return etypes

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

2321
        You can get a relation slice with ``self[srctype, etype, dsttype]``, where
Minjie Wang's avatar
Minjie Wang committed
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
        ``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.

2334
        If there are multiple canonical edge types found, then the source/edge/destination
Minjie Wang's avatar
Minjie Wang committed
2335
2336
2337
2338
        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
2339
        common features of the original source/destination types.  Therefore they are not
Minjie Wang's avatar
Minjie Wang committed
2340
        shared with the original graph.  Edge type is similar.
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395

        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
2396
        """
Hongzhi (Steve), Chen's avatar
Hongzhi (Steve), Chen committed
2397
2398
2399
2400
2401
        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'])."
        )
Minjie Wang's avatar
Minjie Wang committed
2402

2403
        orig_key = key
Minjie Wang's avatar
Minjie Wang committed
2404
2405
2406
2407
2408
2409
2410
        if not isinstance(key, tuple):
            key = (SLICE_FULL, key, SLICE_FULL)

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

        etypes = self._find_etypes(key)
2411
2412

        if len(etypes) == 0:
Hongzhi (Steve), Chen's avatar
Hongzhi (Steve), Chen committed
2413
2414
2415
2416
2417
            raise DGLError(
                'Invalid key "{}". Must be one of the edge types.'.format(
                    orig_key
                )
            )
2418

Minjie Wang's avatar
Minjie Wang committed
2419
2420
2421
        if len(etypes) == 1:
            # no ambiguity: return the unitgraph itself
            srctype, etype, dsttype = self._canonical_etypes[etypes[0]]
2422
            stid = self.get_ntype_id_from_src(srctype)
Minjie Wang's avatar
Minjie Wang committed
2423
            etid = self.get_etype_id((srctype, etype, dsttype))
2424
            dtid = self.get_ntype_id_from_dst(dsttype)
Minjie Wang's avatar
Minjie Wang committed
2425
2426
2427
2428
2429
2430
            new_g = self._graph.get_relation_graph(etid)

            if stid == dtid:
                new_ntypes = [srctype]
                new_nframes = [self._node_frames[stid]]
            else:
2431
                new_ntypes = ([srctype], [dsttype])
Minjie Wang's avatar
Minjie Wang committed
2432
2433
2434
                new_nframes = [self._node_frames[stid], self._node_frames[dtid]]
            new_etypes = [etype]
            new_eframes = [self._edge_frames[etid]]
2435

Hongzhi (Steve), Chen's avatar
Hongzhi (Steve), Chen committed
2436
2437
2438
            return self.__class__(
                new_g, new_ntypes, new_etypes, new_nframes, new_eframes
            )
Minjie Wang's avatar
Minjie Wang committed
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
        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),
Hongzhi (Steve), Chen's avatar
Hongzhi (Steve), Chen committed
2452
2453
                    combine_frames(self._node_frames, dtids),
                ]
Minjie Wang's avatar
Minjie Wang committed
2454
2455
2456
2457
2458
2459
2460
            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
Hongzhi (Steve), Chen's avatar
Hongzhi (Steve), Chen committed
2461
2462
2463
            new_hg = self.__class__(
                new_g, new_ntypes, new_etypes, new_nframes, new_eframes
            )
Minjie Wang's avatar
Minjie Wang committed
2464
2465
2466
2467

            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
Hongzhi (Steve), Chen's avatar
Hongzhi (Steve), Chen committed
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
            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
            )
Minjie Wang's avatar
Minjie Wang committed
2483
2484
2485
2486
2487
2488
2489
2490
2491
            new_hg.edata[EID] = F.zerocopy_from_dgl_ndarray(flat.induced_eid)

            return new_hg

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

    def number_of_nodes(self, ntype=None):
2492
        """Alias of :meth:`num_nodes`"""
2493
2494
2495
        return self.num_nodes(ntype)

    def num_nodes(self, ntype=None):
2496
        """Return the number of nodes in the graph.
Da Zheng's avatar
Da Zheng committed
2497
2498
2499

        Parameters
        ----------
Minjie Wang's avatar
Minjie Wang committed
2500
        ntype : str, optional
2501
            The node type name. If given, it returns the number of nodes of the
2502
            type. If not given (default), it returns the total number of nodes of all types.
2503
2504
2505
2506

        Returns
        -------
        int
2507
            The number of nodes.
Da Zheng's avatar
Da Zheng committed
2508
2509
2510

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

2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
        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
2532
        """
2533
        if ntype is None:
Hongzhi (Steve), Chen's avatar
Hongzhi (Steve), Chen committed
2534
2535
2536
2537
2538
2539
            return sum(
                [
                    self._graph.number_of_nodes(ntid)
                    for ntid in range(len(self.ntypes))
                ]
            )
2540
2541
        else:
            return self._graph.number_of_nodes(self.get_ntype_id(ntype))
2542

2543
    def number_of_src_nodes(self, ntype=None):
2544
        """Alias of :meth:`num_src_nodes`"""
2545
        return self.num_src_nodes(ntype)
2546

2547
    def num_src_nodes(self, ntype=None):
2548
2549
2550
2551
2552
2553
2554
2555
        """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.
2556
2557
2558
2559

        Parameters
        ----------
        ntype : str, optional
2560
2561
            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
2562
            nodes summed over all source node types.
2563
2564
2565
2566
2567
2568

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

2569
2570
2571
2572
2573
        See Also
        --------
        num_dst_nodes
        is_unibipartite

2574
2575
        Examples
        --------
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
        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')
2597
        2
2598
2599
2600
2601
        >>> g.num_src_nodes('user')
        5
        >>> g.num_src_nodes()
        7
2602
        """
2603
        if ntype is None:
Hongzhi (Steve), Chen's avatar
Hongzhi (Steve), Chen committed
2604
2605
2606
2607
2608
2609
            return sum(
                [
                    self._graph.number_of_nodes(self.get_ntype_id_from_src(nty))
                    for nty in self.srctypes
                ]
            )
2610
        else:
Hongzhi (Steve), Chen's avatar
Hongzhi (Steve), Chen committed
2611
2612
2613
            return self._graph.number_of_nodes(
                self.get_ntype_id_from_src(ntype)
            )
2614
2615

    def number_of_dst_nodes(self, ntype=None):
2616
2617
        """Alias of :func:`num_dst_nodes`"""
        return self.num_dst_nodes(ntype)
2618

2619
    def num_dst_nodes(self, ntype=None):
2620
2621
2622
2623
2624
2625
2626
2627
        """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.
2628
2629
2630
2631

        Parameters
        ----------
        ntype : str, optional
2632
2633
2634
            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.
2635
2636
2637
2638
2639
2640

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

2641
2642
2643
2644
2645
        See Also
        --------
        num_src_nodes
        is_unibipartite

2646
2647
        Examples
        --------
2648
2649
2650
2651
2652
2653
2654
2655
2656
        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()
2657
        3
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673

        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
2674
        """
2675
        if ntype is None:
Hongzhi (Steve), Chen's avatar
Hongzhi (Steve), Chen committed
2676
2677
2678
2679
2680
2681
            return sum(
                [
                    self._graph.number_of_nodes(self.get_ntype_id_from_dst(nty))
                    for nty in self.dsttypes
                ]
            )
2682
        else:
Hongzhi (Steve), Chen's avatar
Hongzhi (Steve), Chen committed
2683
2684
2685
            return self._graph.number_of_nodes(
                self.get_ntype_id_from_dst(ntype)
            )
2686

Minjie Wang's avatar
Minjie Wang committed
2687
    def number_of_edges(self, etype=None):
2688
2689
2690
2691
        """Alias of :func:`num_edges`"""
        return self.num_edges(etype)

    def num_edges(self, etype=None):
2692
        """Return the number of edges in the graph.
2693
2694
2695

        Parameters
        ----------
2696
2697
2698
2699
2700
2701
2702
2703
2704
        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
2705
2706
2707
2708

        Returns
        -------
        int
2709
            The number of edges.
Da Zheng's avatar
Da Zheng committed
2710

2711
2712
        Examples
        --------
Mufei Li's avatar
Mufei Li committed
2713

2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
        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
2730
        2
2731
2732
2733
2734
2735
2736
        >>> 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
2737
        2
2738
2739
        >>> g.num_edges(('user', 'follows', 'game'))
        3
2740
        """
2741
        if etype is None:
Hongzhi (Steve), Chen's avatar
Hongzhi (Steve), Chen committed
2742
2743
2744
2745
2746
2747
            return sum(
                [
                    self._graph.number_of_edges(etid)
                    for etid in range(len(self.canonical_etypes))
                ]
            )
2748
2749
        else:
            return self._graph.number_of_edges(self.get_etype_id(etype))
Minjie Wang's avatar
Minjie Wang committed
2750
2751
2752

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

2755
2756
2757
2758
        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).
2759

Mufei Li's avatar
Mufei Li committed
2760
2761
2762
        Returns
        -------
        bool
2763
            True if the graph is a multigraph.
2764
2765
2766

        Notes
        -----
2767
        Checking whether the graph is a multigraph could be expensive for a large one.
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799

        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
2800
        """
2801
        return self._graph.is_multigraph()
Minjie Wang's avatar
Minjie Wang committed
2802

2803
2804
    @property
    def is_homogeneous(self):
2805
        """Return whether the graph is a homogeneous graph.
2806
2807
2808
2809
2810
2811

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

        Returns
        -------
        bool
2812
            True if the graph is a homogeneous graph.
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838

        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

2839
2840
    @property
    def idtype(self):
2841
2842
        """The data type for storing the structure-related graph information
        such as node and edge IDs.
2843
2844
2845

        Returns
        -------
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
        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
2865
2866
2867
2868
2869

        See Also
        --------
        long
        int
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
        """
        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

2884
    def has_nodes(self, vid, ntype=None):
2885
        """Return whether the graph contains the given nodes.
Da Zheng's avatar
Da Zheng committed
2886
2887
2888

        Parameters
        ----------
2889
        vid : node ID(s)
2890
2891
2892
2893
2894
2895
            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.
2896

Minjie Wang's avatar
Minjie Wang committed
2897
        ntype : str, optional
2898
2899
            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
2900
2901
2902

        Returns
        -------
2903
        bool or bool Tensor
2904
2905
            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
2906
2907
2908

        Examples
        --------
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923

        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.

2924
        >>> g.has_nodes(0, 'user')
Da Zheng's avatar
Da Zheng committed
2925
        True
2926
        >>> g.has_nodes(3, 'game')
Da Zheng's avatar
Da Zheng committed
2927
        False
2928
2929
        >>> g.has_nodes(torch.tensor([3, 0, 1]), 'game')
        tensor([False,  True,  True])
Da Zheng's avatar
Da Zheng committed
2930
        """
2931
        vid_tensor = utils.prepare_tensor(self, vid, "vid")
Hongzhi (Steve), Chen's avatar
Hongzhi (Steve), Chen committed
2932
2933
2934
2935
2936
        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.")
        ret = self._graph.has_nodes(self.get_ntype_id(ntype), vid_tensor)
2937
2938
2939
2940
        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
2941

2942
    def has_edges_between(self, u, v, etype=None):
2943
        """Return whether the graph contains the given edges.
Da Zheng's avatar
Da Zheng committed
2944
2945
2946

        Parameters
        ----------
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
        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
2972
2973
2974

        Returns
        -------
2975
        bool or bool Tensor
2976
2977
            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
2978
2979
2980

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

2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
        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
2994
        True
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
        >>> 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
3016
        """
3017
        srctype, _, dsttype = self.to_canonical_etype(etype)
Hongzhi (Steve), Chen's avatar
Hongzhi (Steve), Chen committed
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
        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")
3028
        ret = self._graph.has_edges_between(
Hongzhi (Steve), Chen's avatar
Hongzhi (Steve), Chen committed
3029
3030
            self.get_etype_id(etype), u_tensor, v_tensor
        )
3031
3032
3033
3034
        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
3035

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

3039
3040
        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
3041
3042
3043
3044

        Parameters
        ----------
        v : int
3045
3046
            The node ID. If the graph has multiple edge types, the ID is for the destination
            type corresponding to the edge type.
3047
3048
3049
3050
3051
3052
3053
3054
3055
        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
3056
3057
3058

        Returns
        -------
3059
3060
        Tensor
            The predecessors of :attr:`v` with the specified edge type.
Da Zheng's avatar
Da Zheng committed
3061
3062
3063
3064
3065

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

3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
        >>> 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
3085
        tensor([0])
Da Zheng's avatar
Da Zheng committed
3086
3087
3088
3089
3090

        See Also
        --------
        successors
        """
3091
        if not self.has_nodes(v, self.to_canonical_etype(etype)[-1]):
Hongzhi (Steve), Chen's avatar
Hongzhi (Steve), Chen committed
3092
            raise DGLError("Non-existing node ID {}".format(v))
3093
        return self._graph.predecessors(self.get_etype_id(etype), v)
Da Zheng's avatar
Da Zheng committed
3094

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

3098
3099
        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
3100
3101
3102
3103

        Parameters
        ----------
        v : int
3104
3105
            The node ID. If the graph has multiple edge types, the ID is for the source
            type corresponding to the edge type.
3106
3107
3108
3109
3110
3111
3112
3113
        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
3114
3115
3116

        Returns
        -------
3117
3118
        Tensor
            The successors of :attr:`v` with the specified edge type.
Da Zheng's avatar
Da Zheng committed
3119
3120
3121
3122
3123

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

3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
        >>> 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
3144
3145
3146
3147
3148

        See Also
        --------
        predecessors
        """
3149
        if not self.has_nodes(v, self.to_canonical_etype(etype)[0]):
Hongzhi (Steve), Chen's avatar
Hongzhi (Steve), Chen committed
3150
            raise DGLError("Non-existing node ID {}".format(v))
3151
        return self._graph.successors(self.get_etype_id(etype), v)
Da Zheng's avatar
Da Zheng committed
3152

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

Da Zheng's avatar
Da Zheng committed
3156
3157
        Parameters
        ----------
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
        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.
3173
3174
3175
3176
3177
        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.
3178
3179
3180
3181
3182
3183
3184
3185
        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
3186
3187
3188

        Returns
        -------
3189
        Tensor, or (Tensor, Tensor, Tensor)
Mufei Li's avatar
Mufei Li committed
3190

3191
3192
            * 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])``.
3193
3194
            * 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
3195
              (including parallel edges) from ``eu[i]`` to ``ev[i]`` in this case.
Da Zheng's avatar
Da Zheng committed
3196
3197
3198

        Notes
        -----
3199
3200
        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
3201

3202
3203
        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.
3204

Da Zheng's avatar
Da Zheng committed
3205
3206
3207
3208
        Examples
        --------
        The following example uses PyTorch backend.

3209
3210
        >>> import dgl
        >>> import torch
Mufei Li's avatar
Mufei Li committed
3211

3212
        Create a homogeneous graph.
Mufei Li's avatar
Mufei Li committed
3213

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

3216
3217
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
        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
3246
        """
Hongzhi (Steve), Chen's avatar
Hongzhi (Steve), Chen committed
3247
3248
3249
        is_int = isinstance(u, numbers.Integral) and isinstance(
            v, numbers.Integral
        )
3250
        srctype, _, dsttype = self.to_canonical_etype(etype)
Hongzhi (Steve), Chen's avatar
Hongzhi (Steve), Chen committed
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
        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("u 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("v contains invalid node IDs")
3261
3262

        if return_uv:
3263
            return self._graph.edge_ids_all(self.get_etype_id(etype), u, v)
3264
        else:
3265
3266
3267
3268
3269
            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)
Hongzhi (Steve), Chen's avatar
Hongzhi (Steve), Chen committed
3270
3271
3272
3273
3274
3275
3276
                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)),
                    )
                )
3277
            return F.as_scalar(eid) if is_int else eid
Da Zheng's avatar
Da Zheng committed
3278

Minjie Wang's avatar
Minjie Wang committed
3279
    def find_edges(self, eid, etype=None):
3280
        """Return the source and destination node ID(s) given the edge ID(s).
Da Zheng's avatar
Da Zheng committed
3281
3282
3283

        Parameters
        ----------
3284
        eid : edge ID(s)
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
            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
3300
3301
3302

        Returns
        -------
3303
        Tensor
3304
3305
            The source node IDs of the edges. The i-th element is the source node ID of
            the i-th edge.
3306
        Tensor
3307
3308
            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
3309
3310
3311
3312
3313

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

3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
        >>> 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
3334
        """
Hongzhi (Steve), Chen's avatar
Hongzhi (Steve), Chen committed
3335
        eid = utils.prepare_tensor(self, eid, "eid")
3336
3337
3338
        if len(eid) > 0:
            min_eid = F.as_scalar(F.min(eid, 0))
            if min_eid < 0:
Hongzhi (Steve), Chen's avatar
Hongzhi (Steve), Chen committed
3339
                raise DGLError("Invalid edge ID {:d}".format(min_eid))
3340
3341
            max_eid = F.as_scalar(F.max(eid, 0))
            if max_eid >= self.num_edges(etype):
Hongzhi (Steve), Chen's avatar
Hongzhi (Steve), Chen committed
3342
                raise DGLError("Invalid edge ID {:d}".format(max_eid))
3343

3344
        if len(eid) == 0:
3345
3346
            empty = F.copy_to(F.tensor([], self.idtype), self.device)
            return empty, empty
Minjie Wang's avatar
Minjie Wang committed
3347
        src, dst, _ = self._graph.find_edges(self.get_etype_id(etype), eid)
3348
        return src, dst
Da Zheng's avatar
Da Zheng committed
3349

Hongzhi (Steve), Chen's avatar
Hongzhi (Steve), Chen committed
3350
    def in_edges(self, v, form="uv", etype=None):
3351
        """Return the incoming edges of the given nodes.
Da Zheng's avatar
Da Zheng committed
3352
3353
3354

        Parameters
        ----------
3355
3356
        v : node ID(s)
            The node IDs. The allowed formats are:
3357

3358
3359
3360
3361
            * ``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
3362
        form : str, optional
3363
            The result format, which can be one of the following:
3364
3365
3366
3367
3368
3369
3370
3371
3372

            - ``'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]`.
3373
3374
3375
3376
3377
3378
3379
3380
        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
3381
3382
3383

        Returns
        -------
3384
3385
3386
        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
3387
3388
3389
3390
3391

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

3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
        >>> 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
3422
        """
Hongzhi (Steve), Chen's avatar
Hongzhi (Steve), Chen committed
3423
        v = utils.prepare_tensor(self, v, "v")
Minjie Wang's avatar
Minjie Wang committed
3424
        src, dst, eid = self._graph.in_edges(self.get_etype_id(etype), v)
Hongzhi (Steve), Chen's avatar
Hongzhi (Steve), Chen committed
3425
        if form == "all":
3426
            return src, dst, eid
Hongzhi (Steve), Chen's avatar
Hongzhi (Steve), Chen committed
3427
        elif form == "uv":
3428
            return src, dst
Hongzhi (Steve), Chen's avatar
Hongzhi (Steve), Chen committed
3429
        elif form == "eid":
3430
            return eid
3431
        else:
Hongzhi (Steve), Chen's avatar
Hongzhi (Steve), Chen committed
3432
3433
3434
            raise DGLError(
                'Invalid form: {}. Must be "all", "uv" or "eid".'.format(form)
            )
3435

Hongzhi (Steve), Chen's avatar
Hongzhi (Steve), Chen committed
3436
    def out_edges(self, u, form="uv", etype=None):
3437
        """Return the outgoing edges of the given nodes.
Da Zheng's avatar
Da Zheng committed
3438
3439
3440

        Parameters
        ----------
3441
3442
        u : node ID(s)
            The node IDs. The allowed formats are:
3443

3444
3445
3446
3447
            * ``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
3448
        form : str, optional
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
            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]`.
3459
3460
3461
3462
3463
3464
3465
3466
        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.
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493

        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
3494

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

3497
3498
3499
3500
3501
3502
        >>> 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
3503

3504
        See Also
Da Zheng's avatar
Da Zheng committed
3505
        --------
3506
3507
        edges
        in_edges
Da Zheng's avatar
Da Zheng committed
3508
        """
Hongzhi (Steve), Chen's avatar
Hongzhi (Steve), Chen committed
3509
        u = utils.prepare_tensor(self, u, "u")
3510
        srctype, _, _ = self.to_canonical_etype(etype)
Hongzhi (Steve), Chen's avatar
Hongzhi (Steve), Chen committed
3511
3512
3513
3514
        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
3515
        src, dst, eid = self._graph.out_edges(self.get_etype_id(etype), u)
Hongzhi (Steve), Chen's avatar
Hongzhi (Steve), Chen committed
3516
        if form == "all":
3517
            return src, dst, eid
Hongzhi (Steve), Chen's avatar
Hongzhi (Steve), Chen committed
3518
        elif form == "uv":
3519
            return src, dst
Hongzhi (Steve), Chen's avatar
Hongzhi (Steve), Chen committed
3520
        elif form == "eid":
3521
            return eid
3522
        else:
Hongzhi (Steve), Chen's avatar
Hongzhi (Steve), Chen committed
3523
3524
3525
            raise DGLError(
                'Invalid form: {}. Must be "all", "uv" or "eid".'.format(form)
            )
3526

Hongzhi (Steve), Chen's avatar
Hongzhi (Steve), Chen committed
3527
    def all_edges(self, form="uv", order="eid", etype=None):
3528
        """Return all edges with the specified edge type.
Da Zheng's avatar
Da Zheng committed
3529
3530
3531
3532

        Parameters
        ----------
        form : str, optional
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
            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
3549
        etype : str or tuple of str, optional
3550
3551
3552
3553
            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
3554
3555
3556

        Returns
        -------
3557
3558
3559
        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
3560
3561
3562
3563
3564

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

3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
        >>> 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
3579
        >>> g.all_edges(form='all', order='srcdst')
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
        (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
3596
        """
Minjie Wang's avatar
Minjie Wang committed
3597
        src, dst, eid = self._graph.edges(self.get_etype_id(etype), order)
Hongzhi (Steve), Chen's avatar
Hongzhi (Steve), Chen committed
3598
        if form == "all":
3599
            return src, dst, eid
Hongzhi (Steve), Chen's avatar
Hongzhi (Steve), Chen committed
3600
        elif form == "uv":
3601
            return src, dst
Hongzhi (Steve), Chen's avatar
Hongzhi (Steve), Chen committed
3602
        elif form == "eid":
3603
            return eid
3604
        else:
Hongzhi (Steve), Chen's avatar
Hongzhi (Steve), Chen committed
3605
3606
3607
            raise DGLError(
                'Invalid form: {}. Must be "all", "uv" or "eid".'.format(form)
            )
3608

Minjie Wang's avatar
Minjie Wang committed
3609
    def in_degrees(self, v=ALL, etype=None):
3610
3611
3612
        """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
3613
3614
3615

        Parameters
        ----------
3616
3617
        v : node IDs
            The node IDs. The allowed formats are:
3618

3619
3620
3621
3622
            * ``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.
3623

3624
3625
3626
3627
3628
3629
3630
3631
3632
            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
3633
3634
3635

        Returns
        -------
3636
3637
3638
        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
3639
3640
3641
3642
3643

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

3644
3645
        >>> import dgl
        >>> import torch
Mufei Li's avatar
Mufei Li committed
3646

3647
        Create a homogeneous graph.
Mufei Li's avatar
Mufei Li committed
3648

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

3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
        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
3673
        """
3674
        dsttype = self.to_canonical_etype(etype)[2]
Minjie Wang's avatar
Minjie Wang committed
3675
        etid = self.get_etype_id(etype)
3676
        if is_all(v):
3677
            v = self.dstnodes(dsttype)
Hongzhi (Steve), Chen's avatar
Hongzhi (Steve), Chen committed
3678
        v_tensor = utils.prepare_tensor(self, v, "v")
3679
        deg = self._graph.in_degrees(etid, v_tensor)
3680
3681
        if isinstance(v, numbers.Integral):
            return F.as_scalar(deg)
3682
        else:
3683
            return deg
Da Zheng's avatar
Da Zheng committed
3684

Mufei Li's avatar
Mufei Li committed
3685
    def out_degrees(self, u=ALL, etype=None):
3686
3687
3688
        """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.
3689
3690
3691

        Parameters
        ----------
3692
3693
        u : node IDs
            The node IDs. The allowed formats are:
3694

3695
3696
3697
3698
            * ``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.
3699

3700
3701
3702
3703
3704
3705
3706
3707
3708
            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.
3709
3710
3711

        Returns
        -------
3712
3713
3714
        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.
3715
3716
3717
3718
3719

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

3720
3721
        >>> import dgl
        >>> import torch
Mufei Li's avatar
Mufei Li committed
3722

3723
        Create a homogeneous graph.
Mufei Li's avatar
Mufei Li committed
3724

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

3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
        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])
3745
3746
3747

        See Also
        --------
3748
        in_degrees
3749
        """
3750
        srctype = self.to_canonical_etype(etype)[0]
Minjie Wang's avatar
Minjie Wang committed
3751
        etid = self.get_etype_id(etype)
Mufei Li's avatar
Mufei Li committed
3752
        if is_all(u):
3753
            u = self.srcnodes(srctype)
Hongzhi (Steve), Chen's avatar
Hongzhi (Steve), Chen committed
3754
3755
3756
3757
3758
3759
        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")
        deg = self._graph.out_degrees(etid, utils.prepare_tensor(self, u, "u"))
3760
3761
        if isinstance(u, numbers.Integral):
            return F.as_scalar(deg)
3762
        else:
3763
            return deg
Minjie Wang's avatar
Minjie Wang committed
3764

Hongzhi (Steve), Chen's avatar
Hongzhi (Steve), Chen committed
3765
3766
3767
    def adjacency_matrix(
        self, transpose=False, ctx=F.cpu(), scipy_fmt=None, etype=None
    ):
3768
        """Alias of :meth:`adj`"""
3769
3770
        return self.adj(transpose, ctx, scipy_fmt, etype)

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

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

3777
3778
        When transpose is True, a row represents the destination and a column
        represents the source.
3779
3780
3781

        Parameters
        ----------
Mufei Li's avatar
Mufei Li committed
3782
        transpose : bool, optional
3783
            A flag to transpose the returned adjacency matrix. (Default: False)
Mufei Li's avatar
Mufei Li committed
3784
3785
3786
        ctx : context, optional
            The context of returned adjacency matrix. (Default: cpu)
        scipy_fmt : str, optional
Minjie Wang's avatar
Minjie Wang committed
3787
            If specified, return a scipy sparse matrix in the given format.
Mufei Li's avatar
Mufei Li committed
3788
            Otherwise, return a backend dependent sparse tensor. (Default: None)
3789
3790
3791
3792
3793
3794
3795
3796
3797
        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.

3798

Minjie Wang's avatar
Minjie Wang committed
3799
3800
3801
3802
        Returns
        -------
        SparseTensor or scipy.sparse.spmatrix
            Adjacency matrix.
Mufei Li's avatar
Mufei Li committed
3803
3804
3805
3806

        Examples
        --------

3807
3808
3809
3810
3811
        The following example uses PyTorch backend.

        >>> import dgl
        >>> import torch

Mufei Li's avatar
Mufei Li committed
3812
3813
        Instantiate a heterogeneous graph.

3814
3815
3816
3817
        >>> g = dgl.heterograph({
        ...     ('user', 'follows', 'user'): ([0, 1], [0, 1]),
        ...     ('developer', 'develops', 'game'): ([0, 1], [0, 2])
        ... })
Mufei Li's avatar
Mufei Li committed
3818
3819
3820

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

3821
        >>> g.adj(etype='develops')
3822
3823
        tensor(indices=tensor([[0, 1],
                               [0, 2]]),
Mufei Li's avatar
Mufei Li committed
3824
               values=tensor([1., 1.]),
3825
               size=(2, 3), nnz=2, layout=torch.sparse_coo)
Mufei Li's avatar
Mufei Li committed
3826
3827
3828

        Get a scipy coo sparse matrix.

3829
        >>> g.adj(scipy_fmt='coo', etype='develops')
3830
        <2x3 sparse matrix of type '<class 'numpy.int64'>'
3831
           with 2 stored elements in COOrdinate format>
3832
        """
Minjie Wang's avatar
Minjie Wang committed
3833
3834
3835
3836
        etid = self.get_etype_id(etype)
        if scipy_fmt is None:
            return self._graph.adjacency_matrix(etid, transpose, ctx)[0]
        else:
Hongzhi (Steve), Chen's avatar
Hongzhi (Steve), Chen committed
3837
3838
3839
            return self._graph.adjacency_matrix_scipy(
                etid, transpose, scipy_fmt, False
            )
3840

3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
    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')
3877
        (tensor([0, 1, 2]), tensor([1, 2, 3]))
3878
        >>> g.adj_sparse('csr')
3879
        (tensor([0, 1, 2, 3, 3]), tensor([1, 2, 3]), tensor([0, 1, 2]))
3880
3881
        """
        etid = self.get_etype_id(etype)
Hongzhi (Steve), Chen's avatar
Hongzhi (Steve), Chen committed
3882
        if fmt == "csc":
3883
            # The first two elements are number of rows and columns
Hongzhi (Steve), Chen's avatar
Hongzhi (Steve), Chen committed
3884
            return self._graph.adjacency_matrix_tensors(etid, True, "csr")[2:]
3885
3886
        else:
            return self._graph.adjacency_matrix_tensors(etid, False, fmt)[2:]
3887

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

Mufei Li's avatar
Mufei Li committed
3892
        An incidence matrix is an n-by-m sparse matrix, where n is
Minjie Wang's avatar
Minjie Wang committed
3893
3894
3895
        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.
3896

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

Minjie Wang's avatar
Minjie Wang committed
3899
        * ``in``:
Da Zheng's avatar
Da Zheng committed
3900

Minjie Wang's avatar
Minjie Wang committed
3901
3902
3903
            - :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
3904

Minjie Wang's avatar
Minjie Wang committed
3905
        * ``out``:
Da Zheng's avatar
Da Zheng committed
3906

Minjie Wang's avatar
Minjie Wang committed
3907
3908
3909
3910
3911
3912
3913
3914
3915
            - :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
3916
3917
3918

        Parameters
        ----------
Minjie Wang's avatar
Minjie Wang committed
3919
3920
        typestr : str
            Can be either ``in``, ``out`` or ``both``
Mufei Li's avatar
Mufei Li committed
3921
3922
        ctx : context, optional
            The context of returned incidence matrix. (Default: cpu)
3923
3924
3925
3926
3927
3928
3929
3930
        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
3931
3932
3933

        Returns
        -------
Mufei Li's avatar
Mufei Li committed
3934
        Framework SparseTensor
Minjie Wang's avatar
Minjie Wang committed
3935
            The incidence matrix.
Mufei Li's avatar
Mufei Li committed
3936
3937
3938
3939

        Examples
        --------

3940
3941
3942
3943
3944
3945
        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
3946
3947
3948
3949
        tensor(indices=tensor([[0, 2],
                               [0, 1]]),
               values=tensor([1., 1.]),
               size=(3, 2), nnz=2, layout=torch.sparse_coo)
3950
        >>> g.inc('out')
Mufei Li's avatar
Mufei Li committed
3951
3952
3953
3954
        tensor(indices=tensor([[0, 1],
                               [0, 1]]),
               values=tensor([1., 1.]),
               size=(3, 2), nnz=2, layout=torch.sparse_coo)
3955
        >>> g.inc('both')
Mufei Li's avatar
Mufei Li committed
3956
3957
3958
3959
        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
3960
        """
Minjie Wang's avatar
Minjie Wang committed
3961
3962
3963
        etid = self.get_etype_id(etype)
        return self._graph.incidence_matrix(etid, typestr, ctx)[0]

3964
3965
    incidence_matrix = inc

Minjie Wang's avatar
Minjie Wang committed
3966
3967
3968
3969
3970
    #################################################################
    # Features
    #################################################################

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

3973
        The scheme of a feature describes the shape and data type of it.
Da Zheng's avatar
Da Zheng committed
3974
3975
3976

        Parameters
        ----------
Minjie Wang's avatar
Minjie Wang committed
3977
        ntype : str, optional
3978
3979
            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
3980
3981
3982

        Returns
        -------
3983
3984
        dict[str, Scheme]
            A dictionary mapping a feature name to its associated feature scheme.
3985
3986
3987

        Examples
        --------
3988
3989
3990
3991
3992
3993
        The following example uses PyTorch backend.

        >>> import dgl
        >>> import torch

        Query for a homogeneous graph.
3994

3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
        >>> 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)
4008
        >>> g.node_attr_schemes('user')
4009
4010
        {'h1': Scheme(shape=(1,), dtype=torch.float32),
         'h2': Scheme(shape=(2,), dtype=torch.float32)}
Mufei Li's avatar
Mufei Li committed
4011
4012
4013
4014

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

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

4021
        The scheme of a feature describes the shape and data type of it.
Da Zheng's avatar
Da Zheng committed
4022
4023
4024

        Parameters
        ----------
4025
4026
4027
4028
4029
4030
4031
4032
4033
        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
4034
4035
4036

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

4040
4041
        Examples
        --------
4042
4043
4044
4045
4046
4047
        The following example uses PyTorch backend.

        >>> import dgl
        >>> import torch

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

4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
        >>> 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
4067
4068
4069
4070

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

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

4077
4078
4079
        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
4080
4081
4082
4083

        Parameters
        ----------
        initializer : callable
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
            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
4095
        field : str, optional
4096
4097
            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
4098
        ntype : str, optional
4099
            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
4100

4101
        Notes
Minjie Wang's avatar
Minjie Wang committed
4102
        -----
4103
4104
        Without setting a node feature initializer, zero tensors are generated
        for nodes without a feature.
Da Zheng's avatar
Da Zheng committed
4105

4106
        Examples
Mufei Li's avatar
Mufei Li committed
4107
        --------
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157

        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
4158
        """
Minjie Wang's avatar
Minjie Wang committed
4159
4160
        ntid = self.get_ntype_id(ntype)
        self._node_frames[ntid].set_initializer(initializer, field)
Da Zheng's avatar
Da Zheng committed
4161

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

4165
4166
4167
        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
4168
4169
4170
4171

        Parameters
        ----------
        initializer : callable
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
            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
4183
        field : str, optional
4184
4185
            The name of the feature that the initializer applies. If not given, the
            initializer applies to all features.
4186
4187
4188
4189
4190
4191
4192
4193
4194
        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
4195

4196
        Notes
Minjie Wang's avatar
Minjie Wang committed
4197
        -----
4198
4199
        Without setting an edge feature initializer, zero tensors are generated
        for edges without a feature.
Mufei Li's avatar
Mufei Li committed
4200

4201
        Examples
Mufei Li's avatar
Mufei Li committed
4202
        --------
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250

        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
4251
        """
Minjie Wang's avatar
Minjie Wang committed
4252
4253
        etid = self.get_etype_id(etype)
        self._edge_frames[etid].set_initializer(initializer, field)
Da Zheng's avatar
Da Zheng committed
4254

4255
    def _set_n_repr(self, ntid, u, data):
Minjie Wang's avatar
Minjie Wang committed
4256
        """Internal API to set node features.
Da Zheng's avatar
Da Zheng committed
4257
4258
4259
4260
4261
4262

        `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).

4263
        All updates will be done out of place to work with autograd.
Da Zheng's avatar
Da Zheng committed
4264
4265
4266

        Parameters
        ----------
Minjie Wang's avatar
Minjie Wang committed
4267
4268
        ntid : int
            Node type id.
Da Zheng's avatar
Da Zheng committed
4269
4270
        u : node, container or tensor
            The node(s).
Minjie Wang's avatar
Minjie Wang committed
4271
4272
        data : dict of tensor
            Node representation.
Da Zheng's avatar
Da Zheng committed
4273
        """
4274
        if is_all(u):
Minjie Wang's avatar
Minjie Wang committed
4275
            num_nodes = self._graph.number_of_nodes(ntid)
4276
        else:
Hongzhi (Steve), Chen's avatar
Hongzhi (Steve), Chen committed
4277
            u = utils.prepare_tensor(self, u, "u")
4278
4279
4280
4281
            num_nodes = len(u)
        for key, val in data.items():
            nfeats = F.shape(val)[0]
            if nfeats != num_nodes:
Hongzhi (Steve), Chen's avatar
Hongzhi (Steve), Chen committed
4282
4283
4284
4285
                raise DGLError(
                    "Expect number of features to match number of nodes (len(u))."
                    " Got %d and %d instead." % (nfeats, num_nodes)
                )
4286
            if F.context(val) != self.device:
Hongzhi (Steve), Chen's avatar
Hongzhi (Steve), Chen committed
4287
4288
4289
4290
4291
                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)
                )
4292
4293
4294
4295
4296
4297
            # 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
Hongzhi (Steve), Chen's avatar
Hongzhi (Steve), Chen committed
4298
4299
4300
4301
4302
4303
4304
4305
4306
            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."
                )
4307
4308

        if is_all(u):
4309
            self._node_frames[ntid].update(data)
4310
        else:
4311
            self._node_frames[ntid].update_row(u, data)
Da Zheng's avatar
Da Zheng committed
4312

Minjie Wang's avatar
Minjie Wang committed
4313
    def _get_n_repr(self, ntid, u):
Da Zheng's avatar
Da Zheng committed
4314
4315
4316
4317
4318
4319
        """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
4320
4321
        ntid : int
            Node type id.
Da Zheng's avatar
Da Zheng committed
4322
4323
4324
4325
4326
4327
4328
4329
        u : node, container or tensor
            The node(s).

        Returns
        -------
        dict
            Representation dict from feature name to feature tensor.
        """
4330
        if is_all(u):
4331
            return self._node_frames[ntid]
4332
        else:
Hongzhi (Steve), Chen's avatar
Hongzhi (Steve), Chen committed
4333
            u = utils.prepare_tensor(self, u, "u")
4334
            return self._node_frames[ntid].subframe(u)
Da Zheng's avatar
Da Zheng committed
4335

Minjie Wang's avatar
Minjie Wang committed
4336
4337
    def _pop_n_repr(self, ntid, key):
        """Internal API to get and remove the specified node feature.
Da Zheng's avatar
Da Zheng committed
4338
4339
4340

        Parameters
        ----------
Minjie Wang's avatar
Minjie Wang committed
4341
4342
        ntid : int
            Node type id.
Da Zheng's avatar
Da Zheng committed
4343
4344
4345
4346
4347
4348
4349
4350
        key : str
            The attribute name.

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

4353
    def _set_e_repr(self, etid, edges, data):
Minjie Wang's avatar
Minjie Wang committed
4354
        """Internal API to set edge(s) features.
Da Zheng's avatar
Da Zheng committed
4355
4356
4357
4358
4359

        `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.

4360
        All update will be done out of place to work with autograd.
Da Zheng's avatar
Da Zheng committed
4361
4362
4363

        Parameters
        ----------
Minjie Wang's avatar
Minjie Wang committed
4364
4365
        etid : int
            Edge type id.
Da Zheng's avatar
Da Zheng committed
4366
4367
4368
4369
4370
4371
4372
4373
        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
4374
4375
        data : tensor or dict of tensor
            Edge representation.
Da Zheng's avatar
Da Zheng committed
4376
        """
4377
        # parse argument
4378
        if not is_all(edges):
Hongzhi (Steve), Chen's avatar
Hongzhi (Steve), Chen committed
4379
            eid = utils.parse_edges_arg_to_eid(self, edges, etid, "edges")
4380
4381
4382

        # sanity check
        if not utils.is_dict_like(data):
Hongzhi (Steve), Chen's avatar
Hongzhi (Steve), Chen committed
4383
4384
4385
4386
            raise DGLError(
                "Expect dictionary type for feature data."
                ' Got "%s" instead.' % type(data)
            )
4387

4388
        if is_all(edges):
Minjie Wang's avatar
Minjie Wang committed
4389
            num_edges = self._graph.number_of_edges(etid)
4390
4391
4392
4393
4394
        else:
            num_edges = len(eid)
        for key, val in data.items():
            nfeats = F.shape(val)[0]
            if nfeats != num_edges:
Hongzhi (Steve), Chen's avatar
Hongzhi (Steve), Chen committed
4395
4396
4397
4398
                raise DGLError(
                    "Expect number of features to match number of edges."
                    " Got %d and %d instead." % (nfeats, num_edges)
                )
4399
            if F.context(val) != self.device:
Hongzhi (Steve), Chen's avatar
Hongzhi (Steve), Chen committed
4400
4401
4402
4403
4404
                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)
                )
4405
4406
4407
4408
4409
4410
            # 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
Hongzhi (Steve), Chen's avatar
Hongzhi (Steve), Chen committed
4411
4412
4413
4414
4415
4416
4417
4418
4419
            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."
                )
4420

4421
        # set
4422
4423
        if is_all(edges):
            self._edge_frames[etid].update(data)
4424
        else:
4425
            self._edge_frames[etid].update_row(eid, data)
Da Zheng's avatar
Da Zheng committed
4426

Minjie Wang's avatar
Minjie Wang committed
4427
4428
    def _get_e_repr(self, etid, edges):
        """Internal API to get edge features.
Da Zheng's avatar
Da Zheng committed
4429
4430
4431

        Parameters
        ----------
Minjie Wang's avatar
Minjie Wang committed
4432
4433
        etid : int
            Edge type id.
Da Zheng's avatar
Da Zheng committed
4434
4435
4436
4437
4438
4439
4440
4441
4442
        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
        """
4443
4444
        # parse argument
        if is_all(edges):
4445
            return self._edge_frames[etid]
4446
        else:
Hongzhi (Steve), Chen's avatar
Hongzhi (Steve), Chen committed
4447
            eid = utils.parse_edges_arg_to_eid(self, edges, etid, "edges")
4448
            return self._edge_frames[etid].subframe(eid)
Da Zheng's avatar
Da Zheng committed
4449

Minjie Wang's avatar
Minjie Wang committed
4450
    def _pop_e_repr(self, etid, key):
Da Zheng's avatar
Da Zheng committed
4451
4452
4453
4454
        """Get and remove the specified edge repr of a single edge type.

        Parameters
        ----------
Minjie Wang's avatar
Minjie Wang committed
4455
4456
        etid : int
            Edge type id.
Da Zheng's avatar
Da Zheng committed
4457
4458
4459
4460
4461
4462
4463
4464
        key : str
          The attribute name.

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

Minjie Wang's avatar
Minjie Wang committed
4467
4468
4469
4470
    #################################################################
    # Message passing
    #################################################################

4471
    def apply_nodes(self, func, v=ALL, ntype=None):
4472
        """Update the features of the specified nodes by the provided function.
Da Zheng's avatar
Da Zheng committed
4473
4474
4475

        Parameters
        ----------
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
        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
4488
        ntype : str, optional
4489
4490
            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
4491
4492
4493

        Examples
        --------
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513

        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**

4514
        >>> g = dgl.heterograph({('user', 'follows', 'user'): ([0, 1], [1, 2])})
Minjie Wang's avatar
Minjie Wang committed
4515
4516
4517
        >>> 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
4518
4519
4520
        tensor([[2., 2., 2., 2., 2.],
                [2., 2., 2., 2., 2.],
                [2., 2., 2., 2., 2.]])
Mufei Li's avatar
Mufei Li committed
4521
4522
4523
4524

        See Also
        --------
        apply_edges
Da Zheng's avatar
Da Zheng committed
4525
        """
Minjie Wang's avatar
Minjie Wang committed
4526
        ntid = self.get_ntype_id(ntype)
4527
        ntype = self.ntypes[ntid]
Minjie Wang's avatar
Minjie Wang committed
4528
        if is_all(v):
4529
            v_id = self.nodes(ntype)
Minjie Wang's avatar
Minjie Wang committed
4530
        else:
Hongzhi (Steve), Chen's avatar
Hongzhi (Steve), Chen committed
4531
            v_id = utils.prepare_tensor(self, v, "v")
4532
        ndata = core.invoke_node_udf(self, v_id, ntype, func, orig_nid=v_id)
4533
        self._set_n_repr(ntid, v, ndata)
Minjie Wang's avatar
Minjie Wang committed
4534

4535
    def apply_edges(self, func, edges=ALL, etype=None):
4536
        """Update the features of the specified edges by the provided function.
Da Zheng's avatar
Da Zheng committed
4537
4538
4539

        Parameters
        ----------
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
        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.

        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
4571
4572
4573

        Examples
        --------
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602

        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**

4603
        >>> g = dgl.heterograph({('user', 'plays', 'game'): ([0, 1, 1, 2], [0, 0, 2, 1])})
Minjie Wang's avatar
Minjie Wang committed
4604
4605
4606
        >>> 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
4607
        tensor([[2., 2., 2., 2., 2.],
4608
                [2., 2., 2., 2., 2.],
Da Zheng's avatar
Da Zheng committed
4609
4610
                [2., 2., 2., 2., 2.],
                [2., 2., 2., 2., 2.]])
Mufei Li's avatar
Mufei Li committed
4611
4612
4613
4614

        See Also
        --------
        apply_nodes
Da Zheng's avatar
Da Zheng committed
4615
        """
4616
4617
4618
4619
4620
        # 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]
Hongzhi (Steve), Chen's avatar
Hongzhi (Steve), Chen committed
4621
        else:  # heterogeneous graph with number of relation types > 1
4622
            if not core.is_builtin(func):
Hongzhi (Steve), Chen's avatar
Hongzhi (Steve), Chen committed
4623
4624
4625
4626
4627
                raise DGLError(
                    "User defined functions are not yet "
                    "supported in apply_edges for heterogeneous graphs. "
                    "Please use (apply_edges(func), etype = rel) instead."
                )
4628
            g = self
Minjie Wang's avatar
Minjie Wang committed
4629
        if is_all(edges):
4630
            eid = ALL
Minjie Wang's avatar
Minjie Wang committed
4631
        else:
Hongzhi (Steve), Chen's avatar
Hongzhi (Steve), Chen committed
4632
            eid = utils.parse_edges_arg_to_eid(self, edges, etid, "edges")
4633
4634
        if core.is_builtin(func):
            if not is_all(eid):
4635
                g = g.edge_subgraph(eid, relabel_nodes=False)
4636
4637
4638
            edata = core.invoke_gsddmm(g, func)
        else:
            edata = core.invoke_edge_udf(g, eid, etype, func)
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650

        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
4651

Hongzhi (Steve), Chen's avatar
Hongzhi (Steve), Chen committed
4652
4653
4654
    def send_and_recv(
        self, edges, message_func, reduce_func, apply_node_func=None, etype=None
    ):
4655
4656
        """Send messages along the specified edges and reduce them on
        the destination nodes to update their features.
4657

Da Zheng's avatar
Da Zheng committed
4658
4659
        Parameters
        ----------
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
        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`.
4678
        apply_node_func : callable, optional
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
            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
        -----
        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
4696
4697
4698
4699
4700
4701
4702
4703

        Examples
        --------

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

4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
        **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**

4727
4728
4729
4730
        >>> 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
4731
        >>> g.nodes['user'].data['h'] = torch.tensor([[0.], [1.], [2.]])
4732
        >>> g.send_and_recv(g['follows'].edges(), fn.copy_u('h', 'm'),
4733
        ...                 fn.sum('m', 'h'), etype='follows')
Mufei Li's avatar
Mufei Li committed
4734
4735
4736
4737
        >>> g.nodes['user'].data['h']
        tensor([[0.],
                [0.],
                [1.]])
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760

        **``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
4761
        """
4762
        # edge type
Minjie Wang's avatar
Minjie Wang committed
4763
        etid = self.get_etype_id(etype)
4764
4765
4766
        _, dtid = self._graph.metagraph.find_edge(etid)
        etype = self.canonical_etypes[etid]
        # edge IDs
Hongzhi (Steve), Chen's avatar
Hongzhi (Steve), Chen committed
4767
        eid = utils.parse_edges_arg_to_eid(self, edges, etid, "edges")
4768
4769
        if len(eid) == 0:
            # no computation
4770
            return
4771
4772
        u, v = self.find_edges(eid, etype=etype)
        # call message passing onsubgraph
4773
        g = self if etype is None else self[etype]
4774
4775
        compute_graph, _, dstnodes, _ = _create_compute_graph(g, u, v, eid)
        ndata = core.message_passing(
Hongzhi (Steve), Chen's avatar
Hongzhi (Steve), Chen committed
4776
4777
            compute_graph, message_func, reduce_func, apply_node_func
        )
4778
        self._set_n_repr(dtid, dstnodes, ndata)
Minjie Wang's avatar
Minjie Wang committed
4779

Hongzhi (Steve), Chen's avatar
Hongzhi (Steve), Chen committed
4780
4781
4782
    def pull(
        self, v, message_func, reduce_func, apply_node_func=None, etype=None
    ):
4783
4784
        """Pull messages from the specified node(s)' predecessors along the
        specified edge type, aggregate them to update the node features.
4785

Da Zheng's avatar
Da Zheng committed
4786
4787
        Parameters
        ----------
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
        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`.
4802
        apply_node_func : callable, optional
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
            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 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
4824
4825
4826
4827
4828
4829
4830
4831

        Examples
        --------

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

4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
        **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
4845

4846
4847
4848
4849
        >>> g = dgl.heterograph({
        ...     ('user', 'follows', 'user'): ([0, 1], [1, 2]),
        ...     ('user', 'plays', 'game'): ([0, 2], [0, 1])
        ... })
Mufei Li's avatar
Mufei Li committed
4850
4851
4852
4853
        >>> g.nodes['user'].data['h'] = torch.tensor([[0.], [1.], [2.]])

        Pull.

4854
        >>> g['follows'].pull(2, fn.copy_u('h', 'm'), fn.sum('m', 'h'), etype='follows')
Mufei Li's avatar
Mufei Li committed
4855
4856
4857
4858
        >>> g.nodes['user'].data['h']
        tensor([[0.],
                [1.],
                [1.]])
Da Zheng's avatar
Da Zheng committed
4859
        """
Hongzhi (Steve), Chen's avatar
Hongzhi (Steve), Chen committed
4860
        v = utils.prepare_tensor(self, v, "v")
4861
        if len(v) == 0:
4862
            # no computation
4863
            return
4864
4865
4866
4867
4868
        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
Hongzhi (Steve), Chen's avatar
Hongzhi (Steve), Chen committed
4869
4870
4871
4872
        src, dst, eid = g.in_edges(v, form="all")
        compute_graph, _, dstnodes, _ = _create_compute_graph(
            g, src, dst, eid, v
        )
4873
        ndata = core.message_passing(
Hongzhi (Steve), Chen's avatar
Hongzhi (Steve), Chen committed
4874
4875
            compute_graph, message_func, reduce_func, apply_node_func
        )
4876
        self._set_n_repr(dtid, dstnodes, ndata)
Minjie Wang's avatar
Minjie Wang committed
4877

Hongzhi (Steve), Chen's avatar
Hongzhi (Steve), Chen committed
4878
4879
4880
    def push(
        self, u, message_func, reduce_func, apply_node_func=None, etype=None
    ):
4881
4882
        """Send message from the specified node(s) to their successors
        along the specified edge type and update their node features.
4883

Da Zheng's avatar
Da Zheng committed
4884
4885
        Parameters
        ----------
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
        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`.
4900
        apply_node_func : callable, optional
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
            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
        -----
        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
4918
4919
4920
4921
4922
4923
4924
4925

        Examples
        --------

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

4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
        **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
4939

4940
        >>> g = dgl.heterograph({('user', 'follows', 'user'): ([0, 0], [1, 2])})
Mufei Li's avatar
Mufei Li committed
4941
4942
4943
4944
        >>> g.nodes['user'].data['h'] = torch.tensor([[0.], [1.], [2.]])

        Push.

4945
        >>> g['follows'].push(0, fn.copy_u('h', 'm'), fn.sum('m', 'h'), etype='follows')
Mufei Li's avatar
Mufei Li committed
4946
4947
4948
4949
        >>> g.nodes['user'].data['h']
        tensor([[0.],
                [0.],
                [0.]])
Da Zheng's avatar
Da Zheng committed
4950
        """
Hongzhi (Steve), Chen's avatar
Hongzhi (Steve), Chen committed
4951
4952
4953
4954
4955
4956
4957
4958
        edges = self.out_edges(u, form="eid", etype=etype)
        self.send_and_recv(
            edges, message_func, reduce_func, apply_node_func, etype=etype
        )

    def update_all(
        self, message_func, reduce_func, apply_node_func=None, etype=None
    ):
4959
4960
        """Send messages along all the edges of the specified type
        and update all the nodes of the corresponding destination type.
4961

4962
4963
4964
4965
        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
4966
4967
        Parameters
        ----------
4968
4969
4970
4971
4972
4973
        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`.
4974
        apply_node_func : callable, optional
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
            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
4996
4997
4998
4999
5000

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

5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
        **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
5016

5017
        >>> g = dgl.heterograph({('user', 'follows', 'user'): ([0, 1, 2], [1, 2, 2])})
Mufei Li's avatar
Mufei Li committed
5018
5019
5020
5021

        Update all.

        >>> g.nodes['user'].data['h'] = torch.tensor([[0.], [1.], [2.]])
5022
        >>> g['follows'].update_all(fn.copy_u('h', 'm'), fn.sum('m', 'h'), etype='follows')
Mufei Li's avatar
Mufei Li committed
5023
5024
5025
5026
        >>> g.nodes['user'].data['h']
        tensor([[0.],
                [0.],
                [3.]])
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038

        **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.]])
5039
        >>> g.update_all(fn.copy_u('h', 'm'), fn.sum('m', 'h'))
5040
5041
5042
        >>> g.nodes['user'].data['h']
        tensor([[0.],
                [4.]])
Da Zheng's avatar
Da Zheng committed
5043
        """
5044
5045
5046
5047
5048
5049
        # 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]
Hongzhi (Steve), Chen's avatar
Hongzhi (Steve), Chen committed
5050
5051
5052
5053
5054
5055
5056
5057
            ndata = core.message_passing(
                g, message_func, reduce_func, apply_node_func
            )
            if (
                core.is_builtin(reduce_func)
                and reduce_func.name in ["min", "max"]
                and ndata
            ):
5058
5059
5060
                # Replace infinity with zero for isolated nodes
                key = list(ndata.keys())[0]
                ndata[key] = F.replace_inf_with_zero(ndata[key])
5061
            self._set_n_repr(dtid, ALL, ndata)
Hongzhi (Steve), Chen's avatar
Hongzhi (Steve), Chen committed
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
        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."
                )
5077
            g = self
Hongzhi (Steve), Chen's avatar
Hongzhi (Steve), Chen committed
5078
5079
5080
            all_out = core.message_passing(
                g, message_func, reduce_func, apply_node_func
            )
5081
5082
5083
5084
5085
5086
5087
            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]
Hongzhi (Steve), Chen's avatar
Hongzhi (Steve), Chen committed
5088
5089
5090
5091
                if core.is_builtin(reduce_func) and reduce_func.name in [
                    "min",
                    "max",
                ]:
5092
                    dst_tensor[key] = F.replace_inf_with_zero(dst_tensor[key])
5093
                self._node_frames[dtid].update(dst_tensor)
5094

5095
5096
5097
    #################################################################
    # Message passing on heterograph
    #################################################################
Da Zheng's avatar
Da Zheng committed
5098

Mufei Li's avatar
Mufei Li committed
5099
    def multi_update_all(self, etype_dict, cross_reducer, apply_node_func=None):
5100
5101
5102
        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
5103
5104
5105

        Parameters
        ----------
Mufei Li's avatar
Mufei Li committed
5106
        etype_dict : dict
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
            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
5124
            * apply_node_func : callable, optional
5125
5126
5127
                An optional apply function to further update the node features
                after the message reduction. It must be a :ref:`apiudf`.

5128
5129
5130
5131
5132
        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.
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
        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
5145
5146
5147
5148
5149
5150
5151
5152
5153

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

        Instantiate a heterograph.

5154
5155
5156
5157
        >>> g = dgl.heterograph({
        ...     ('user', 'follows', 'user'): ([0, 1], [1, 1]),
        ...     ('game', 'attracts', 'user'): ([0], [1])
        ... })
Mufei Li's avatar
Mufei Li committed
5158
5159
5160
5161
5162
5163
        >>> g.nodes['user'].data['h'] = torch.tensor([[1.], [2.]])
        >>> g.nodes['game'].data['h'] = torch.tensor([[1.]])

        Update all.

        >>> g.multi_update_all(
5164
5165
        ...     {'follows': (fn.copy_u('h', 'm'), fn.sum('m', 'h')),
        ...      'attracts': (fn.copy_u('h', 'm'), fn.sum('m', 'h'))},
5166
        ... "sum")
Mufei Li's avatar
Mufei Li committed
5167
5168
5169
        >>> g.nodes['user'].data['h']
        tensor([[0.],
                [4.]])
5170
5171
5172
5173
5174
5175
5176
5177
5178

        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(
5179
5180
        ...     {'follows': (fn.copy_u('h', 'm'), fn.sum('m', 'h')),
        ...      'attracts': (fn.copy_u('h', 'm'), fn.sum('m', 'h'))},
5181
        ... cross_sum)
Mufei Li's avatar
Mufei Li committed
5182
        """
Minjie Wang's avatar
Minjie Wang committed
5183
        all_out = defaultdict(list)
5184
        merge_order = defaultdict(list)
5185
        for etype, args in etype_dict.items():
5186

5187
5188
5189
5190
            etid = self.get_etype_id(etype)
            _, dtid = self._graph.metagraph.find_edge(etid)
            args = pad_tuple(args, 3)
            if args is None:
Hongzhi (Steve), Chen's avatar
Hongzhi (Steve), Chen committed
5191
5192
5193
5194
                raise DGLError(
                    'Invalid arguments for edge type "{}". Should be '
                    "(msg_func, reduce_func, [apply_node_func])".format(etype)
                )
5195
            mfunc, rfunc, afunc = args
5196
5197
            g = self if etype is None else self[etype]
            all_out[dtid].append(core.message_passing(g, mfunc, rfunc, afunc))
Hongzhi (Steve), Chen's avatar
Hongzhi (Steve), Chen committed
5198
5199
5200
            merge_order[dtid].append(
                etid
            )  # use edge type id as merge order hint
Minjie Wang's avatar
Minjie Wang committed
5201
5202
        for dtid, frames in all_out.items():
            # merge by cross_reducer
5203
5204
            out = reduce_dict_data(frames, cross_reducer, merge_order[dtid])
            # Replace infinity with zero for isolated nodes when reducer is min/max
Hongzhi (Steve), Chen's avatar
Hongzhi (Steve), Chen committed
5205
            if core.is_builtin(rfunc) and rfunc.name in ["min", "max"]:
5206
                key = list(out.keys())[0]
Hongzhi (Steve), Chen's avatar
Hongzhi (Steve), Chen committed
5207
5208
5209
5210
5211
                out[key] = (
                    F.replace_inf_with_zero(out[key])
                    if out[key] is not None
                    else None
                )
5212
            self._node_frames[dtid].update(out)
Minjie Wang's avatar
Minjie Wang committed
5213
            # apply
Mufei Li's avatar
Mufei Li committed
5214
            if apply_node_func is not None:
5215
5216
5217
5218
5219
                self.apply_nodes(apply_node_func, ALL, self.ntypes[dtid])

    #################################################################
    # Message propagation
    #################################################################
Minjie Wang's avatar
Minjie Wang committed
5220

Hongzhi (Steve), Chen's avatar
Hongzhi (Steve), Chen committed
5221
5222
5223
5224
5225
5226
5227
5228
    def prop_nodes(
        self,
        nodes_generator,
        message_func,
        reduce_func,
        apply_node_func=None,
        etype=None,
    ):
Mufei Li's avatar
Mufei Li committed
5229
        """Propagate messages using graph traversal by sequentially triggering
Minjie Wang's avatar
Minjie Wang committed
5230
5231
5232
5233
5234
5235
        :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
5236
5237
5238

        Parameters
        ----------
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
        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
5249
        apply_node_func : callable, optional
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
            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
5260
5261
5262
5263
5264
5265
5266
5267
5268

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

        Instantiate a heterogrph and perform multiple rounds of message passing.

5269
        >>> g = dgl.heterograph({('user', 'follows', 'user'): ([0, 1, 2, 3], [2, 3, 4, 4])})
Mufei Li's avatar
Mufei Li committed
5270
        >>> g.nodes['user'].data['h'] = torch.tensor([[1.], [2.], [3.], [4.], [5.]])
5271
        >>> g['follows'].prop_nodes([[2, 3], [4]], fn.copy_u('h', 'm'),
5272
        ...                         fn.sum('m', 'h'), etype='follows')
Mufei Li's avatar
Mufei Li committed
5273
5274
5275
5276
5277
        tensor([[1.],
                [2.],
                [1.],
                [2.],
                [3.]])
Da Zheng's avatar
Da Zheng committed
5278

Minjie Wang's avatar
Minjie Wang committed
5279
5280
5281
        See Also
        --------
        prop_edges
Da Zheng's avatar
Da Zheng committed
5282
        """
Minjie Wang's avatar
Minjie Wang committed
5283
        for node_frontier in nodes_generator:
Hongzhi (Steve), Chen's avatar
Hongzhi (Steve), Chen committed
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
            self.pull(
                node_frontier,
                message_func,
                reduce_func,
                apply_node_func,
                etype=etype,
            )

    def prop_edges(
        self,
        edges_generator,
        message_func,
        reduce_func,
        apply_node_func=None,
        etype=None,
    ):
Mufei Li's avatar
Mufei Li committed
5300
        """Propagate messages using graph traversal by sequentially triggering
Minjie Wang's avatar
Minjie Wang committed
5301
        :func:`send_and_recv()` on edges.
Da Zheng's avatar
Da Zheng committed
5302

Minjie Wang's avatar
Minjie Wang committed
5303
5304
5305
        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
5306

Mufei Li's avatar
Mufei Li committed
5307
        Edges in the same frontier will be triggered together, and edges in
Minjie Wang's avatar
Minjie Wang committed
5308
        different frontiers will be triggered according to the generating order.
Da Zheng's avatar
Da Zheng committed
5309
5310
5311

        Parameters
        ----------
Minjie Wang's avatar
Minjie Wang committed
5312
5313
        edges_generator : generator
            The generator of edge frontiers.
5314
5315
5316
5317
5318
5319
        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
5320
        apply_node_func : callable, optional
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
            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
5331
5332
5333
5334
5335
5336
5337
5338
5339

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

        Instantiate a heterogrph and perform multiple rounds of message passing.

5340
        >>> g = dgl.heterograph({('user', 'follows', 'user'): ([0, 1, 2, 3], [2, 3, 4, 4])})
Mufei Li's avatar
Mufei Li committed
5341
        >>> g.nodes['user'].data['h'] = torch.tensor([[1.], [2.], [3.], [4.], [5.]])
5342
        >>> g['follows'].prop_edges([[0, 1], [2, 3]], fn.copy_u('h', 'm'),
5343
        ...                         fn.sum('m', 'h'), etype='follows')
Mufei Li's avatar
Mufei Li committed
5344
5345
5346
5347
5348
5349
        >>> g.nodes['user'].data['h']
        tensor([[1.],
                [2.],
                [1.],
                [2.],
                [3.]])
Da Zheng's avatar
Da Zheng committed
5350

Minjie Wang's avatar
Minjie Wang committed
5351
5352
5353
        See Also
        --------
        prop_nodes
Da Zheng's avatar
Da Zheng committed
5354
        """
Minjie Wang's avatar
Minjie Wang committed
5355
        for edge_frontier in edges_generator:
Hongzhi (Steve), Chen's avatar
Hongzhi (Steve), Chen committed
5356
5357
5358
5359
5360
5361
5362
            self.send_and_recv(
                edge_frontier,
                message_func,
                reduce_func,
                apply_node_func,
                etype=etype,
            )
Da Zheng's avatar
Da Zheng committed
5363

Minjie Wang's avatar
Minjie Wang committed
5364
5365
5366
    #################################################################
    # Misc
    #################################################################
Da Zheng's avatar
Da Zheng committed
5367

Minjie Wang's avatar
Minjie Wang committed
5368
    def filter_nodes(self, predicate, nodes=ALL, ntype=None):
5369
        """Return the IDs of the nodes with the given node type that satisfy
Da Zheng's avatar
Da Zheng committed
5370
5371
5372
5373
5374
        the given predicate.

        Parameters
        ----------
        predicate : callable
5375
5376
5377
            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
5378
5379
            each element indicating whether the corresponding node in
            the batch satisfies the predicate.
5380
5381
5382
5383
5384
5385
5386
5387
5388
        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
5389
        ntype : str, optional
5390
5391
            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
5392
5393
5394

        Returns
        -------
5395
        Tensor
5396
            A 1D tensor that contains the ID(s) of the node(s) that satisfy the predicate.
Mufei Li's avatar
Mufei Li committed
5397
5398
5399

        Examples
        --------
5400
5401
5402

        The following example uses PyTorch backend.

Mufei Li's avatar
Mufei Li committed
5403
        >>> import dgl
5404
5405
5406
5407
5408
5409
5410
5411
5412
5413
5414
5415
5416
5417
5418
5419
5420
5421
5422
5423
5424
5425
5426
5427
5428
5429
5430
5431
5432
        >>> 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
5433
        tensor([1, 2])
Da Zheng's avatar
Da Zheng committed
5434
        """
5435
5436
        if is_all(nodes):
            nodes = self.nodes(ntype)
Hongzhi (Steve), Chen's avatar
Hongzhi (Steve), Chen committed
5437
        v = utils.prepare_tensor(self, nodes, "nodes")
5438
        if F.as_scalar(F.sum(self.has_nodes(v, ntype=ntype), dim=0)) != len(v):
Hongzhi (Steve), Chen's avatar
Hongzhi (Steve), Chen committed
5439
            raise DGLError("v contains invalid node IDs")
5440

5441
        with self.local_scope():
Hongzhi (Steve), Chen's avatar
Hongzhi (Steve), Chen committed
5442
5443
5444
            self.apply_nodes(
                lambda nbatch: {"_mask": predicate(nbatch)}, nodes, ntype
            )
5445
            ntype = self.ntypes[0] if ntype is None else ntype
Hongzhi (Steve), Chen's avatar
Hongzhi (Steve), Chen committed
5446
            mask = self.nodes[ntype].data["_mask"]
5447
5448
5449
            if is_all(nodes):
                return F.nonzero_1d(mask)
            else:
5450
                return F.boolean_mask(v, F.gather_row(mask, v))
Minjie Wang's avatar
Minjie Wang committed
5451
5452

    def filter_edges(self, predicate, edges=ALL, etype=None):
5453
        """Return the IDs of the edges with the given edge type that satisfy
Da Zheng's avatar
Da Zheng committed
5454
5455
5456
5457
5458
        the given predicate.

        Parameters
        ----------
        predicate : callable
5459
5460
5461
            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
5462
5463
            each element indicating whether the corresponding edge in
            the batch satisfies the predicate.
5464
5465
        edges : edges
            The edges to send and receive messages on. The allowed input formats are:
5466

5467
5468
5469
5470
5471
5472
5473
5474
5475
5476
5477
5478
5479
5480
5481
5482
5483
5484
            * ``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
5485
5486
5487

        Returns
        -------
5488
        Tensor
5489
            A 1D tensor that contains the ID(s) of the edge(s) that satisfy the predicate.
Mufei Li's avatar
Mufei Li committed
5490
5491
5492

        Examples
        --------
5493
5494
5495

        The following example uses PyTorch backend.

Mufei Li's avatar
Mufei Li committed
5496
        >>> import dgl
5497
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
5523
5524
5525
        >>> 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
5526
        tensor([1, 2])
Da Zheng's avatar
Da Zheng committed
5527
        """
5528
5529
5530
5531
5532
        if is_all(edges):
            pass
        elif isinstance(edges, tuple):
            u, v = edges
            srctype, _, dsttype = self.to_canonical_etype(etype)
Hongzhi (Steve), Chen's avatar
Hongzhi (Steve), Chen committed
5533
5534
5535
5536
5537
5538
5539
5540
5541
5542
            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")
5543
        elif isinstance(edges, Iterable) or F.is_tensor(edges):
Hongzhi (Steve), Chen's avatar
Hongzhi (Steve), Chen committed
5544
            edges = utils.prepare_tensor(self, edges, "edges")
5545
5546
            min_eid = F.as_scalar(F.min(edges, 0))
            if len(edges) > 0 > min_eid:
Hongzhi (Steve), Chen's avatar
Hongzhi (Steve), Chen committed
5547
                raise DGLError("Invalid edge ID {:d}".format(min_eid))
5548
5549
            max_eid = F.as_scalar(F.max(edges, 0))
            if len(edges) > 0 and max_eid >= self.num_edges(etype):
Hongzhi (Steve), Chen's avatar
Hongzhi (Steve), Chen committed
5550
                raise DGLError("Invalid edge ID {:d}".format(max_eid))
5551
        else:
Hongzhi (Steve), Chen's avatar
Hongzhi (Steve), Chen committed
5552
            raise ValueError("Unsupported type of edges:", type(edges))
5553

5554
        with self.local_scope():
Hongzhi (Steve), Chen's avatar
Hongzhi (Steve), Chen committed
5555
5556
5557
            self.apply_edges(
                lambda ebatch: {"_mask": predicate(ebatch)}, edges, etype
            )
5558
            etype = self.canonical_etypes[0] if etype is None else etype
Hongzhi (Steve), Chen's avatar
Hongzhi (Steve), Chen committed
5559
            mask = self.edges[etype].data["_mask"]
5560
5561
5562
5563
5564
5565
            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:
Hongzhi (Steve), Chen's avatar
Hongzhi (Steve), Chen committed
5566
                    e = utils.prepare_tensor(self, edges, "edges")
5567
                return F.boolean_mask(e, F.gather_row(mask, e))
Minjie Wang's avatar
Minjie Wang committed
5568

5569
5570
    @property
    def device(self):
5571
5572
5573
5574
5575
5576
5577
        """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``).
5578
5579
5580
5581
5582

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

5583
5584
5585
5586
5587
5588
        >>> import dgl
        >>> import torch

        Create a homogeneous graph for demonstration.

        >>> g = dgl.graph((torch.tensor([0, 1]), torch.tensor([1, 2])))
5589
5590
5591
        >>> print(g.device)
        device(type='cpu')

5592
        The case of heterogeneous graphs is the same.
5593
5594
5595
        """
        return F.to_backend_ctx(self._graph.ctx)

5596
5597
    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
5598

5599
5600
5601
        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
5602
5603
        Parameters
        ----------
5604
        device : Framework-specific device context object
5605
            The context to move data to (e.g., ``torch.device``).
5606
5607
        kwargs : Key-word arguments.
            Key-word arguments fed to the framework copy function.
Minjie Wang's avatar
Minjie Wang committed
5608

5609
5610
        Returns
        -------
5611
5612
        DGLGraph
            The graph on the specified device.
5613

Minjie Wang's avatar
Minjie Wang committed
5614
5615
5616
5617
        Examples
        --------
        The following example uses PyTorch backend.

5618
        >>> import dgl
Minjie Wang's avatar
Minjie Wang committed
5619
        >>> import torch
5620
5621
5622
5623

        >>> 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)
5624
5625
5626
        >>> g1 = g.to(torch.device('cuda:0'))
        >>> print(g1.device)
        device(type='cuda', index=0)
5627
5628
5629
5630
5631
5632
5633
        >>> 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.

5634
5635
        >>> print(g.device)
        device(type='cpu')
5636
5637
5638
5639
5640
5641
        >>> 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
5642
        """
5643
        if device is None or self.device == device:
5644
            return self
5645
5646
5647
5648
5649
5650
5651
5652

        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
5653
5654
        new_nframes = []
        for nframe in self._node_frames:
5655
            new_nframes.append(nframe.to(device, **kwargs))
5656
5657
        ret._node_frames = new_nframes

5658
5659
        new_eframes = []
        for eframe in self._edge_frames:
5660
            new_eframes.append(eframe.to(device, **kwargs))
5661
5662
5663
5664
        ret._edge_frames = new_eframes

        # 2. Copy misc info
        if self._batch_num_nodes is not None:
Hongzhi (Steve), Chen's avatar
Hongzhi (Steve), Chen committed
5665
5666
5667
5668
            new_bnn = {
                k: F.copy_to(num, device, **kwargs)
                for k, num in self._batch_num_nodes.items()
            }
5669
5670
            ret._batch_num_nodes = new_bnn
        if self._batch_num_edges is not None:
Hongzhi (Steve), Chen's avatar
Hongzhi (Steve), Chen committed
5671
5672
5673
5674
            new_bne = {
                k: F.copy_to(num, device, **kwargs)
                for k, num in self._batch_num_edges.items()
            }
5675
5676
5677
5678
5679
5680
5681
5682
5683
            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
5684
        DGLGraph
5685
5686
5687
5688
5689
5690
5691
5692
            Graph on CPU.

        See Also
        --------
        to
        """
        return self.to(F.cpu())

5693
    def pin_memory_(self):
5694
5695
        """Pin the graph structure and node/edge data to the page-locked memory for
        GPU zero-copy access.
5696
5697
5698
5699
5700
5701

        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,
5702
        you should create all the needed formats before pinning.
5703
5704
5705
5706
5707
5708
5709
5710
5711
5712
5713
5714
5715
5716
5717
5718
5719
5720
5721
5722
5723
5724
5725
5726
5727
        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()
5728
5729
5730
5731
5732
5733
5734
5735
5736
5737
5738
5739
5740
5741
5742
5743
5744
5745
5746
5747
5748
5749
5750
5751

        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])
5752
        """
5753
        if not self._graph.is_pinned():
Hongzhi (Steve), Chen's avatar
Hongzhi (Steve), Chen committed
5754
5755
5756
5757
            if F.device_type(self.device) != "cpu":
                raise DGLError(
                    "The graph structure must be on CPU to be pinned."
                )
5758
            self._graph.pin_memory_()
5759
5760
5761
        for frame in itertools.chain(self._node_frames, self._edge_frames):
            for col in frame._columns.values():
                col.pin_memory_()
5762

5763
5764
5765
        return self

    def unpin_memory_(self):
5766
        """Unpin the graph structure and node/edge data from the page-locked memory.
5767

5768
        This is an **inplace** method. If the graph struture is not pinned,
5769
5770
5771
5772
5773
5774
5775
        e.g., on CPU or GPU, the function directly returns it.

        Returns
        -------
        DGLGraph
            The unpinned graph.
        """
5776
5777
        if self._graph.is_pinned():
            self._graph.unpin_memory_()
5778
5779
5780
        for frame in itertools.chain(self._node_frames, self._edge_frames):
            for col in frame._columns.values():
                col.unpin_memory_()
5781

5782
5783
5784
5785
5786
5787
5788
5789
5790
5791
5792
5793
        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()

5794
5795
5796
5797
5798
5799
5800
5801
5802
5803
5804
5805
5806
5807
    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.
        """
Hongzhi (Steve), Chen's avatar
Hongzhi (Steve), Chen committed
5808
        if F.get_preferred_backend() != "pytorch":
5809
            raise DGLError("record_stream only support the PyTorch backend.")
Hongzhi (Steve), Chen's avatar
Hongzhi (Steve), Chen committed
5810
        if F.device_type(self.device) != "cuda":
5811
5812
5813
5814
5815
5816
5817
5818
            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

5819
5820
5821
5822
5823
    def clone(self):
        """Return a heterograph object that is a clone of current graph.

        Returns
        -------
peizhou001's avatar
peizhou001 committed
5824
        DGLGraph
5825
5826
5827
5828
5829
5830
5831
5832
5833
            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:
Hongzhi (Steve), Chen's avatar
Hongzhi (Steve), Chen committed
5834
5835
5836
            meta_edges.append(
                (self.get_ntype_id(s_ntype), self.get_ntype_id(d_ntype))
            )
5837
5838
5839

        metagraph = graph_index.from_edge_list(meta_edges, True)
        # rebuild graph idx
Hongzhi (Steve), Chen's avatar
Hongzhi (Steve), Chen committed
5840
5841
5842
5843
5844
5845
5846
        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
        ]
5847
        ret._graph = heterograph_index.create_heterograph_from_relations(
Hongzhi (Steve), Chen's avatar
Hongzhi (Steve), Chen committed
5848
5849
5850
5851
            metagraph,
            relation_graphs,
            utils.toindex(num_nodes_per_type, "int64"),
        )
5852
5853
5854
5855
5856

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

5857
5858
5859
5860
        # Copy the batch information
        ret._batch_num_nodes = copy.copy(self._batch_num_nodes)
        ret._batch_num_edges = copy.copy(self._batch_num_edges)

5861
        return ret
Da Zheng's avatar
Da Zheng committed
5862

Minjie Wang's avatar
Minjie Wang committed
5863
    def local_var(self):
5864
        """Return a graph object for usage in a local function scope.
Minjie Wang's avatar
Minjie Wang committed
5865
5866
5867

        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,
5868
        thus making it easier to use in a function scope (e.g. forward computation of a model).
Minjie Wang's avatar
Minjie Wang committed
5869
5870
5871
5872

        If set, the local graph object will use same initializers for node features and
        edge features.

Mufei Li's avatar
Mufei Li committed
5873
5874
        Returns
        -------
5875
5876
        DGLGraph
            The graph object for a local variable.
Mufei Li's avatar
Mufei Li committed
5877
5878
5879

        Notes
        -----
5880
5881
        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
5882

Minjie Wang's avatar
Minjie Wang committed
5883
5884
        Examples
        --------
5885

Minjie Wang's avatar
Minjie Wang committed
5886
5887
        The following example uses PyTorch backend.

5888
5889
5890
5891
        >>> import dgl
        >>> import torch

        Create a function for computation on graphs.
Minjie Wang's avatar
Minjie Wang committed
5892
5893

        >>> def foo(g):
5894
5895
5896
5897
5898
5899
5900
5901
5902
5903
        ...     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
5904
        >>> print(g.edata['h'])  # still get tensor of all zeros
5905
5906
5907
5908
5909
        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
5910

5911
        In-place operations will still reflect to the original graph.
Minjie Wang's avatar
Minjie Wang committed
5912
5913

        >>> def foo(g):
5914
5915
5916
5917
5918
5919
5920
5921
5922
5923
5924
5925
        ...     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
5926
5927
5928

        See Also
        --------
5929
        local_scope
Minjie Wang's avatar
Minjie Wang committed
5930
        """
5931
        ret = copy.copy(self)
5932
5933
        ret._node_frames = [fr.clone() for fr in self._node_frames]
        ret._edge_frames = [fr.clone() for fr in self._edge_frames]
5934
        return ret
Minjie Wang's avatar
Minjie Wang committed
5935
5936
5937

    @contextmanager
    def local_scope(self):
5938
        """Enter a local scope context for the graph.
Minjie Wang's avatar
Minjie Wang committed
5939
5940

        By entering a local scope, any out-place mutation to the feature data will
5941
5942
        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
5943
5944
5945
5946

        If set, the local scope will use same initializers for node features and
        edge features.

5947
5948
5949
5950
5951
        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
5952
5953
        Examples
        --------
5954

Minjie Wang's avatar
Minjie Wang committed
5955
5956
        The following example uses PyTorch backend.

5957
5958
5959
5960
        >>> import dgl
        >>> import torch

        Create a function for computation on graphs.
Minjie Wang's avatar
Minjie Wang committed
5961
5962

        >>> def foo(g):
5963
5964
5965
5966
5967
5968
5969
5970
5971
5972
        ...     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
5973
        >>> print(g.edata['h'])  # still get tensor of all zeros
5974
5975
5976
5977
5978
        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
5979

5980
        In-place operations will still reflect to the original graph.
Minjie Wang's avatar
Minjie Wang committed
5981
5982

        >>> def foo(g):
5983
5984
5985
5986
5987
5988
5989
5990
5991
5992
5993
5994
        ...     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
5995
5996
5997
5998
5999
6000
6001

        See Also
        --------
        local_var
        """
        old_nframes = self._node_frames
        old_eframes = self._edge_frames
6002
6003
        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
6004
6005
6006
6007
        yield
        self._node_frames = old_nframes
        self._edge_frames = old_eframes

6008
6009
6010
6011
6012
6013
6014
6015
    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.
6016

6017
6018
        Parameters
        ----------
6019
6020
6021
6022
        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
6023
              them, specifying the sparse formats to use.
6024

6025
6026
        Returns
        -------
6027
6028
6029
6030
6031
6032
        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``.
6033

6034
6035
6036
        Examples
        --------

6037
        The following example uses PyTorch backend.
6038

6039
6040
        >>> import dgl
        >>> import torch
6041

6042
6043
        **Homographs or Heterographs with A Single Edge Type**

6044
        >>> g = dgl.graph(([0, 0, 1], [2, 3, 2]))
6045
6046
6047
6048
6049
6050
6051
6052
6053
6054
6055
6056
6057
6058
6059
        >>> 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.]])
6060

6061
        **Heterographs with Multiple Edge Types**
6062

6063
        >>> g = dgl.heterograph({
6064
6065
6066
6067
6068
        ...     ('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]))
        ...     })
6069
6070
6071
6072
6073
6074
6075
        >>> 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': []}
6076
        """
6077
6078
6079
6080
6081
6082
6083
6084
        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
6085

6086
    def create_formats_(self):
6087
        r"""Create all sparse matrices allowed for the graph.
6088

6089
6090
6091
        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.
6092
6093
6094
6095

        Examples
        --------

6096
        The following example uses PyTorch backend.
6097

6098
6099
        >>> import dgl
        >>> import torch
6100

6101
        **Homographs or Heterographs with A Single Edge Type**
6102

6103
        >>> g = dgl.graph(([0, 0, 1], [2, 3, 2]))
6104
6105
        >>> g.format()
        {'created': ['coo'], 'not created': ['csr', 'csc']}
6106
        >>> g.create_formats_()
6107
6108
        >>> g.format()
        {'created': ['coo', 'csr', 'csc'], 'not created': []}
6109

6110
        **Heterographs with Multiple Edge Types**
6111
6112

        >>> g = dgl.heterograph({
6113
6114
6115
6116
6117
        ...     ('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]))
        ...     })
6118
6119
        >>> g.format()
        {'created': ['coo'], 'not created': ['csr', 'csc']}
6120
        >>> g.create_formats_()
6121
6122
        >>> g.format()
        {'created': ['coo', 'csr', 'csc'], 'not created': []}
6123
        """
6124
        return self._graph.create_formats_()
6125

6126
6127
    def astype(self, idtype):
        """Cast this graph to use another ID type.
6128

6129
        Features are copied (shallow copy) to the new graph.
6130
6131
6132

        Parameters
        ----------
6133
6134
        idtype : Data type object.
            New ID type. Can only be int32 or int64.
6135
6136
6137

        Returns
        -------
peizhou001's avatar
peizhou001 committed
6138
        DGLGraph
6139
            Graph in the new ID type.
6140
        """
6141
6142
        if idtype is None:
            return self
6143
        utils.check_valid_idtype(idtype)
6144
6145
6146
6147
6148
6149
        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
6150

6151
    # TODO: Formats should not be specified, just saving all the materialized formats
Hongzhi (Steve), Chen's avatar
Hongzhi (Steve), Chen committed
6152
    def shared_memory(self, name, formats=("coo", "csr", "csc")):
6153
6154
        """Return a copy of this graph in shared memory, without node data or edge data.

peizhou001's avatar
peizhou001 committed
6155
        It moves the graph index to shared memory and returns a DGLGraph object which
6156
6157
6158
6159
6160
6161
6162
        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.
6163
        formats : str or a list of str (optional)
6164
6165
6166
6167
            Desired formats to be materialized.

        Returns
        -------
peizhou001's avatar
peizhou001 committed
6168
        DGLGraph
6169
6170
6171
6172
            The graph in shared memory
        """
        assert len(name) > 0, "The name of shared memory cannot be empty"
        assert len(formats) > 0
6173
6174
        if isinstance(formats, str):
            formats = [formats]
6175
        for fmt in formats:
Hongzhi (Steve), Chen's avatar
Hongzhi (Steve), Chen committed
6176
6177
6178
6179
6180
6181
6182
6183
            assert fmt in (
                "coo",
                "csr",
                "csc",
            ), "{} is not coo, csr or csc".format(fmt)
        gidx = self._graph.shared_memory(
            name, self.ntypes, self.etypes, formats
        )
peizhou001's avatar
peizhou001 committed
6184
        return DGLGraph(gidx, self.ntypes, self.etypes)
6185

6186
    def long(self):
6187
        """Cast the graph to one with idtype int64
6188

6189
6190
        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).
6191
6192
6193

        Returns
        -------
6194
6195
        DGLGraph
            The graph of idtype int64.
6196
6197
6198
6199

        Examples
        --------

6200
6201
6202
6203
6204
6205
6206
6207
6208
6209
6210
6211
6212
6213
6214
6215
6216
6217
6218
6219
6220
6221
6222
6223
6224
6225
6226
6227
        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.]])}
6228
6229
6230
6231

        See Also
        --------
        int
6232
        idtype
6233
        """
6234
        return self.astype(F.int64)
6235
6236

    def int(self):
6237
6238
6239
6240
        """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).
6241
6242
6243

        Returns
        -------
6244
6245
        DGLGraph
            The graph of idtype int32.
6246
6247
6248
6249

        Examples
        --------

6250
6251
6252
6253
6254
6255
6256
6257
6258
6259
6260
6261
6262
6263
6264
6265
6266
6267
6268
6269
6270
6271
6272
6273
6274
6275
6276
6277
        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.]])}
6278
6279
6280
6281

        See Also
        --------
        long
6282
        idtype
6283
        """
6284
        return self.astype(F.int32)
6285

Hongzhi (Steve), Chen's avatar
Hongzhi (Steve), Chen committed
6286

Minjie Wang's avatar
Minjie Wang committed
6287
6288
6289
6290
############################################################
# Internal APIs
############################################################

Hongzhi (Steve), Chen's avatar
Hongzhi (Steve), Chen committed
6291

Minjie Wang's avatar
Minjie Wang committed
6292
6293
6294
6295
6296
6297
6298
6299
6300
6301
6302
6303
6304
6305
6306
6307
6308
6309
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():
Hongzhi (Steve), Chen's avatar
Hongzhi (Steve), Chen committed
6310
6311
6312
6313
6314
6315
        raise DGLError(
            "Length of edge type list must match the number of "
            "edges in the metagraph. {} vs {}".format(
                len(etypes), metagraph.number_of_edges()
            )
        )
Minjie Wang's avatar
Minjie Wang committed
6316
    if len(ntypes) != metagraph.number_of_nodes():
Hongzhi (Steve), Chen's avatar
Hongzhi (Steve), Chen committed
6317
6318
6319
6320
6321
6322
6323
        raise DGLError(
            "Length of nodes type list must match the number of "
            "nodes in the metagraph. {} vs {}".format(
                len(ntypes), metagraph.number_of_nodes()
            )
        )
    if len(etypes) == 1 and len(ntypes) == 1:
6324
6325
        return [(ntypes[0], etypes[0], ntypes[0])]
    src, dst, eid = metagraph.edges(order="eid")
Hongzhi (Steve), Chen's avatar
Hongzhi (Steve), Chen committed
6326
6327
6328
6329
    rst = [
        (ntypes[sid], etypes[eid], ntypes[did])
        for sid, did, eid in zip(src, dst, eid)
    ]
Minjie Wang's avatar
Minjie Wang committed
6330
6331
    return rst

Hongzhi (Steve), Chen's avatar
Hongzhi (Steve), Chen committed
6332

6333
6334
6335
6336
6337
6338
6339
6340
6341
6342
6343
6344
6345
6346
6347
6348
6349
6350
6351
6352
6353
6354
6355
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.
    """
6356
6357
    ret = _CAPI_DGLFindSrcDstNtypes(metagraph)
    if ret is None:
6358
        return None
6359
6360
    else:
        src, dst = ret
Hongzhi (Steve), Chen's avatar
Hongzhi (Steve), Chen committed
6361
6362
        srctypes = {ntypes[tid]: tid for tid in src}
        dsttypes = {ntypes[tid]: tid for tid in dst}
6363
        return srctypes, dsttypes
6364

Hongzhi (Steve), Chen's avatar
Hongzhi (Steve), Chen committed
6365

Minjie Wang's avatar
Minjie Wang committed
6366
6367
6368
6369
6370
6371
6372
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):
Hongzhi (Steve), Chen's avatar
Hongzhi (Steve), Chen committed
6373
        tup = (tup,)
Minjie Wang's avatar
Minjie Wang committed
6374
6375
6376
6377
6378
6379
6380
    if len(tup) > length:
        return None
    elif len(tup) == length:
        return tup
    else:
        return tup + (pad_val,) * (length - len(tup))

Hongzhi (Steve), Chen's avatar
Hongzhi (Steve), Chen committed
6381

6382
6383
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
6384
6385
6386

    Parameters
    ----------
6387
6388
    frames : list[dict[str, Tensor]]
        Input tensor dictionaries
6389
6390
6391
6392
6393
    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.
6394
6395
6396
6397
6398
6399
    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
6400
6401
6402

    Returns
    -------
6403
    dict[str, Tensor]
Minjie Wang's avatar
Minjie Wang committed
6404
        Merged frame
Da Zheng's avatar
Da Zheng committed
6405
    """
Hongzhi (Steve), Chen's avatar
Hongzhi (Steve), Chen committed
6406
    if len(frames) == 1 and reducer != "stack":
6407
6408
        # Directly return the only one input. Stack reducer requires
        # modifying tensor shape.
Minjie Wang's avatar
Minjie Wang committed
6409
        return frames[0]
6410
6411
    if callable(reducer):
        merger = reducer
Hongzhi (Steve), Chen's avatar
Hongzhi (Steve), Chen committed
6412
    elif reducer == "stack":
6413
6414
6415
6416
6417
        # 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]
Hongzhi (Steve), Chen's avatar
Hongzhi (Steve), Chen committed
6418

Minjie Wang's avatar
Minjie Wang committed
6419
6420
        def merger(flist):
            return F.stack(flist, 1)
Hongzhi (Steve), Chen's avatar
Hongzhi (Steve), Chen committed
6421

Minjie Wang's avatar
Minjie Wang committed
6422
6423
6424
    else:
        redfn = getattr(F, reducer, None)
        if redfn is None:
Hongzhi (Steve), Chen's avatar
Hongzhi (Steve), Chen committed
6425
6426
6427
6428
6429
            raise DGLError(
                "Invalid cross type reducer. Must be one of "
                '"sum", "max", "min", "mean" or "stack".'
            )

Minjie Wang's avatar
Minjie Wang committed
6430
        def merger(flist):
6431
            return redfn(F.stack(flist, 0), 0) if len(flist) > 1 else flist[0]
Hongzhi (Steve), Chen's avatar
Hongzhi (Steve), Chen committed
6432

Minjie Wang's avatar
Minjie Wang committed
6433
6434
6435
    keys = set()
    for frm in frames:
        keys.update(frm.keys())
6436
    ret = {}
Minjie Wang's avatar
Minjie Wang committed
6437
6438
6439
6440
6441
    for k in keys:
        flist = []
        for frm in frames:
            if k in frm:
                flist.append(frm[k])
6442
        ret[k] = merger(flist)
Minjie Wang's avatar
Minjie Wang committed
6443
6444
    return ret

Hongzhi (Steve), Chen's avatar
Hongzhi (Steve), Chen committed
6445

6446
def combine_frames(frames, ids, col_names=None):
Minjie Wang's avatar
Minjie Wang committed
6447
6448
6449
6450
    """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
6451
6452
    Parameters
    ----------
6453
    frames : List[Frame]
Minjie Wang's avatar
Minjie Wang committed
6454
6455
6456
        List of frames
    ids : List[int]
        List of frame IDs
6457
6458
    col_names : List[str], optional
        Column names to consider. If not given, it considers all columns.
Minjie Wang's avatar
Minjie Wang committed
6459
6460
6461

    Returns
    -------
6462
    Frame
Minjie Wang's avatar
Minjie Wang committed
6463
        The resulting frame
Da Zheng's avatar
Da Zheng committed
6464
    """
Minjie Wang's avatar
Minjie Wang committed
6465
    # find common columns and check if their schemes match
6466
    schemes = None
Minjie Wang's avatar
Minjie Wang committed
6467
6468
    for frame_id in ids:
        frame = frames[frame_id]
6469
6470
6471
6472
6473
6474
6475
6476
6477
6478
        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:
Hongzhi (Steve), Chen's avatar
Hongzhi (Steve), Chen committed
6479
6480
6481
6482
                    raise DGLError(
                        "Cannot concatenate column %s with shape %s and shape %s"
                        % (key, frame.schemes[key], scheme)
                    )
6483
6484
            else:
                del schemes[key]
Minjie Wang's avatar
Minjie Wang committed
6485
6486
6487
6488
6489
6490
6491

    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}
6492
    return Frame(cols)
Minjie Wang's avatar
Minjie Wang committed
6493

Hongzhi (Steve), Chen's avatar
Hongzhi (Steve), Chen committed
6494

Minjie Wang's avatar
Minjie Wang committed
6495
6496
6497
6498
6499
6500
6501
6502
6503
6504
6505
6506
6507
6508
6509
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:
Hongzhi (Steve), Chen's avatar
Hongzhi (Steve), Chen committed
6510
        return "+".join(sorted(names))
Minjie Wang's avatar
Minjie Wang committed
6511
6512
    else:
        selected = sorted([names[i] for i in ids])
Hongzhi (Steve), Chen's avatar
Hongzhi (Steve), Chen committed
6513
6514
        return "+".join(selected)

Minjie Wang's avatar
Minjie Wang committed
6515

peizhou001's avatar
peizhou001 committed
6516
class DGLBlock(DGLGraph):
6517
6518
6519
    """Subclass that signifies the graph is a block created from
    :func:`dgl.to_block`.
    """
Hongzhi (Steve), Chen's avatar
Hongzhi (Steve), Chen committed
6520

6521
6522
6523
6524
6525
    # (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):
Hongzhi (Steve), Chen's avatar
Hongzhi (Steve), Chen committed
6526
6527
6528
6529
6530
6531
        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})"
6532
6533
6534
            return ret.format(
                srcnode=self.number_of_src_nodes(),
                dstnode=self.number_of_dst_nodes(),
Hongzhi (Steve), Chen's avatar
Hongzhi (Steve), Chen committed
6535
6536
                edge=self.number_of_edges(),
            )
6537
        else:
Hongzhi (Steve), Chen's avatar
Hongzhi (Steve), Chen committed
6538
6539
6540
6541
6542
6543
6544
6545
6546
6547
6548
6549
6550
6551
6552
6553
6554
6555
            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
            }
6556
            meta = str(self.metagraph().edges(keys=True))
6557
            return ret.format(
Hongzhi (Steve), Chen's avatar
Hongzhi (Steve), Chen committed
6558
6559
6560
6561
6562
                srcnode=nsrcnode_dict,
                dstnode=ndstnode_dict,
                edge=nedge_dict,
                meta=meta,
            )
6563

6564
6565
6566
6567
6568
6569
6570
6571
6572
6573
6574
6575
6576
6577
6578
6579
6580
6581
6582
6583
6584
6585
6586
6587
6588
6589
6590
6591
6592
6593
6594
6595
6596
6597
6598
6599
6600
6601
6602
6603
6604
6605
6606
6607
6608
6609
6610
6611
6612
6613
6614
6615

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(
Hongzhi (Steve), Chen's avatar
Hongzhi (Steve), Chen committed
6616
6617
        2, len(unique_src), len(unique_dst), new_u, new_v, ["coo", "csr", "csc"]
    )
6618
    # create frame
Hongzhi (Steve), Chen's avatar
Hongzhi (Steve), Chen committed
6619
6620
6621
    srcframe = graph._node_frames[graph.get_ntype_id(srctype)].subframe(
        unique_src
    )
6622
    srcframe[NID] = unique_src
Hongzhi (Steve), Chen's avatar
Hongzhi (Steve), Chen committed
6623
6624
6625
    dstframe = graph._node_frames[graph.get_ntype_id(dsttype)].subframe(
        unique_dst
    )
6626
6627
6628
6629
    dstframe[NID] = unique_dst
    eframe = graph._edge_frames[0].subframe(eid)
    eframe[EID] = eid

Hongzhi (Steve), Chen's avatar
Hongzhi (Steve), Chen committed
6630
6631
6632
6633
6634
6635
6636
6637
6638
6639
6640
6641
6642
    return (
        DGLGraph(
            hgidx,
            ([srctype], [dsttype]),
            [etype],
            node_frames=[srcframe, dstframe],
            edge_frames=[eframe],
        ),
        unique_src,
        unique_dst,
        eid,
    )

6643

6644
_init_api("dgl.heterograph")