test_heterograph.py 120 KB
Newer Older
1
2
3
4
5
6
7
import itertools
import multiprocessing as mp
import unittest
from collections import Counter

import backend as F

8
9
import dgl
import dgl.function as fn
10
import networkx as nx
11
import numpy as np
12
import pytest
13
import scipy.sparse as ssp
14
from dgl import DGLError
15
from scipy.sparse import rand
16
17
18
19
20
21
from utils import (
    assert_is_identical_hetero,
    check_graph_equal,
    get_cases,
    parametrize_idtype,
)
22

23

24
def create_test_heterograph(idtype):
25
    # test heterograph from the docstring, plus a user -- wishes -- game relation
Minjie Wang's avatar
Minjie Wang committed
26
27
28
29
30
31
    # 3 users, 2 games, 2 developers
    # metagraph:
    #    ('user', 'follows', 'user'),
    #    ('user', 'plays', 'game'),
    #    ('user', 'wishes', 'game'),
    #    ('developer', 'develops', 'game')])
32

33
34
35
36
37
38
39
40
41
42
    g = dgl.heterograph(
        {
            ("user", "follows", "user"): ([0, 1], [1, 2]),
            ("user", "plays", "game"): ([0, 1, 2, 1], [0, 0, 1, 1]),
            ("user", "wishes", "game"): ([0, 2], [1, 0]),
            ("developer", "develops", "game"): ([0, 1], [0, 1]),
        },
        idtype=idtype,
        device=F.ctx(),
    )
43
44
    assert g.idtype == idtype
    assert g.device == F.ctx()
45
46
    return g

47

48
def create_test_heterograph1(idtype):
Minjie Wang's avatar
Minjie Wang committed
49
    edges = []
50
51
52
53
54
    edges.extend([(0, 1), (1, 2)])  # follows
    edges.extend([(0, 3), (1, 3), (2, 4), (1, 4)])  # plays
    edges.extend([(0, 4), (2, 3)])  # wishes
    edges.extend([(5, 3), (6, 4)])  # develops
    edges = tuple(zip(*edges))
Minjie Wang's avatar
Minjie Wang committed
55
56
    ntypes = F.tensor([0, 0, 0, 1, 1, 2, 2])
    etypes = F.tensor([0, 0, 1, 1, 1, 1, 2, 2, 3, 3])
57
    g0 = dgl.graph(edges, idtype=idtype, device=F.ctx())
Minjie Wang's avatar
Minjie Wang committed
58
59
    g0.ndata[dgl.NTYPE] = ntypes
    g0.edata[dgl.ETYPE] = etypes
60
61
62
63
64
65
    return dgl.to_heterogeneous(
        g0,
        ["user", "game", "developer"],
        ["follows", "plays", "wishes", "develops"],
    )

Minjie Wang's avatar
Minjie Wang committed
66

67
def create_test_heterograph2(idtype):
68
69
70
71
72
73
74
75
76
77
78
79
80
    g = dgl.heterograph(
        {
            ("user", "follows", "user"): ([0, 1], [1, 2]),
            ("user", "plays", "game"): ([0, 1, 2, 1], [0, 0, 1, 1]),
            ("user", "wishes", "game"): ("csr", ([0, 1, 1, 2], [1, 0], [])),
            ("developer", "develops", "game"): (
                "csc",
                ([0, 1, 2], [0, 1], [0, 1]),
            ),
        },
        idtype=idtype,
        device=F.ctx(),
    )
81
82
    assert g.idtype == idtype
    assert g.device == F.ctx()
83
84
    return g

85

86
def create_test_heterograph3(idtype):
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
    g = dgl.heterograph(
        {
            ("user", "plays", "game"): (
                F.tensor([0, 1, 1, 2], dtype=idtype),
                F.tensor([0, 0, 1, 1], dtype=idtype),
            ),
            ("developer", "develops", "game"): (
                F.tensor([0, 1], dtype=idtype),
                F.tensor([0, 1], dtype=idtype),
            ),
        },
        idtype=idtype,
        device=F.ctx(),
    )

    g.nodes["user"].data["h"] = F.copy_to(
        F.tensor([1, 1, 1], dtype=idtype), ctx=F.ctx()
    )
    g.nodes["game"].data["h"] = F.copy_to(
        F.tensor([2, 2], dtype=idtype), ctx=F.ctx()
    )
    g.nodes["developer"].data["h"] = F.copy_to(
        F.tensor([3, 3], dtype=idtype), ctx=F.ctx()
    )
    g.edges["plays"].data["h"] = F.copy_to(
        F.tensor([1, 1, 1, 1], dtype=idtype), ctx=F.ctx()
    )
114
115
    return g

116

117
def create_test_heterograph4(idtype):
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
    g = dgl.heterograph(
        {
            ("user", "follows", "user"): (
                F.tensor([0, 1, 1, 2, 2, 2], dtype=idtype),
                F.tensor([0, 0, 1, 1, 2, 2], dtype=idtype),
            ),
            ("user", "plays", "game"): (
                F.tensor([0, 1], dtype=idtype),
                F.tensor([0, 1], dtype=idtype),
            ),
        },
        idtype=idtype,
        device=F.ctx(),
    )
    g.nodes["user"].data["h"] = F.copy_to(
        F.tensor([1, 1, 1], dtype=idtype), ctx=F.ctx()
    )
    g.nodes["game"].data["h"] = F.copy_to(
        F.tensor([2, 2], dtype=idtype), ctx=F.ctx()
    )
    g.edges["follows"].data["h"] = F.copy_to(
        F.tensor([1, 2, 3, 4, 5, 6], dtype=idtype), ctx=F.ctx()
    )
    g.edges["plays"].data["h"] = F.copy_to(
        F.tensor([1, 2], dtype=idtype), ctx=F.ctx()
    )
144
145
    return g

146

147
def create_test_heterograph5(idtype):
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
    g = dgl.heterograph(
        {
            ("user", "follows", "user"): (
                F.tensor([1, 2], dtype=idtype),
                F.tensor([0, 1], dtype=idtype),
            ),
            ("user", "plays", "game"): (
                F.tensor([0, 1], dtype=idtype),
                F.tensor([0, 1], dtype=idtype),
            ),
        },
        idtype=idtype,
        device=F.ctx(),
    )
    g.nodes["user"].data["h"] = F.copy_to(
        F.tensor([1, 1, 1], dtype=idtype), ctx=F.ctx()
    )
    g.nodes["game"].data["h"] = F.copy_to(
        F.tensor([2, 2], dtype=idtype), ctx=F.ctx()
    )
    g.edges["follows"].data["h"] = F.copy_to(
        F.tensor([1, 2], dtype=idtype), ctx=F.ctx()
    )
    g.edges["plays"].data["h"] = F.copy_to(
        F.tensor([1, 2], dtype=idtype), ctx=F.ctx()
    )
174
175
    return g

176

Minjie Wang's avatar
Minjie Wang committed
177
178
179
def get_redfn(name):
    return getattr(F, name)

180

nv-dlasalle's avatar
nv-dlasalle committed
181
@parametrize_idtype
182
183
184
185
186
def test_create(idtype):
    device = F.ctx()
    g0 = create_test_heterograph(idtype)
    g1 = create_test_heterograph1(idtype)
    g2 = create_test_heterograph2(idtype)
187
    assert set(g0.ntypes) == set(g1.ntypes) == set(g2.ntypes)
188
189
190
191
192
    assert (
        set(g0.canonical_etypes)
        == set(g1.canonical_etypes)
        == set(g2.canonical_etypes)
    )
Minjie Wang's avatar
Minjie Wang committed
193

194
195
196
197
198
    # Create a bipartite graph from a SciPy matrix
    src_ids = np.array([2, 3, 4])
    dst_ids = np.array([1, 2, 3])
    eweight = np.array([0.2, 0.3, 0.5])
    sp_mat = ssp.coo_matrix((eweight, (src_ids, dst_ids)))
199
200
201
202
203
204
205
206
    g = dgl.bipartite_from_scipy(
        sp_mat,
        utype="user",
        etype="plays",
        vtype="game",
        idtype=idtype,
        device=device,
    )
207
208
209
210
211
212
213
214
    assert g.idtype == idtype
    assert g.device == device
    assert g.num_src_nodes() == 5
    assert g.num_dst_nodes() == 4
    assert g.num_edges() == 3
    src, dst = g.edges()
    assert F.allclose(src, F.tensor([2, 3, 4], dtype=idtype))
    assert F.allclose(dst, F.tensor([1, 2, 3], dtype=idtype))
215
216
217
218
219
220
221
222
223
224
    g = dgl.bipartite_from_scipy(
        sp_mat,
        utype="_U",
        etype="_E",
        vtype="_V",
        eweight_name="w",
        idtype=idtype,
        device=device,
    )
    assert F.allclose(g.edata["w"], F.tensor(eweight))
225
226
227

    # Create a bipartite graph from a NetworkX graph
    nx_g = nx.DiGraph()
228
229
230
    nx_g.add_nodes_from(
        [1, 3], bipartite=0, feat1=np.zeros((2)), feat2=np.ones((2))
    )
231
232
233
    nx_g.add_nodes_from([2, 4, 5], bipartite=1, feat3=np.zeros((3)))
    nx_g.add_edge(1, 4, weight=np.ones((1)), eid=np.array([1]))
    nx_g.add_edge(3, 5, weight=np.ones((1)), eid=np.array([0]))
234
235
236
237
238
239
240
241
    g = dgl.bipartite_from_networkx(
        nx_g,
        utype="user",
        etype="plays",
        vtype="game",
        idtype=idtype,
        device=device,
    )
242
243
    assert g.idtype == idtype
    assert g.device == device
244
245
246
247
248
249
    assert g.num_src_nodes() == 2
    assert g.num_dst_nodes() == 3
    assert g.num_edges() == 2
    src, dst = g.edges()
    assert F.allclose(src, F.tensor([0, 1], dtype=idtype))
    assert F.allclose(dst, F.tensor([1, 2], dtype=idtype))
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
    g = dgl.bipartite_from_networkx(
        nx_g,
        utype="_U",
        etype="_E",
        vtype="V",
        u_attrs=["feat1", "feat2"],
        e_attrs=["weight"],
        v_attrs=["feat3"],
    )
    assert F.allclose(g.srcdata["feat1"], F.tensor(np.zeros((2, 2))))
    assert F.allclose(g.srcdata["feat2"], F.tensor(np.ones((2, 2))))
    assert F.allclose(g.dstdata["feat3"], F.tensor(np.zeros((3, 3))))
    assert F.allclose(g.edata["weight"], F.tensor(np.ones((2, 1))))
    g = dgl.bipartite_from_networkx(
        nx_g,
        utype="_U",
        etype="_E",
        vtype="V",
        edge_id_attr_name="eid",
        idtype=idtype,
        device=device,
    )
272
273
274
    src, dst = g.edges()
    assert F.allclose(src, F.tensor([1, 0], dtype=idtype))
    assert F.allclose(dst, F.tensor([2, 1], dtype=idtype))
Minjie Wang's avatar
Minjie Wang committed
275
276

    # create from scipy
277
    spmat = ssp.coo_matrix(([1, 1, 1], ([0, 0, 1], [2, 3, 2])), shape=(4, 4))
278
279
280
    g = dgl.from_scipy(spmat, idtype=idtype, device=device)
    assert g.num_nodes() == 4
    assert g.num_edges() == 3
281
282
    assert g.idtype == idtype
    assert g.device == device
Minjie Wang's avatar
Minjie Wang committed
283

284
    # test inferring number of nodes for heterograph
285
286
287
288
289
290
291
292
293
294
295
296
    g = dgl.heterograph(
        {
            ("l0", "e0", "l1"): ([0, 0], [1, 2]),
            ("l0", "e1", "l2"): ([2], [2]),
            ("l2", "e2", "l2"): ([1, 3], [1, 3]),
        },
        idtype=idtype,
        device=device,
    )
    assert g.num_nodes("l0") == 3
    assert g.num_nodes("l1") == 3
    assert g.num_nodes("l2") == 4
297
298
    assert g.idtype == idtype
    assert g.device == device
299

300
301
    # test if validate flag works
    # homo graph
302
    with pytest.raises(DGLError):
303
304
        g = dgl.graph(
            ([0, 0, 0, 1, 1, 2], [0, 1, 2, 0, 1, 2]),
305
            num_nodes=2,
306
307
            idtype=idtype,
            device=device,
308
        )
309

310
311
    # bipartite graph
    def _test_validate_bipartite(card):
312
        with pytest.raises(DGLError):
313
314
315
316
317
318
            g = dgl.heterograph(
                {("_U", "_E", "_V"): ([0, 0, 1, 1, 2], [1, 1, 2, 2, 3])},
                {"_U": card[0], "_V": card[1]},
                idtype=idtype,
                device=device,
            )
319
320
321
322

    _test_validate_bipartite((3, 3))
    _test_validate_bipartite((2, 4))

323
324
325
    # test from_scipy
    num_nodes = 10
    density = 0.25
326
    for fmt in ["csr", "coo", "csc"]:
327
        adj = rand(num_nodes, num_nodes, density=density, format=fmt)
328
        g = dgl.from_scipy(adj, eweight_name="w", idtype=idtype)
329
330
        assert g.idtype == idtype
        assert g.device == F.cpu()
331
332
333
334
        assert F.array_equal(
            g.edata["w"], F.copy_to(F.tensor(adj.data), F.cpu())
        )

335

336
337
338
339
340
341
342
343
def test_create2():
    mat = ssp.random(20, 30, 0.1)

    # coo
    mat = mat.tocoo()
    row = F.tensor(mat.row, dtype=F.int64)
    col = F.tensor(mat.col, dtype=F.int64)
    g = dgl.heterograph(
344
345
346
        {("A", "AB", "B"): ("coo", (row, col))},
        num_nodes_dict={"A": 20, "B": 30},
    )
347
348
349
350
351
352
353

    # csr
    mat = mat.tocsr()
    indptr = F.tensor(mat.indptr, dtype=F.int64)
    indices = F.tensor(mat.indices, dtype=F.int64)
    data = F.tensor([], dtype=F.int64)
    g = dgl.heterograph(
354
355
356
        {("A", "AB", "B"): ("csr", (indptr, indices, data))},
        num_nodes_dict={"A": 20, "B": 30},
    )
357
358
359
360
361
362
363

    # csc
    mat = mat.tocsc()
    indptr = F.tensor(mat.indptr, dtype=F.int64)
    indices = F.tensor(mat.indices, dtype=F.int64)
    data = F.tensor([], dtype=F.int64)
    g = dgl.heterograph(
364
365
366
367
        {("A", "AB", "B"): ("csc", (indptr, indices, data))},
        num_nodes_dict={"A": 20, "B": 30},
    )

368

nv-dlasalle's avatar
nv-dlasalle committed
369
@parametrize_idtype
370
371
def test_query(idtype):
    g = create_test_heterograph(idtype)
372

373
    ntypes = ["user", "game", "developer"]
Minjie Wang's avatar
Minjie Wang committed
374
    canonical_etypes = [
375
376
377
378
379
380
        ("user", "follows", "user"),
        ("user", "plays", "game"),
        ("user", "wishes", "game"),
        ("developer", "develops", "game"),
    ]
    etypes = ["follows", "plays", "wishes", "develops"]
381
382

    # node & edge types
Minjie Wang's avatar
Minjie Wang committed
383
384
385
    assert set(ntypes) == set(g.ntypes)
    assert set(etypes) == set(g.etypes)
    assert set(canonical_etypes) == set(g.canonical_etypes)
386
387

    # metagraph
388
    mg = g.metagraph()
Minjie Wang's avatar
Minjie Wang committed
389
    assert set(g.ntypes) == set(mg.nodes)
390
    etype_triplets = [(u, v, e) for u, v, e in mg.edges(keys=True)]
391
392
393
394
395
396
397
398
    assert set(
        [
            ("user", "user", "follows"),
            ("user", "game", "plays"),
            ("user", "game", "wishes"),
            ("developer", "game", "develops"),
        ]
    ) == set(etype_triplets)
Minjie Wang's avatar
Minjie Wang committed
399
400
    for i in range(len(etypes)):
        assert g.to_canonical_etype(etypes[i]) == canonical_etypes[i]
401

402
403
    def _test(g):
        # number of nodes
404
        assert [g.num_nodes(ntype) for ntype in ntypes] == [3, 2, 2]
405

406
        # number of edges
407
        assert [g.num_edges(etype) for etype in etypes] == [2, 4, 2, 2]
408

409
        # has_nodes
410
        for ntype in ntypes:
Hongzhi (Steve), Chen's avatar
Hongzhi (Steve), Chen committed
411
            n = g.num_nodes(ntype)
412
            for i in range(n):
413
414
                assert g.has_nodes(i, ntype)
            assert not g.has_nodes(n, ntype)
415
            assert np.array_equal(
416
417
                F.asnumpy(g.has_nodes([0, n], ntype)).astype("int32"), [1, 0]
            )
Minjie Wang's avatar
Minjie Wang committed
418

419
        assert not g.is_multigraph
Minjie Wang's avatar
Minjie Wang committed
420
421
422
423

        for etype in etypes:
            srcs, dsts = edges[etype]
            for src, dst in zip(srcs, dsts):
424
                assert g.has_edges_between(src, dst, etype)
Minjie Wang's avatar
Minjie Wang committed
425
426
427
428
            assert F.asnumpy(g.has_edges_between(srcs, dsts, etype)).all()

            srcs, dsts = negative_edges[etype]
            for src, dst in zip(srcs, dsts):
429
                assert not g.has_edges_between(src, dst, etype)
Minjie Wang's avatar
Minjie Wang committed
430
431
432
433
434
435
436
            assert not F.asnumpy(g.has_edges_between(srcs, dsts, etype)).any()

            srcs, dsts = edges[etype]
            n_edges = len(srcs)

            # predecessors & in_edges & in_degree
            pred = [s for s, d in zip(srcs, dsts) if d == 0]
437
438
439
            assert set(F.asnumpy(g.predecessors(0, etype)).tolist()) == set(
                pred
            )
Minjie Wang's avatar
Minjie Wang committed
440
441
442
            u, v = g.in_edges([0], etype=etype)
            assert F.asnumpy(v).tolist() == [0] * len(pred)
            assert set(F.asnumpy(u).tolist()) == set(pred)
443
            assert g.in_degrees(0, etype) == len(pred)
Minjie Wang's avatar
Minjie Wang committed
444
445
446
447
448
449
450

            # successors & out_edges & out_degree
            succ = [d for s, d in zip(srcs, dsts) if s == 0]
            assert set(F.asnumpy(g.successors(0, etype)).tolist()) == set(succ)
            u, v = g.out_edges([0], etype=etype)
            assert F.asnumpy(u).tolist() == [0] * len(succ)
            assert set(F.asnumpy(v).tolist()) == set(succ)
451
            assert g.out_degrees(0, etype) == len(succ)
Minjie Wang's avatar
Minjie Wang committed
452

453
            # edge_ids
Minjie Wang's avatar
Minjie Wang committed
454
            for i, (src, dst) in enumerate(zip(srcs, dsts)):
455
456
457
                assert g.edge_ids(src, dst, etype=etype) == i
                _, _, eid = g.edge_ids(src, dst, etype=etype, return_uv=True)
                assert eid == i
458
459
460
            assert F.asnumpy(
                g.edge_ids(srcs, dsts, etype=etype)
            ).tolist() == list(range(n_edges))
461
            u, v, e = g.edge_ids(srcs, dsts, etype=etype, return_uv=True)
462
463
464
            u, v, e = F.asnumpy(u), F.asnumpy(v), F.asnumpy(e)
            assert u[e].tolist() == srcs
            assert v[e].tolist() == dsts
465

Minjie Wang's avatar
Minjie Wang committed
466
            # find_edges
467
468
469
470
471
            for eid in [
                list(range(n_edges)),
                np.arange(n_edges),
                F.astype(F.arange(0, n_edges), g.idtype),
            ]:
472
                u, v = g.find_edges(eid, etype)
473
474
                assert F.asnumpy(u).tolist() == srcs
                assert F.asnumpy(v).tolist() == dsts
Minjie Wang's avatar
Minjie Wang committed
475
476

            # all_edges.
477
478
            for order in ["eid"]:
                u, v, e = g.edges("all", order, etype)
Minjie Wang's avatar
Minjie Wang committed
479
480
481
482
483
484
485
486
487
488
                assert F.asnumpy(u).tolist() == srcs
                assert F.asnumpy(v).tolist() == dsts
                assert F.asnumpy(e).tolist() == list(range(n_edges))

            # in_degrees & out_degrees
            in_degrees = F.asnumpy(g.in_degrees(etype=etype))
            out_degrees = F.asnumpy(g.out_degrees(etype=etype))
            src_count = Counter(srcs)
            dst_count = Counter(dsts)
            utype, _, vtype = g.to_canonical_etype(etype)
Hongzhi (Steve), Chen's avatar
Hongzhi (Steve), Chen committed
489
            for i in range(g.num_nodes(utype)):
Minjie Wang's avatar
Minjie Wang committed
490
                assert out_degrees[i] == src_count[i]
Hongzhi (Steve), Chen's avatar
Hongzhi (Steve), Chen committed
491
            for i in range(g.num_nodes(vtype)):
Minjie Wang's avatar
Minjie Wang committed
492
493
494
                assert in_degrees[i] == dst_count[i]

    edges = {
495
496
497
498
        "follows": ([0, 1], [1, 2]),
        "plays": ([0, 1, 2, 1], [0, 0, 1, 1]),
        "wishes": ([0, 2], [1, 0]),
        "develops": ([0, 1], [0, 1]),
Minjie Wang's avatar
Minjie Wang committed
499
500
501
    }
    # edges that does not exist in the graph
    negative_edges = {
502
503
504
505
        "follows": ([0, 1], [0, 1]),
        "plays": ([0, 2], [1, 0]),
        "wishes": ([0, 1], [0, 1]),
        "develops": ([0, 1], [1, 0]),
Minjie Wang's avatar
Minjie Wang committed
506
    }
507
    g = create_test_heterograph(idtype)
Minjie Wang's avatar
Minjie Wang committed
508
    _test(g)
509
    g = create_test_heterograph1(idtype)
510
    _test(g)
511
    if F._default_context_str != "gpu":
512
        # XXX: CUDA COO operators have not been live yet.
513
        g = create_test_heterograph2(idtype)
514
        _test(g)
Minjie Wang's avatar
Minjie Wang committed
515
516
517

    etypes = canonical_etypes
    edges = {
518
519
520
521
        ("user", "follows", "user"): ([0, 1], [1, 2]),
        ("user", "plays", "game"): ([0, 1, 2, 1], [0, 0, 1, 1]),
        ("user", "wishes", "game"): ([0, 2], [1, 0]),
        ("developer", "develops", "game"): ([0, 1], [0, 1]),
Minjie Wang's avatar
Minjie Wang committed
522
523
524
    }
    # edges that does not exist in the graph
    negative_edges = {
525
526
527
528
529
        ("user", "follows", "user"): ([0, 1], [0, 1]),
        ("user", "plays", "game"): ([0, 2], [1, 0]),
        ("user", "wishes", "game"): ([0, 1], [0, 1]),
        ("developer", "develops", "game"): ([0, 1], [1, 0]),
    }
530
    g = create_test_heterograph(idtype)
Minjie Wang's avatar
Minjie Wang committed
531
    _test(g)
532
    g = create_test_heterograph1(idtype)
533
    _test(g)
534
    if F._default_context_str != "gpu":
535
        # XXX: CUDA COO operators have not been live yet.
536
        g = create_test_heterograph2(idtype)
537
        _test(g)
Minjie Wang's avatar
Minjie Wang committed
538
539
540
541

    # test repr
    print(g)

542

nv-dlasalle's avatar
nv-dlasalle committed
543
@parametrize_idtype
544
545
546
547
548
549
550
551
552
553
554
555
def test_empty_query(idtype):
    g = dgl.graph(([1, 2, 3], [0, 4, 5]), idtype=idtype, device=F.ctx())
    g.add_nodes(0)
    g.add_edges([], [])
    g.remove_edges([])
    g.remove_nodes([])
    assert F.shape(g.has_nodes([])) == (0,)
    assert F.shape(g.has_edges_between([], [])) == (0,)
    g.edge_ids([], [])
    g.edge_ids([], [], return_uv=True)
    g.find_edges([])

556
557
    assert F.shape(g.in_edges([], form="eid")) == (0,)
    u, v = g.in_edges([], form="uv")
558
559
    assert F.shape(u) == (0,)
    assert F.shape(v) == (0,)
560
    u, v, e = g.in_edges([], form="all")
561
562
563
564
    assert F.shape(u) == (0,)
    assert F.shape(v) == (0,)
    assert F.shape(e) == (0,)

565
566
    assert F.shape(g.out_edges([], form="eid")) == (0,)
    u, v = g.out_edges([], form="uv")
567
568
    assert F.shape(u) == (0,)
    assert F.shape(v) == (0,)
569
    u, v, e = g.out_edges([], form="all")
570
571
572
573
574
575
576
    assert F.shape(u) == (0,)
    assert F.shape(v) == (0,)
    assert F.shape(e) == (0,)

    assert F.shape(g.in_degrees([])) == (0,)
    assert F.shape(g.out_degrees([])) == (0,)

Quan (Andy) Gan's avatar
Quan (Andy) Gan committed
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
    g = dgl.graph(([], []), idtype=idtype, device=F.ctx())
    error_thrown = True
    try:
        g.in_degrees([0])
        fail = False
    except:
        pass
    assert error_thrown
    error_thrown = True
    try:
        g.out_degrees([0])
        fail = False
    except:
        pass
    assert error_thrown

593
594
595
596

@unittest.skipIf(
    F._default_context_str == "gpu", reason="GPU does not have COO impl."
)
597
def _test_hypersparse():
598
    N1 = 1 << 50  # should crash if allocated a CSR
599
600
    N2 = 1 << 48

601
602
603
604
605
606
607
608
609
610
611
612
613
614
    g = dgl.heterograph(
        {
            ("user", "follows", "user"): (
                F.tensor([0], F.int64),
                F.tensor([1], F.int64),
            ),
            ("user", "plays", "game"): (
                F.tensor([0], F.int64),
                F.tensor([N2], F.int64),
            ),
        },
        {"user": N1, "game": N1},
        device=F.ctx(),
    )
Hongzhi (Steve), Chen's avatar
Hongzhi (Steve), Chen committed
615
616
617
618
    assert g.num_nodes("user") == N1
    assert g.num_nodes("game") == N1
    assert g.num_edges("follows") == 1
    assert g.num_edges("plays") == 1
619
620
621
622

    assert g.has_edges_between(0, 1, "follows")
    assert not g.has_edges_between(0, 0, "follows")
    mask = F.asnumpy(g.has_edges_between([0, 0], [0, 1], "follows")).tolist()
623
624
    assert mask == [0, 1]

625
626
627
    assert g.has_edges_between(0, N2, "plays")
    assert not g.has_edges_between(0, 0, "plays")
    mask = F.asnumpy(g.has_edges_between([0, 0], [0, N2], "plays")).tolist()
628
629
    assert mask == [0, 1]

630
631
632
633
    assert F.asnumpy(g.predecessors(0, "follows")).tolist() == []
    assert F.asnumpy(g.successors(0, "follows")).tolist() == [1]
    assert F.asnumpy(g.predecessors(1, "follows")).tolist() == [0]
    assert F.asnumpy(g.successors(1, "follows")).tolist() == []
634

635
636
637
638
    assert F.asnumpy(g.predecessors(0, "plays")).tolist() == []
    assert F.asnumpy(g.successors(0, "plays")).tolist() == [N2]
    assert F.asnumpy(g.predecessors(N2, "plays")).tolist() == [0]
    assert F.asnumpy(g.successors(N2, "plays")).tolist() == []
639

640
641
    assert g.edge_ids(0, 1, etype="follows") == 0
    assert g.edge_ids(0, N2, etype="plays") == 0
642

643
    u, v = g.find_edges([0], "follows")
644
645
    assert F.asnumpy(u).tolist() == [0]
    assert F.asnumpy(v).tolist() == [1]
646
    u, v = g.find_edges([0], "plays")
647
648
    assert F.asnumpy(u).tolist() == [0]
    assert F.asnumpy(v).tolist() == [N2]
649
    u, v, e = g.all_edges("all", "eid", "follows")
650
651
652
    assert F.asnumpy(u).tolist() == [0]
    assert F.asnumpy(v).tolist() == [1]
    assert F.asnumpy(e).tolist() == [0]
653
    u, v, e = g.all_edges("all", "eid", "plays")
654
655
656
657
    assert F.asnumpy(u).tolist() == [0]
    assert F.asnumpy(v).tolist() == [N2]
    assert F.asnumpy(e).tolist() == [0]

658
659
660
661
662
663
664
665
666
667
668
669
670
    assert g.in_degrees(0, "follows") == 0
    assert g.in_degrees(1, "follows") == 1
    assert F.asnumpy(g.in_degrees([0, 1], "follows")).tolist() == [0, 1]
    assert g.in_degrees(0, "plays") == 0
    assert g.in_degrees(N2, "plays") == 1
    assert F.asnumpy(g.in_degrees([0, N2], "plays")).tolist() == [0, 1]
    assert g.out_degrees(0, "follows") == 1
    assert g.out_degrees(1, "follows") == 0
    assert F.asnumpy(g.out_degrees([0, 1], "follows")).tolist() == [1, 0]
    assert g.out_degrees(0, "plays") == 1
    assert g.out_degrees(N2, "plays") == 0
    assert F.asnumpy(g.out_degrees([0, N2], "plays")).tolist() == [1, 0]

671

672
def _test_edge_ids():
673
    N1 = 1 << 50  # should crash if allocated a CSR
674
675
    N2 = 1 << 48

676
677
678
679
680
681
682
683
684
685
686
687
688
    g = dgl.heterograph(
        {
            ("user", "follows", "user"): (
                F.tensor([0], F.int64),
                F.tensor([1], F.int64),
            ),
            ("user", "plays", "game"): (
                F.tensor([0], F.int64),
                F.tensor([N2], F.int64),
            ),
        },
        {"user": N1, "game": N1},
    )
689
    with pytest.raises(DGLError):
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
        eid = g.edge_ids(0, 0, etype="follows")

    g2 = dgl.heterograph(
        {
            ("user", "follows", "user"): (
                F.tensor([0, 0], F.int64),
                F.tensor([1, 1], F.int64),
            ),
            ("user", "plays", "game"): (
                F.tensor([0], F.int64),
                F.tensor([N2], F.int64),
            ),
        },
        {"user": N1, "game": N1},
        device=F.cpu(),
    )

    eid = g2.edge_ids(0, 1, etype="follows")
708
    assert eid == 0
709

710

nv-dlasalle's avatar
nv-dlasalle committed
711
@parametrize_idtype
712
713
def test_adj(idtype):
    g = create_test_heterograph(idtype)
714
    adj = F.sparse_to_numpy(g.adj(transpose=True, etype="follows"))
Minjie Wang's avatar
Minjie Wang committed
715
    assert np.allclose(
716
717
718
        adj, np.array([[0.0, 0.0, 0.0], [1.0, 0.0, 0.0], [0.0, 1.0, 0.0]])
    )
    adj = F.sparse_to_numpy(g.adj(transpose=False, etype="follows"))
Minjie Wang's avatar
Minjie Wang committed
719
    assert np.allclose(
720
721
722
723
724
725
726
727
        adj, np.array([[0.0, 1.0, 0.0], [0.0, 0.0, 1.0], [0.0, 0.0, 0.0]])
    )
    adj = F.sparse_to_numpy(g.adj(transpose=True, etype="plays"))
    assert np.allclose(adj, np.array([[1.0, 1.0, 0.0], [0.0, 1.0, 1.0]]))
    adj = F.sparse_to_numpy(g.adj(transpose=False, etype="plays"))
    assert np.allclose(adj, np.array([[1.0, 0.0], [1.0, 1.0], [0.0, 1.0]]))

    adj = g.adj(transpose=True, scipy_fmt="csr", etype="follows")
Minjie Wang's avatar
Minjie Wang committed
728
    assert np.allclose(
729
730
731
732
        adj.todense(),
        np.array([[0.0, 0.0, 0.0], [1.0, 0.0, 0.0], [0.0, 1.0, 0.0]]),
    )
    adj = g.adj(transpose=True, scipy_fmt="coo", etype="follows")
Minjie Wang's avatar
Minjie Wang committed
733
    assert np.allclose(
734
735
736
737
        adj.todense(),
        np.array([[0.0, 0.0, 0.0], [1.0, 0.0, 0.0], [0.0, 1.0, 0.0]]),
    )
    adj = g.adj(transpose=True, scipy_fmt="csr", etype="plays")
Minjie Wang's avatar
Minjie Wang committed
738
    assert np.allclose(
739
740
741
        adj.todense(), np.array([[1.0, 1.0, 0.0], [0.0, 1.0, 1.0]])
    )
    adj = g.adj(transpose=True, scipy_fmt="coo", etype="plays")
Minjie Wang's avatar
Minjie Wang committed
742
    assert np.allclose(
743
744
745
        adj.todense(), np.array([[1.0, 1.0, 0.0], [0.0, 1.0, 1.0]])
    )
    adj = F.sparse_to_numpy(g["follows"].adj(transpose=True))
Minjie Wang's avatar
Minjie Wang committed
746
    assert np.allclose(
747
748
749
        adj, np.array([[0.0, 0.0, 0.0], [1.0, 0.0, 0.0], [0.0, 1.0, 0.0]])
    )

Minjie Wang's avatar
Minjie Wang committed
750

nv-dlasalle's avatar
nv-dlasalle committed
751
@parametrize_idtype
752
753
def test_inc(idtype):
    g = create_test_heterograph(idtype)
754
755
756
757
758
759
760
    adj = F.sparse_to_numpy(g["follows"].inc("in"))
    assert np.allclose(adj, np.array([[0.0, 0.0], [1.0, 0.0], [0.0, 1.0]]))
    adj = F.sparse_to_numpy(g["follows"].inc("out"))
    assert np.allclose(adj, np.array([[1.0, 0.0], [0.0, 1.0], [0.0, 0.0]]))
    adj = F.sparse_to_numpy(g["follows"].inc("both"))
    assert np.allclose(adj, np.array([[-1.0, 0.0], [1.0, -1.0], [0.0, 1.0]]))
    adj = F.sparse_to_numpy(g.inc("in", etype="plays"))
Minjie Wang's avatar
Minjie Wang committed
761
    assert np.allclose(
762
763
764
        adj, np.array([[1.0, 1.0, 0.0, 0.0], [0.0, 0.0, 1.0, 1.0]])
    )
    adj = F.sparse_to_numpy(g.inc("out", etype="plays"))
Minjie Wang's avatar
Minjie Wang committed
765
    assert np.allclose(
766
767
768
769
770
771
772
773
        adj,
        np.array(
            [[1.0, 0.0, 0.0, 0.0], [0.0, 1.0, 0.0, 1.0], [0.0, 0.0, 1.0, 0.0]]
        ),
    )
    adj = F.sparse_to_numpy(g.inc("both", etype="follows"))
    assert np.allclose(adj, np.array([[-1.0, 0.0], [1.0, -1.0], [0.0, 1.0]]))

774

nv-dlasalle's avatar
nv-dlasalle committed
775
@parametrize_idtype
776
def test_view(idtype):
777
    # test single node type
778
779
780
781
782
    g = dgl.heterograph(
        {("user", "follows", "user"): ([0, 1], [1, 2])},
        idtype=idtype,
        device=F.ctx(),
    )
783
    f1 = F.randn((3, 6))
784
785
    g.ndata["h"] = f1
    f2 = g.nodes["user"].data["h"]
786
787
788
    assert F.array_equal(f1, f2)
    fail = False
    try:
789
        g.ndata["h"] = {"user": f1}
790
791
792
793
794
795
    except Exception:
        fail = True
    assert fail

    # test single edge type
    f3 = F.randn((2, 4))
796
797
    g.edata["h"] = f3
    f4 = g.edges["follows"].data["h"]
798
799
800
    assert F.array_equal(f3, f4)
    fail = False
    try:
801
        g.edata["h"] = {"follows": f3}
802
803
804
805
    except Exception:
        fail = True
    assert fail

Minjie Wang's avatar
Minjie Wang committed
806
    # test data view
807
    g = create_test_heterograph(idtype)
808
809

    f1 = F.randn((3, 6))
810
811
    g.nodes["user"].data["h"] = f1  # ok
    f2 = g.nodes["user"].data["h"]
812
    assert F.array_equal(f1, f2)
813
814
    assert F.array_equal(g.nodes("user"), F.arange(0, 3, idtype))
    g.nodes["user"].data.pop("h")
815
816
817
818
819
820

    # multi type ndata
    f1 = F.randn((3, 6))
    f2 = F.randn((2, 6))
    fail = False
    try:
821
        g.ndata["h"] = f1
822
823
824
    except Exception:
        fail = True
    assert fail
825
826

    f3 = F.randn((2, 4))
827
828
829
    g.edges["user", "follows", "user"].data["h"] = f3
    f4 = g.edges["user", "follows", "user"].data["h"]
    f5 = g.edges["follows"].data["h"]
830
    assert F.array_equal(f3, f4)
Minjie Wang's avatar
Minjie Wang committed
831
    assert F.array_equal(f3, f5)
832
833
834
835
    assert F.array_equal(
        g.edges(etype="follows", form="eid"), F.arange(0, 2, idtype)
    )
    g.edges["follows"].data.pop("h")
836
837
838
839

    f3 = F.randn((2, 4))
    fail = False
    try:
840
        g.edata["h"] = f3
841
842
843
844
845
846
    except Exception:
        fail = True
    assert fail

    # test srcdata
    f1 = F.randn((3, 6))
847
848
    g.srcnodes["user"].data["h"] = f1  # ok
    f2 = g.srcnodes["user"].data["h"]
849
    assert F.array_equal(f1, f2)
850
851
    assert F.array_equal(g.srcnodes("user"), F.arange(0, 3, idtype))
    g.srcnodes["user"].data.pop("h")
852
853
854

    # test dstdata
    f1 = F.randn((3, 6))
855
856
    g.dstnodes["user"].data["h"] = f1  # ok
    f2 = g.dstnodes["user"].data["h"]
857
    assert F.array_equal(f1, f2)
858
859
860
    assert F.array_equal(g.dstnodes("user"), F.arange(0, 3, idtype))
    g.dstnodes["user"].data.pop("h")

861

nv-dlasalle's avatar
nv-dlasalle committed
862
@parametrize_idtype
863
def test_view1(idtype):
Minjie Wang's avatar
Minjie Wang committed
864
    # test relation view
865
    HG = create_test_heterograph(idtype)
866
    ntypes = ["user", "game", "developer"]
Minjie Wang's avatar
Minjie Wang committed
867
    canonical_etypes = [
868
869
870
871
872
873
        ("user", "follows", "user"),
        ("user", "plays", "game"),
        ("user", "wishes", "game"),
        ("developer", "develops", "game"),
    ]
    etypes = ["follows", "plays", "wishes", "develops"]
Minjie Wang's avatar
Minjie Wang committed
874
875
876
877
878
879
880

    def _test_query():
        for etype in etypes:
            utype, _, vtype = HG.to_canonical_etype(etype)
            g = HG[etype]
            srcs, dsts = edges[etype]
            for src, dst in zip(srcs, dsts):
881
                assert g.has_edges_between(src, dst)
Minjie Wang's avatar
Minjie Wang committed
882
883
884
885
            assert F.asnumpy(g.has_edges_between(srcs, dsts)).all()

            srcs, dsts = negative_edges[etype]
            for src, dst in zip(srcs, dsts):
886
                assert not g.has_edges_between(src, dst)
Minjie Wang's avatar
Minjie Wang committed
887
888
889
890
891
892
893
894
895
896
897
            assert not F.asnumpy(g.has_edges_between(srcs, dsts)).any()

            srcs, dsts = edges[etype]
            n_edges = len(srcs)

            # predecessors & in_edges & in_degree
            pred = [s for s, d in zip(srcs, dsts) if d == 0]
            assert set(F.asnumpy(g.predecessors(0)).tolist()) == set(pred)
            u, v = g.in_edges([0])
            assert F.asnumpy(v).tolist() == [0] * len(pred)
            assert set(F.asnumpy(u).tolist()) == set(pred)
898
            assert g.in_degrees(0) == len(pred)
Minjie Wang's avatar
Minjie Wang committed
899
900
901
902
903
904
905

            # successors & out_edges & out_degree
            succ = [d for s, d in zip(srcs, dsts) if s == 0]
            assert set(F.asnumpy(g.successors(0)).tolist()) == set(succ)
            u, v = g.out_edges([0])
            assert F.asnumpy(u).tolist() == [0] * len(succ)
            assert set(F.asnumpy(v).tolist()) == set(succ)
906
            assert g.out_degrees(0) == len(succ)
Minjie Wang's avatar
Minjie Wang committed
907

908
            # edge_ids
Minjie Wang's avatar
Minjie Wang committed
909
            for i, (src, dst) in enumerate(zip(srcs, dsts)):
910
911
912
                assert g.edge_ids(src, dst, etype=etype) == i
                _, _, eid = g.edge_ids(src, dst, etype=etype, return_uv=True)
                assert eid == i
913
914
915
            assert F.asnumpy(g.edge_ids(srcs, dsts)).tolist() == list(
                range(n_edges)
            )
916
            u, v, e = g.edge_ids(srcs, dsts, return_uv=True)
917
918
919
            u, v, e = F.asnumpy(u), F.asnumpy(v), F.asnumpy(e)
            assert u[e].tolist() == srcs
            assert v[e].tolist() == dsts
Minjie Wang's avatar
Minjie Wang committed
920
921
922
923
924
925
926

            # find_edges
            u, v = g.find_edges(list(range(n_edges)))
            assert F.asnumpy(u).tolist() == srcs
            assert F.asnumpy(v).tolist() == dsts

            # all_edges.
927
928
            for order in ["eid"]:
                u, v, e = g.all_edges(form="all", order=order)
Minjie Wang's avatar
Minjie Wang committed
929
930
931
932
933
934
935
936
937
                assert F.asnumpy(u).tolist() == srcs
                assert F.asnumpy(v).tolist() == dsts
                assert F.asnumpy(e).tolist() == list(range(n_edges))

            # in_degrees & out_degrees
            in_degrees = F.asnumpy(g.in_degrees())
            out_degrees = F.asnumpy(g.out_degrees())
            src_count = Counter(srcs)
            dst_count = Counter(dsts)
Hongzhi (Steve), Chen's avatar
Hongzhi (Steve), Chen committed
938
            for i in range(g.num_nodes(utype)):
Minjie Wang's avatar
Minjie Wang committed
939
                assert out_degrees[i] == src_count[i]
Hongzhi (Steve), Chen's avatar
Hongzhi (Steve), Chen committed
940
            for i in range(g.num_nodes(vtype)):
941
                assert in_degrees[i] == dst_count[i]
Minjie Wang's avatar
Minjie Wang committed
942
943

    edges = {
944
945
946
947
        "follows": ([0, 1], [1, 2]),
        "plays": ([0, 1, 2, 1], [0, 0, 1, 1]),
        "wishes": ([0, 2], [1, 0]),
        "develops": ([0, 1], [0, 1]),
Minjie Wang's avatar
Minjie Wang committed
948
949
950
    }
    # edges that does not exist in the graph
    negative_edges = {
951
952
953
954
        "follows": ([0, 1], [0, 1]),
        "plays": ([0, 2], [1, 0]),
        "wishes": ([0, 1], [0, 1]),
        "develops": ([0, 1], [1, 0]),
Minjie Wang's avatar
Minjie Wang committed
955
956
957
958
    }
    _test_query()
    etypes = canonical_etypes
    edges = {
959
960
961
962
        ("user", "follows", "user"): ([0, 1], [1, 2]),
        ("user", "plays", "game"): ([0, 1, 2, 1], [0, 0, 1, 1]),
        ("user", "wishes", "game"): ([0, 2], [1, 0]),
        ("developer", "develops", "game"): ([0, 1], [0, 1]),
Minjie Wang's avatar
Minjie Wang committed
963
964
965
    }
    # edges that does not exist in the graph
    negative_edges = {
966
967
968
969
970
        ("user", "follows", "user"): ([0, 1], [0, 1]),
        ("user", "plays", "game"): ([0, 2], [1, 0]),
        ("user", "wishes", "game"): ([0, 1], [0, 1]),
        ("developer", "develops", "game"): ([0, 1], [1, 0]),
    }
Minjie Wang's avatar
Minjie Wang committed
971
972
973
    _test_query()

    # test features
Hongzhi (Steve), Chen's avatar
Hongzhi (Steve), Chen committed
974
975
    HG.nodes["user"].data["h"] = F.ones((HG.num_nodes("user"), 5))
    HG.nodes["game"].data["m"] = F.ones((HG.num_nodes("game"), 3)) * 2
Minjie Wang's avatar
Minjie Wang committed
976
977

    # test only one node type
978
    g = HG["follows"]
Hongzhi (Steve), Chen's avatar
Hongzhi (Steve), Chen committed
979
    assert g.num_nodes() == 3
Minjie Wang's avatar
Minjie Wang committed
980
981
982

    # test ndata and edata
    f1 = F.randn((3, 6))
983
984
    g.ndata["h"] = f1  # ok
    f2 = HG.nodes["user"].data["h"]
Minjie Wang's avatar
Minjie Wang committed
985
    assert F.array_equal(f1, f2)
986
    assert F.array_equal(g.nodes(), F.arange(0, 3, g.idtype))
Minjie Wang's avatar
Minjie Wang committed
987
988

    f3 = F.randn((2, 4))
989
990
    g.edata["h"] = f3
    f4 = HG.edges["follows"].data["h"]
Minjie Wang's avatar
Minjie Wang committed
991
    assert F.array_equal(f3, f4)
992
993
    assert F.array_equal(g.edges(form="eid"), F.arange(0, 2, g.idtype))

Minjie Wang's avatar
Minjie Wang committed
994

nv-dlasalle's avatar
nv-dlasalle committed
995
@parametrize_idtype
996
def test_flatten(idtype):
Minjie Wang's avatar
Minjie Wang committed
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
    def check_mapping(g, fg):
        if len(fg.ntypes) == 1:
            SRC = DST = fg.ntypes[0]
        else:
            SRC = fg.ntypes[0]
            DST = fg.ntypes[1]

        etypes = F.asnumpy(fg.edata[dgl.ETYPE]).tolist()
        eids = F.asnumpy(fg.edata[dgl.EID]).tolist()

        for i, (etype, eid) in enumerate(zip(etypes, eids)):
            src_g, dst_g = g.find_edges([eid], g.canonical_etypes[etype])
            src_fg, dst_fg = fg.find_edges([i])
            # TODO(gq): I feel this code is quite redundant; can we just add new members (like
            # "induced_srcid") to returned heterograph object and not store them as features?
1012
1013
1014
1015
1016
1017
            assert F.asnumpy(src_g) == F.asnumpy(
                F.gather_row(fg.nodes[SRC].data[dgl.NID], src_fg)[0]
            )
            tid = F.asnumpy(
                F.gather_row(fg.nodes[SRC].data[dgl.NTYPE], src_fg)
            ).item()
Minjie Wang's avatar
Minjie Wang committed
1018
            assert g.canonical_etypes[etype][0] == g.ntypes[tid]
1019
1020
1021
1022
1023
1024
            assert F.asnumpy(dst_g) == F.asnumpy(
                F.gather_row(fg.nodes[DST].data[dgl.NID], dst_fg)[0]
            )
            tid = F.asnumpy(
                F.gather_row(fg.nodes[DST].data[dgl.NTYPE], dst_fg)
            ).item()
Minjie Wang's avatar
Minjie Wang committed
1025
1026
1027
            assert g.canonical_etypes[etype][2] == g.ntypes[tid]

    # check for wildcard slices
1028
    g = create_test_heterograph(idtype)
1029
1030
1031
1032
1033
    g.nodes["user"].data["h"] = F.ones((3, 5))
    g.nodes["game"].data["i"] = F.ones((2, 5))
    g.edges["plays"].data["e"] = F.ones((4, 4))
    g.edges["wishes"].data["e"] = F.ones((2, 4))
    g.edges["wishes"].data["f"] = F.ones((2, 4))
Minjie Wang's avatar
Minjie Wang committed
1034

1035
    fg = g["user", :, "game"]  # user--plays->game and user--wishes->game
Minjie Wang's avatar
Minjie Wang committed
1036
    assert len(fg.ntypes) == 2
1037
1038
    assert fg.ntypes == ["user", "game"]
    assert fg.etypes == ["plays+wishes"]
1039
1040
    assert fg.idtype == g.idtype
    assert fg.device == g.device
1041
    etype = fg.etypes[0]
1042
    assert fg[etype] is not None  # Issue #2166
Minjie Wang's avatar
Minjie Wang committed
1043

1044
1045
1046
1047
    assert F.array_equal(fg.nodes["user"].data["h"], F.ones((3, 5)))
    assert F.array_equal(fg.nodes["game"].data["i"], F.ones((2, 5)))
    assert F.array_equal(fg.edata["e"], F.ones((6, 4)))
    assert "f" not in fg.edata
Minjie Wang's avatar
Minjie Wang committed
1048
1049
1050

    etypes = F.asnumpy(fg.edata[dgl.ETYPE]).tolist()
    eids = F.asnumpy(fg.edata[dgl.EID]).tolist()
1051
1052
1053
    assert set(zip(etypes, eids)) == set(
        [(3, 0), (3, 1), (2, 1), (2, 0), (2, 3), (2, 2)]
    )
Minjie Wang's avatar
Minjie Wang committed
1054
1055
1056

    check_mapping(g, fg)

1057
    fg = g["user", :, "user"]
1058
1059
    assert fg.idtype == g.idtype
    assert fg.device == g.device
Minjie Wang's avatar
Minjie Wang committed
1060
1061
    # NOTE(gq): The node/edge types from the parent graph is returned if there is only one
    # node/edge type.  This differs from the behavior above.
1062
1063
1064
1065
    assert fg.ntypes == ["user"]
    assert fg.etypes == ["follows"]
    u1, v1 = g.edges(etype="follows", order="eid")
    u2, v2 = fg.edges(etype="follows", order="eid")
Minjie Wang's avatar
Minjie Wang committed
1066
1067
1068
    assert F.array_equal(u1, u2)
    assert F.array_equal(v1, v2)

1069
    fg = g["developer", :, "game"]
1070
1071
    assert fg.idtype == g.idtype
    assert fg.device == g.device
1072
1073
1074
1075
    assert fg.ntypes == ["developer", "game"]
    assert fg.etypes == ["develops"]
    u1, v1 = g.edges(etype="develops", order="eid")
    u2, v2 = fg.edges(etype="develops", order="eid")
Minjie Wang's avatar
Minjie Wang committed
1076
1077
1078
1079
    assert F.array_equal(u1, u2)
    assert F.array_equal(v1, v2)

    fg = g[:, :, :]
1080
1081
    assert fg.idtype == g.idtype
    assert fg.device == g.device
1082
1083
    assert fg.ntypes == ["developer+user", "game+user"]
    assert fg.etypes == ["develops+follows+plays+wishes"]
Minjie Wang's avatar
Minjie Wang committed
1084
1085
1086
    check_mapping(g, fg)

    # Test another heterograph
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
    g = dgl.heterograph(
        {
            ("user", "follows", "user"): ([0, 1, 2], [1, 2, 3]),
            ("user", "knows", "user"): ([0, 2], [2, 3]),
        },
        idtype=idtype,
        device=F.ctx(),
    )
    g.nodes["user"].data["h"] = F.randn((4, 3))
    g.edges["follows"].data["w"] = F.randn((3, 2))
    g.nodes["user"].data["hh"] = F.randn((4, 5))
    g.edges["knows"].data["ww"] = F.randn((2, 10))

    fg = g["user", :, "user"]
1101
1102
    assert fg.idtype == g.idtype
    assert fg.device == g.device
1103
1104
    assert fg.ntypes == ["user"]
    assert fg.etypes == ["follows+knows"]
Minjie Wang's avatar
Minjie Wang committed
1105
1106
    check_mapping(g, fg)

1107
    fg = g["user", :, :]
1108
1109
    assert fg.idtype == g.idtype
    assert fg.device == g.device
1110
1111
    assert fg.ntypes == ["user"]
    assert fg.etypes == ["follows+knows"]
Minjie Wang's avatar
Minjie Wang committed
1112
1113
    check_mapping(g, fg)

1114
1115
1116
1117

@unittest.skipIf(
    F._default_context_str == "cpu", reason="Need gpu for this test"
)
nv-dlasalle's avatar
nv-dlasalle committed
1118
@parametrize_idtype
1119
1120
1121
1122
def test_to_device(idtype):
    # TODO: rewrite this test case to accept different graphs so we
    #  can test reverse graph and batched graph
    g = create_test_heterograph(idtype)
1123
1124
1125
    g.nodes["user"].data["h"] = F.ones((3, 5))
    g.nodes["game"].data["i"] = F.ones((2, 5))
    g.edges["plays"].data["e"] = F.ones((4, 4))
1126
1127
1128
    assert g.device == F.ctx()
    g = g.to(F.cpu())
    assert g.device == F.cpu()
1129
1130
1131
    assert F.context(g.nodes["user"].data["h"]) == F.cpu()
    assert F.context(g.nodes["game"].data["i"]) == F.cpu()
    assert F.context(g.edges["plays"].data["e"]) == F.cpu()
1132
1133
1134
1135
1136
    for ntype in g.ntypes:
        assert F.context(g.batch_num_nodes(ntype)) == F.cpu()
    for etype in g.canonical_etypes:
        assert F.context(g.batch_num_edges(etype)) == F.cpu()

1137
    if F.is_cuda_available():
1138
        g1 = g.to(F.cuda())
1139
        assert g1.device == F.cuda()
1140
1141
1142
        assert F.context(g1.nodes["user"].data["h"]) == F.cuda()
        assert F.context(g1.nodes["game"].data["i"]) == F.cuda()
        assert F.context(g1.edges["plays"].data["e"]) == F.cuda()
1143
1144
1145
1146
        for ntype in g1.ntypes:
            assert F.context(g1.batch_num_nodes(ntype)) == F.cuda()
        for etype in g1.canonical_etypes:
            assert F.context(g1.batch_num_edges(etype)) == F.cuda()
1147
1148
1149
        assert F.context(g.nodes["user"].data["h"]) == F.cpu()
        assert F.context(g.nodes["game"].data["i"]) == F.cpu()
        assert F.context(g.edges["plays"].data["e"]) == F.cpu()
1150
1151
1152
1153
1154
        for ntype in g.ntypes:
            assert F.context(g.batch_num_nodes(ntype)) == F.cpu()
        for etype in g.canonical_etypes:
            assert F.context(g.batch_num_edges(etype)) == F.cpu()
        with pytest.raises(DGLError):
1155
            g1.nodes["user"].data["h"] = F.copy_to(F.ones((3, 5)), F.cpu())
1156
        with pytest.raises(DGLError):
1157
            g1.edges["plays"].data["e"] = F.copy_to(F.ones((4, 4)), F.cpu())
1158

1159
1160
1161
1162

@unittest.skipIf(
    F._default_context_str == "cpu", reason="Need gpu for this test"
)
nv-dlasalle's avatar
nv-dlasalle committed
1163
@parametrize_idtype
1164
@pytest.mark.parametrize("g", get_cases(["block"]))
1165
1166
1167
1168
def test_to_device2(g, idtype):
    g = g.astype(idtype)
    g = g.to(F.cpu())
    assert g.device == F.cpu()
1169
1170
    if F.is_cuda_available():
        g1 = g.to(F.cuda())
1171
1172
1173
1174
        assert g1.device == F.cuda()
        assert g1.ntypes == g.ntypes
        assert g1.etypes == g.etypes
        assert g1.canonical_etypes == g.canonical_etypes
1175

1176
1177
1178
1179
1180
1181
1182
1183

@unittest.skipIf(
    F._default_context_str == "cpu", reason="Need gpu for this test"
)
@unittest.skipIf(
    dgl.backend.backend_name != "pytorch",
    reason="Pinning graph inplace only supported for PyTorch",
)
nv-dlasalle's avatar
nv-dlasalle committed
1184
@parametrize_idtype
1185
1186
1187
1188
def test_pin_memory_(idtype):
    # TODO: rewrite this test case to accept different graphs so we
    #  can test reverse graph and batched graph
    g = create_test_heterograph(idtype)
1189
1190
1191
    g.nodes["user"].data["h"] = F.ones((3, 5))
    g.nodes["game"].data["i"] = F.ones((2, 5))
    g.edges["plays"].data["e"] = F.ones((4, 4))
1192
1193
1194
    g = g.to(F.cpu())
    assert not g.is_pinned()

1195
1196
1197
1198
    # unpin an unpinned CPU graph, directly return
    g.unpin_memory_()
    assert not g.is_pinned()
    assert g.device == F.cpu()
1199

1200
1201
1202
1203
    # pin a CPU graph
    g.pin_memory_()
    assert g.is_pinned()
    assert g.device == F.cpu()
1204
1205
1206
1207
1208
1209
    assert g.nodes["user"].data["h"].is_pinned()
    assert g.nodes["game"].data["i"].is_pinned()
    assert g.edges["plays"].data["e"].is_pinned()
    assert F.context(g.nodes["user"].data["h"]) == F.cpu()
    assert F.context(g.nodes["game"].data["i"]) == F.cpu()
    assert F.context(g.edges["plays"].data["e"]) == F.cpu()
1210
1211
1212
1213
    for ntype in g.ntypes:
        assert F.context(g.batch_num_nodes(ntype)) == F.cpu()
    for etype in g.canonical_etypes:
        assert F.context(g.batch_num_edges(etype)) == F.cpu()
1214

1215
1216
1217
    # it's fine to clone with new formats, but new graphs are not pinned
    # >>> g.formats()
    # {'created': ['coo'], 'not created': ['csr', 'csc']}
1218
1219
    assert not g.formats("csc").is_pinned()
    assert not g.formats("csr").is_pinned()
1220
    # 'coo' formats is already created and thus not cloned
1221
    assert g.formats("coo").is_pinned()
1222
1223
1224
1225
1226

    # pin a pinned graph, directly return
    g.pin_memory_()
    assert g.is_pinned()
    assert g.device == F.cpu()
1227

1228
1229
1230
1231
    # unpin a pinned graph
    g.unpin_memory_()
    assert not g.is_pinned()
    assert g.device == F.cpu()
1232

1233
    g1 = g.to(F.cuda())
1234

1235
1236
1237
1238
    # unpin an unpinned GPU graph, directly return
    g1.unpin_memory_()
    assert not g1.is_pinned()
    assert g1.device == F.cuda()
1239

1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
    # error pinning a GPU graph
    with pytest.raises(DGLError):
        g1.pin_memory_()

    # test pin empty homograph
    g2 = dgl.graph(([], []))
    g2.pin_memory_()
    assert g2.is_pinned()
    g2.unpin_memory_()
    assert not g2.is_pinned()

    # test pin heterograph with 0 edge of one relation type
1252
1253
1254
    g3 = dgl.heterograph(
        {("a", "b", "c"): ([0, 1], [1, 2]), ("c", "d", "c"): ([], [])}
    ).astype(idtype)
1255
1256
1257
1258
    g3.pin_memory_()
    assert g3.is_pinned()
    g3.unpin_memory_()
    assert not g3.is_pinned()
1259

1260

nv-dlasalle's avatar
nv-dlasalle committed
1261
@parametrize_idtype
1262
def test_convert_bound(idtype):
1263
    def _test_bipartite_bound(data, card):
1264
        with pytest.raises(DGLError):
1265
1266
1267
1268
1269
1270
            dgl.heterograph(
                {("_U", "_E", "_V"): data},
                {"_U": card[0], "_V": card[1]},
                idtype=idtype,
                device=F.ctx(),
            )
1271
1272

    def _test_graph_bound(data, card):
1273
1274
        with pytest.raises(DGLError):
            dgl.graph(data, num_nodes=card, idtype=idtype, device=F.ctx())
1275

1276
1277
1278
1279
    _test_bipartite_bound(([1, 2], [1, 2]), (2, 3))
    _test_bipartite_bound(([0, 1], [1, 4]), (2, 3))
    _test_graph_bound(([1, 3], [1, 2]), 3)
    _test_graph_bound(([0, 1], [1, 3]), 3)
1280
1281


nv-dlasalle's avatar
nv-dlasalle committed
1282
@parametrize_idtype
1283
1284
def test_convert(idtype):
    hg = create_test_heterograph(idtype)
Minjie Wang's avatar
Minjie Wang committed
1285
1286
    hs = []
    for ntype in hg.ntypes:
Hongzhi (Steve), Chen's avatar
Hongzhi (Steve), Chen committed
1287
        h = F.randn((hg.num_nodes(ntype), 5))
1288
        hg.nodes[ntype].data["h"] = h
Minjie Wang's avatar
Minjie Wang committed
1289
        hs.append(h)
1290
    hg.nodes["user"].data["x"] = F.randn((3, 3))
Minjie Wang's avatar
Minjie Wang committed
1291
1292
    ws = []
    for etype in hg.canonical_etypes:
Hongzhi (Steve), Chen's avatar
Hongzhi (Steve), Chen committed
1293
        w = F.randn((hg.num_edges(etype), 5))
1294
        hg.edges[etype].data["w"] = w
Minjie Wang's avatar
Minjie Wang committed
1295
        ws.append(w)
1296
    hg.edges["plays"].data["x"] = F.randn((4, 3))
Minjie Wang's avatar
Minjie Wang committed
1297

1298
    g = dgl.to_homogeneous(hg, ndata=["h"], edata=["w"])
1299
1300
    assert g.idtype == idtype
    assert g.device == hg.device
1301
1302
1303
1304
    assert F.array_equal(F.cat(hs, dim=0), g.ndata["h"])
    assert "x" not in g.ndata
    assert F.array_equal(F.cat(ws, dim=0), g.edata["w"])
    assert "x" not in g.edata
Minjie Wang's avatar
Minjie Wang committed
1305

1306
    src, dst = g.all_edges(order="eid")
Minjie Wang's avatar
Minjie Wang committed
1307
1308
1309
1310
    src = F.asnumpy(src)
    dst = F.asnumpy(dst)
    etype_id, eid = F.asnumpy(g.edata[dgl.ETYPE]), F.asnumpy(g.edata[dgl.EID])
    ntype_id, nid = F.asnumpy(g.ndata[dgl.NTYPE]), F.asnumpy(g.ndata[dgl.NID])
Hongzhi (Steve), Chen's avatar
Hongzhi (Steve), Chen committed
1311
    for i in range(g.num_edges()):
Minjie Wang's avatar
Minjie Wang committed
1312
1313
1314
1315
1316
1317
1318
        srctype = hg.ntypes[ntype_id[src[i]]]
        dsttype = hg.ntypes[ntype_id[dst[i]]]
        etype = hg.etypes[etype_id[i]]
        src_i, dst_i = hg.find_edges([eid[i]], (srctype, etype, dsttype))
        assert np.asscalar(F.asnumpy(src_i)) == nid[src[i]]
        assert np.asscalar(F.asnumpy(dst_i)) == nid[dst[i]]

1319
1320
1321
1322
1323
1324
1325
1326
    mg = nx.MultiDiGraph(
        [
            ("user", "user", "follows"),
            ("user", "game", "plays"),
            ("user", "game", "wishes"),
            ("developer", "game", "develops"),
        ]
    )
Minjie Wang's avatar
Minjie Wang committed
1327
1328

    for _mg in [None, mg]:
1329
        hg2 = dgl.to_heterogeneous(
1330
1331
1332
1333
1334
1335
1336
            g,
            hg.ntypes,
            hg.etypes,
            ntype_field=dgl.NTYPE,
            etype_field=dgl.ETYPE,
            metagraph=_mg,
        )
1337
1338
        assert hg2.idtype == hg.idtype
        assert hg2.device == hg.device
Minjie Wang's avatar
Minjie Wang committed
1339
1340
1341
        assert set(hg.ntypes) == set(hg2.ntypes)
        assert set(hg.canonical_etypes) == set(hg2.canonical_etypes)
        for ntype in hg.ntypes:
Hongzhi (Steve), Chen's avatar
Hongzhi (Steve), Chen committed
1342
            assert hg.num_nodes(ntype) == hg2.num_nodes(ntype)
1343
1344
1345
            assert F.array_equal(
                hg.nodes[ntype].data["h"], hg2.nodes[ntype].data["h"]
            )
Minjie Wang's avatar
Minjie Wang committed
1346
        for canonical_etype in hg.canonical_etypes:
1347
1348
            src, dst = hg.all_edges(etype=canonical_etype, order="eid")
            src2, dst2 = hg2.all_edges(etype=canonical_etype, order="eid")
Minjie Wang's avatar
Minjie Wang committed
1349
1350
            assert F.array_equal(src, src2)
            assert F.array_equal(dst, dst2)
1351
1352
1353
1354
            assert F.array_equal(
                hg.edges[canonical_etype].data["w"],
                hg2.edges[canonical_etype].data["w"],
            )
Minjie Wang's avatar
Minjie Wang committed
1355
1356

    # hetero_from_homo test case 2
1357
    g = dgl.graph(([0, 1, 2, 0], [2, 2, 3, 3]), idtype=idtype, device=F.ctx())
Minjie Wang's avatar
Minjie Wang committed
1358
1359
    g.ndata[dgl.NTYPE] = F.tensor([0, 0, 1, 2])
    g.edata[dgl.ETYPE] = F.tensor([0, 0, 1, 2])
1360
    hg = dgl.to_heterogeneous(g, ["l0", "l1", "l2"], ["e0", "e1", "e2"])
1361
1362
    assert hg.idtype == idtype
    assert hg.device == g.device
Minjie Wang's avatar
Minjie Wang committed
1363
    assert set(hg.canonical_etypes) == set(
1364
1365
        [("l0", "e0", "l1"), ("l1", "e1", "l2"), ("l0", "e2", "l2")]
    )
Hongzhi (Steve), Chen's avatar
Hongzhi (Steve), Chen committed
1366
1367
1368
1369
1370
1371
    assert hg.num_nodes("l0") == 2
    assert hg.num_nodes("l1") == 1
    assert hg.num_nodes("l2") == 1
    assert hg.num_edges("e0") == 2
    assert hg.num_edges("e1") == 1
    assert hg.num_edges("e2") == 1
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
    assert F.array_equal(hg.ndata[dgl.NID]["l0"], F.tensor([0, 1], F.int64))
    assert F.array_equal(hg.ndata[dgl.NID]["l1"], F.tensor([2], F.int64))
    assert F.array_equal(hg.ndata[dgl.NID]["l2"], F.tensor([3], F.int64))
    assert F.array_equal(
        hg.edata[dgl.EID][("l0", "e0", "l1")], F.tensor([0, 1], F.int64)
    )
    assert F.array_equal(
        hg.edata[dgl.EID][("l0", "e2", "l2")], F.tensor([3], F.int64)
    )
    assert F.array_equal(
        hg.edata[dgl.EID][("l1", "e1", "l2")], F.tensor([2], F.int64)
    )
Minjie Wang's avatar
Minjie Wang committed
1384
1385

    # hetero_from_homo test case 3
1386
1387
1388
    mg = nx.MultiDiGraph(
        [("user", "movie", "watches"), ("user", "TV", "watches")]
    )
1389
    g = dgl.graph(((0, 0), (1, 2)), idtype=idtype, device=F.ctx())
Minjie Wang's avatar
Minjie Wang committed
1390
1391
1392
    g.ndata[dgl.NTYPE] = F.tensor([0, 1, 2])
    g.edata[dgl.ETYPE] = F.tensor([0, 0])
    for _mg in [None, mg]:
1393
1394
1395
        hg = dgl.to_heterogeneous(
            g, ["user", "TV", "movie"], ["watches"], metagraph=_mg
        )
1396
1397
        assert hg.idtype == g.idtype
        assert hg.device == g.device
Minjie Wang's avatar
Minjie Wang committed
1398
        assert set(hg.canonical_etypes) == set(
1399
1400
            [("user", "watches", "movie"), ("user", "watches", "TV")]
        )
Hongzhi (Steve), Chen's avatar
Hongzhi (Steve), Chen committed
1401
1402
1403
1404
1405
        assert hg.num_nodes("user") == 1
        assert hg.num_nodes("TV") == 1
        assert hg.num_nodes("movie") == 1
        assert hg.num_edges(("user", "watches", "TV")) == 1
        assert hg.num_edges(("user", "watches", "movie")) == 1
Minjie Wang's avatar
Minjie Wang committed
1406
1407
        assert len(hg.etypes) == 2

1408
    # hetero_to_homo test case 2
1409
1410
1411
1412
1413
1414
    hg = dgl.heterograph(
        {("_U", "_E", "_V"): ([0, 1], [0, 1])},
        {"_U": 2, "_V": 3},
        idtype=idtype,
        device=F.ctx(),
    )
1415
    g = dgl.to_homogeneous(hg)
1416
1417
    assert hg.idtype == g.idtype
    assert hg.device == g.device
Hongzhi (Steve), Chen's avatar
Hongzhi (Steve), Chen committed
1418
    assert g.num_nodes() == 5
1419

1420
    # hetero_to_subgraph_to_homo
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
    hg = dgl.heterograph(
        {
            ("user", "plays", "game"): ([0, 1, 1, 2], [0, 0, 2, 1]),
            ("user", "follows", "user"): ([0, 1, 1], [1, 2, 2]),
        },
        idtype=idtype,
        device=F.ctx(),
    )
    hg.nodes["user"].data["h"] = F.copy_to(
        F.tensor([[1, 0], [0, 1], [1, 1]], dtype=idtype), ctx=F.ctx()
    )
    sg = dgl.node_subgraph(hg, {"user": [1, 2]})
1433
1434
    assert len(sg.ntypes) == 2
    assert len(sg.etypes) == 2
1435
1436
1437
1438
    assert sg.num_nodes("user") == 2
    assert sg.num_nodes("game") == 0
    g = dgl.to_homogeneous(sg, ndata=["h"])
    assert "h" in g.ndata.keys()
1439
1440
    assert g.num_nodes() == 2

1441
1442
1443
1444

@unittest.skipIf(
    F._default_context_str == "gpu", reason="Test on cpu is enough"
)
nv-dlasalle's avatar
nv-dlasalle committed
1445
@parametrize_idtype
1446
1447
def test_to_homo_zero_nodes(idtype):
    # Fix gihub issue #2870
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
    g = dgl.heterograph(
        {
            ("A", "AB", "B"): (
                np.random.randint(0, 200, (1000,)),
                np.random.randint(0, 200, (1000,)),
            ),
            ("B", "BA", "A"): (
                np.random.randint(0, 200, (1000,)),
                np.random.randint(0, 200, (1000,)),
            ),
        },
        num_nodes_dict={"A": 200, "B": 200, "C": 0},
        idtype=idtype,
    )
    g.nodes["A"].data["x"] = F.randn((200, 3))
    g.nodes["B"].data["x"] = F.randn((200, 3))
    gg = dgl.to_homogeneous(g, ["x"])
    assert "x" in gg.ndata

1467

nv-dlasalle's avatar
nv-dlasalle committed
1468
@parametrize_idtype
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
def test_to_homo2(idtype):
    # test the result homogeneous graph has nodes and edges sorted by their types
    hg = create_test_heterograph(idtype)
    g = dgl.to_homogeneous(hg)
    ntypes = F.asnumpy(g.ndata[dgl.NTYPE])
    etypes = F.asnumpy(g.edata[dgl.ETYPE])
    p = 0
    for tid, ntype in enumerate(hg.ntypes):
        num_nodes = hg.num_nodes(ntype)
        for i in range(p, p + num_nodes):
            assert ntypes[i] == tid
        p += num_nodes
    p = 0
    for tid, etype in enumerate(hg.canonical_etypes):
        num_edges = hg.num_edges(etype)
        for i in range(p, p + num_edges):
            assert etypes[i] == tid
        p += num_edges
    # test store_type=False
    g = dgl.to_homogeneous(hg, store_type=False)
    assert dgl.NTYPE not in g.ndata
    assert dgl.ETYPE not in g.edata
    # test return_count=True
    g, ntype_count, etype_count = dgl.to_homogeneous(hg, return_count=True)
    for i, count in enumerate(ntype_count):
        assert count == hg.num_nodes(hg.ntypes[i])
    for i, count in enumerate(etype_count):
        assert count == hg.num_edges(hg.canonical_etypes[i])

1498

nv-dlasalle's avatar
nv-dlasalle committed
1499
@parametrize_idtype
1500
1501
1502
1503
1504
1505
1506
def test_invertible_conversion(idtype):
    # Test whether to_homogeneous and to_heterogeneous are invertible
    hg = create_test_heterograph(idtype)
    g = dgl.to_homogeneous(hg)
    hg2 = dgl.to_heterogeneous(g, hg.ntypes, hg.etypes)
    assert_is_identical_hetero(hg, hg2, True)

1507

nv-dlasalle's avatar
nv-dlasalle committed
1508
@parametrize_idtype
1509
1510
def test_metagraph_reachable(idtype):
    g = create_test_heterograph(idtype)
Mufei Li's avatar
Mufei Li committed
1511
    x = F.randn((3, 5))
1512
    g.nodes["user"].data["h"] = x
Mufei Li's avatar
Mufei Li committed
1513

1514
    new_g = dgl.metapath_reachable_graph(g, ["follows", "plays"])
1515
    assert new_g.idtype == idtype
1516
    assert new_g.ntypes == ["game", "user"]
Hongzhi (Steve), Chen's avatar
Hongzhi (Steve), Chen committed
1517
    assert new_g.num_edges() == 3
Mufei Li's avatar
Mufei Li committed
1518
1519
    assert F.asnumpy(new_g.has_edges_between([0, 0, 1], [0, 1, 1])).all()

1520
    new_g = dgl.metapath_reachable_graph(g, ["follows"])
1521
    assert new_g.idtype == idtype
1522
    assert new_g.ntypes == ["user"]
Hongzhi (Steve), Chen's avatar
Hongzhi (Steve), Chen committed
1523
    assert new_g.num_edges() == 2
Mufei Li's avatar
Mufei Li committed
1524
1525
    assert F.asnumpy(new_g.has_edges_between([0, 1], [1, 2])).all()

1526
1527
1528
1529
1530

@unittest.skipIf(
    dgl.backend.backend_name == "mxnet",
    reason="MXNet doesn't support bool tensor",
)
nv-dlasalle's avatar
nv-dlasalle committed
1531
@parametrize_idtype
1532
1533
def test_subgraph_mask(idtype):
    g = create_test_heterograph(idtype)
1534
1535
    g_graph = g["follows"]
    g_bipartite = g["plays"]
1536
1537
1538

    x = F.randn((3, 5))
    y = F.randn((2, 4))
1539
1540
    g.nodes["user"].data["h"] = x
    g.edges["follows"].data["h"] = y
1541
1542

    def _check_subgraph(g, sg):
1543
1544
        assert sg.idtype == g.idtype
        assert sg.device == g.device
1545
1546
1547
        assert sg.ntypes == g.ntypes
        assert sg.etypes == g.etypes
        assert sg.canonical_etypes == g.canonical_etypes
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
        assert F.array_equal(
            F.tensor(sg.nodes["user"].data[dgl.NID]), F.tensor([1, 2], idtype)
        )
        assert F.array_equal(
            F.tensor(sg.nodes["game"].data[dgl.NID]), F.tensor([0], idtype)
        )
        assert F.array_equal(
            F.tensor(sg.edges["follows"].data[dgl.EID]), F.tensor([1], idtype)
        )
        assert F.array_equal(
            F.tensor(sg.edges["plays"].data[dgl.EID]), F.tensor([1], idtype)
        )
        assert F.array_equal(
            F.tensor(sg.edges["wishes"].data[dgl.EID]), F.tensor([1], idtype)
        )
Hongzhi (Steve), Chen's avatar
Hongzhi (Steve), Chen committed
1563
1564
        assert sg.num_nodes("developer") == 0
        assert sg.num_edges("develops") == 0
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
        assert F.array_equal(
            sg.nodes["user"].data["h"], g.nodes["user"].data["h"][1:3]
        )
        assert F.array_equal(
            sg.edges["follows"].data["h"], g.edges["follows"].data["h"][1:2]
        )

    sg1 = g.subgraph(
        {
            "user": F.tensor([False, True, True], dtype=F.bool),
            "game": F.tensor([True, False, False, False], dtype=F.bool),
        }
    )
1578
    _check_subgraph(g, sg1)
1579
    if F._default_context_str != "gpu":
1580
        # TODO(minjie): enable this later
1581
1582
1583
1584
1585
1586
1587
        sg2 = g.edge_subgraph(
            {
                "follows": F.tensor([False, True], dtype=F.bool),
                "plays": F.tensor([False, True, False, False], dtype=F.bool),
                "wishes": F.tensor([False, True], dtype=F.bool),
            }
        )
1588
        _check_subgraph(g, sg2)
1589

1590

nv-dlasalle's avatar
nv-dlasalle committed
1591
@parametrize_idtype
1592
1593
def test_subgraph(idtype):
    g = create_test_heterograph(idtype)
1594
1595
    g_graph = g["follows"]
    g_bipartite = g["plays"]
Quan (Andy) Gan's avatar
Quan (Andy) Gan committed
1596

Minjie Wang's avatar
Minjie Wang committed
1597
1598
    x = F.randn((3, 5))
    y = F.randn((2, 4))
1599
1600
    g.nodes["user"].data["h"] = x
    g.edges["follows"].data["h"] = y
Minjie Wang's avatar
Minjie Wang committed
1601
1602

    def _check_subgraph(g, sg):
1603
1604
        assert sg.idtype == g.idtype
        assert sg.device == g.device
1605
1606
1607
        assert sg.ntypes == g.ntypes
        assert sg.etypes == g.etypes
        assert sg.canonical_etypes == g.canonical_etypes
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
        assert F.array_equal(
            F.tensor(sg.nodes["user"].data[dgl.NID]), F.tensor([1, 2], g.idtype)
        )
        assert F.array_equal(
            F.tensor(sg.nodes["game"].data[dgl.NID]), F.tensor([0], g.idtype)
        )
        assert F.array_equal(
            F.tensor(sg.edges["follows"].data[dgl.EID]), F.tensor([1], g.idtype)
        )
        assert F.array_equal(
            F.tensor(sg.edges["plays"].data[dgl.EID]), F.tensor([1], g.idtype)
        )
        assert F.array_equal(
            F.tensor(sg.edges["wishes"].data[dgl.EID]), F.tensor([1], g.idtype)
        )
Hongzhi (Steve), Chen's avatar
Hongzhi (Steve), Chen committed
1623
1624
        assert sg.num_nodes("developer") == 0
        assert sg.num_edges("develops") == 0
1625
1626
1627
1628
1629
1630
1631
1632
        assert F.array_equal(
            sg.nodes["user"].data["h"], g.nodes["user"].data["h"][1:3]
        )
        assert F.array_equal(
            sg.edges["follows"].data["h"], g.edges["follows"].data["h"][1:2]
        )

    sg1 = g.subgraph({"user": [1, 2], "game": [0]})
Minjie Wang's avatar
Minjie Wang committed
1633
    _check_subgraph(g, sg1)
1634
    if F._default_context_str != "gpu":
1635
        # TODO(minjie): enable this later
1636
        sg2 = g.edge_subgraph({"follows": [1], "plays": [1], "wishes": [1]})
1637
        _check_subgraph(g, sg2)
Minjie Wang's avatar
Minjie Wang committed
1638

1639
    # backend tensor input
1640
1641
1642
1643
1644
1645
    sg1 = g.subgraph(
        {
            "user": F.tensor([1, 2], dtype=idtype),
            "game": F.tensor([0], dtype=idtype),
        }
    )
1646
    _check_subgraph(g, sg1)
1647
    if F._default_context_str != "gpu":
1648
        # TODO(minjie): enable this later
1649
1650
1651
1652
1653
1654
1655
        sg2 = g.edge_subgraph(
            {
                "follows": F.tensor([1], dtype=idtype),
                "plays": F.tensor([1], dtype=idtype),
                "wishes": F.tensor([1], dtype=idtype),
            }
        )
1656
        _check_subgraph(g, sg2)
1657
1658

    # numpy input
1659
    sg1 = g.subgraph({"user": np.array([1, 2]), "game": np.array([0])})
1660
    _check_subgraph(g, sg1)
1661
    if F._default_context_str != "gpu":
1662
        # TODO(minjie): enable this later
1663
1664
1665
1666
1667
1668
1669
        sg2 = g.edge_subgraph(
            {
                "follows": np.array([1]),
                "plays": np.array([1]),
                "wishes": np.array([1]),
            }
        )
1670
        _check_subgraph(g, sg2)
1671

Quan (Andy) Gan's avatar
Quan (Andy) Gan committed
1672
    def _check_subgraph_single_ntype(g, sg, preserve_nodes=False):
1673
1674
        assert sg.idtype == g.idtype
        assert sg.device == g.device
Quan (Andy) Gan's avatar
Quan (Andy) Gan committed
1675
1676
1677
        assert sg.ntypes == g.ntypes
        assert sg.etypes == g.etypes
        assert sg.canonical_etypes == g.canonical_etypes
Quan (Andy) Gan's avatar
Quan (Andy) Gan committed
1678
1679

        if not preserve_nodes:
1680
1681
1682
1683
            assert F.array_equal(
                F.tensor(sg.nodes["user"].data[dgl.NID]),
                F.tensor([1, 2], g.idtype),
            )
Quan (Andy) Gan's avatar
Quan (Andy) Gan committed
1684
1685
        else:
            for ntype in sg.ntypes:
Hongzhi (Steve), Chen's avatar
Hongzhi (Steve), Chen committed
1686
                assert g.num_nodes(ntype) == sg.num_nodes(ntype)
Quan (Andy) Gan's avatar
Quan (Andy) Gan committed
1687

1688
1689
1690
        assert F.array_equal(
            F.tensor(sg.edges["follows"].data[dgl.EID]), F.tensor([1], g.idtype)
        )
Quan (Andy) Gan's avatar
Quan (Andy) Gan committed
1691
1692

        if not preserve_nodes:
1693
1694
1695
1696
1697
1698
            assert F.array_equal(
                sg.nodes["user"].data["h"], g.nodes["user"].data["h"][1:3]
            )
        assert F.array_equal(
            sg.edges["follows"].data["h"], g.edges["follows"].data["h"][1:2]
        )
Quan (Andy) Gan's avatar
Quan (Andy) Gan committed
1699

Quan (Andy) Gan's avatar
Quan (Andy) Gan committed
1700
    def _check_subgraph_single_etype(g, sg, preserve_nodes=False):
Quan (Andy) Gan's avatar
Quan (Andy) Gan committed
1701
1702
1703
        assert sg.ntypes == g.ntypes
        assert sg.etypes == g.etypes
        assert sg.canonical_etypes == g.canonical_etypes
Quan (Andy) Gan's avatar
Quan (Andy) Gan committed
1704
1705

        if not preserve_nodes:
1706
1707
1708
1709
1710
1711
1712
1713
            assert F.array_equal(
                F.tensor(sg.nodes["user"].data[dgl.NID]),
                F.tensor([0, 1], g.idtype),
            )
            assert F.array_equal(
                F.tensor(sg.nodes["game"].data[dgl.NID]),
                F.tensor([0], g.idtype),
            )
Quan (Andy) Gan's avatar
Quan (Andy) Gan committed
1714
1715
        else:
            for ntype in sg.ntypes:
Hongzhi (Steve), Chen's avatar
Hongzhi (Steve), Chen committed
1716
                assert g.num_nodes(ntype) == sg.num_nodes(ntype)
Quan (Andy) Gan's avatar
Quan (Andy) Gan committed
1717

1718
1719
1720
1721
        assert F.array_equal(
            F.tensor(sg.edges["plays"].data[dgl.EID]),
            F.tensor([0, 1], g.idtype),
        )
Quan (Andy) Gan's avatar
Quan (Andy) Gan committed
1722
1723
1724

    sg1_graph = g_graph.subgraph([1, 2])
    _check_subgraph_single_ntype(g_graph, sg1_graph)
1725
    if F._default_context_str != "gpu":
1726
1727
1728
        # TODO(minjie): enable this later
        sg1_graph = g_graph.edge_subgraph([1])
        _check_subgraph_single_ntype(g_graph, sg1_graph)
1729
        sg1_graph = g_graph.edge_subgraph([1], relabel_nodes=False)
1730
1731
1732
        _check_subgraph_single_ntype(g_graph, sg1_graph, True)
        sg2_bipartite = g_bipartite.edge_subgraph([0, 1])
        _check_subgraph_single_etype(g_bipartite, sg2_bipartite)
1733
        sg2_bipartite = g_bipartite.edge_subgraph([0, 1], relabel_nodes=False)
1734
        _check_subgraph_single_etype(g_bipartite, sg2_bipartite, True)
Quan (Andy) Gan's avatar
Quan (Andy) Gan committed
1735

1736
    def _check_typed_subgraph1(g, sg):
1737
1738
        assert g.idtype == sg.idtype
        assert g.device == sg.device
1739
1740
        assert set(sg.ntypes) == {"user", "game"}
        assert set(sg.etypes) == {"follows", "plays", "wishes"}
Minjie Wang's avatar
Minjie Wang committed
1741
        for ntype in sg.ntypes:
Hongzhi (Steve), Chen's avatar
Hongzhi (Steve), Chen committed
1742
            assert sg.num_nodes(ntype) == g.num_nodes(ntype)
Minjie Wang's avatar
Minjie Wang committed
1743
        for etype in sg.etypes:
1744
1745
            src_sg, dst_sg = sg.all_edges(etype=etype, order="eid")
            src_g, dst_g = g.all_edges(etype=etype, order="eid")
Minjie Wang's avatar
Minjie Wang committed
1746
1747
            assert F.array_equal(src_sg, src_g)
            assert F.array_equal(dst_sg, dst_g)
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
        assert F.array_equal(
            sg.nodes["user"].data["h"], g.nodes["user"].data["h"]
        )
        assert F.array_equal(
            sg.edges["follows"].data["h"], g.edges["follows"].data["h"]
        )
        g.nodes["user"].data["h"] = F.scatter_row(
            g.nodes["user"].data["h"], F.tensor([2]), F.randn((1, 5))
        )
        g.edges["follows"].data["h"] = F.scatter_row(
            g.edges["follows"].data["h"], F.tensor([1]), F.randn((1, 4))
        )
        assert F.array_equal(
            sg.nodes["user"].data["h"], g.nodes["user"].data["h"]
        )
        assert F.array_equal(
            sg.edges["follows"].data["h"], g.edges["follows"].data["h"]
        )
Minjie Wang's avatar
Minjie Wang committed
1766

1767
    def _check_typed_subgraph2(g, sg):
1768
1769
        assert set(sg.ntypes) == {"developer", "game"}
        assert set(sg.etypes) == {"develops"}
1770
        for ntype in sg.ntypes:
Hongzhi (Steve), Chen's avatar
Hongzhi (Steve), Chen committed
1771
            assert sg.num_nodes(ntype) == g.num_nodes(ntype)
1772
        for etype in sg.etypes:
1773
1774
            src_sg, dst_sg = sg.all_edges(etype=etype, order="eid")
            src_g, dst_g = g.all_edges(etype=etype, order="eid")
1775
1776
1777
            assert F.array_equal(src_sg, src_g)
            assert F.array_equal(dst_sg, dst_g)

1778
    sg3 = g.node_type_subgraph(["user", "game"])
1779
    _check_typed_subgraph1(g, sg3)
1780
    sg4 = g.edge_type_subgraph(["develops"])
1781
    _check_typed_subgraph2(g, sg4)
1782
    sg5 = g.edge_type_subgraph(["follows", "plays", "wishes"])
1783
    _check_typed_subgraph1(g, sg5)
1784

1785

nv-dlasalle's avatar
nv-dlasalle committed
1786
@parametrize_idtype
1787
def test_apply(idtype):
1788
    def node_udf(nodes):
1789
1790
        return {"h": nodes.data["h"] * 2}

1791
    def node_udf2(nodes):
1792
1793
        return {"h": F.sum(nodes.data["h"], dim=1, keepdims=True)}

1794
    def edge_udf(edges):
1795
        return {"h": edges.data["h"] * 2 + edges.src["h"]}
1796

1797
    g = create_test_heterograph(idtype)
1798
1799
1800
    g.nodes["user"].data["h"] = F.ones((3, 5))
    g.apply_nodes(node_udf, ntype="user")
    assert F.array_equal(g.nodes["user"].data["h"], F.ones((3, 5)) * 2)
Minjie Wang's avatar
Minjie Wang committed
1801

1802
1803
1804
    g["plays"].edata["h"] = F.ones((4, 5))
    g.apply_edges(edge_udf, etype=("user", "plays", "game"))
    assert F.array_equal(g["plays"].edata["h"], F.ones((4, 5)) * 4)
Minjie Wang's avatar
Minjie Wang committed
1805
1806

    # test apply on graph with only one type
1807
1808
    g["follows"].apply_nodes(node_udf)
    assert F.array_equal(g.nodes["user"].data["h"], F.ones((3, 5)) * 4)
1809

1810
1811
    g["plays"].apply_edges(edge_udf)
    assert F.array_equal(g["plays"].edata["h"], F.ones((4, 5)) * 12)
Minjie Wang's avatar
Minjie Wang committed
1812

1813
    # Test the case that feature size changes
1814
1815
1816
    g.nodes["user"].data["h"] = F.ones((3, 5))
    g.apply_nodes(node_udf2, ntype="user")
    assert F.array_equal(g.nodes["user"].data["h"], F.ones((3, 1)) * 5)
1817

Minjie Wang's avatar
Minjie Wang committed
1818
1819
    # test fail case
    # fail due to multiple types
1820
    with pytest.raises(DGLError):
Minjie Wang's avatar
Minjie Wang committed
1821
1822
        g.apply_nodes(node_udf)

1823
    with pytest.raises(DGLError):
Minjie Wang's avatar
Minjie Wang committed
1824
1825
        g.apply_edges(edge_udf)

1826

nv-dlasalle's avatar
nv-dlasalle committed
1827
@parametrize_idtype
1828
def test_level2(idtype):
1829
    # edges = {
Minjie Wang's avatar
Minjie Wang committed
1830
1831
1832
1833
    #    'follows': ([0, 1], [1, 2]),
    #    'plays': ([0, 1, 2, 1], [0, 0, 1, 1]),
    #    'wishes': ([0, 2], [1, 0]),
    #    'develops': ([0, 1], [0, 1]),
1834
    # }
1835
    g = create_test_heterograph(idtype)
1836

Minjie Wang's avatar
Minjie Wang committed
1837
    def rfunc(nodes):
1838
1839
        return {"y": F.sum(nodes.mailbox["m"], 1)}

Minjie Wang's avatar
Minjie Wang committed
1840
    def rfunc2(nodes):
1841
1842
        return {"y": F.max(nodes.mailbox["m"], 1)}

Minjie Wang's avatar
Minjie Wang committed
1843
    def mfunc(edges):
1844
1845
        return {"m": edges.src["h"]}

Minjie Wang's avatar
Minjie Wang committed
1846
    def afunc(nodes):
1847
        return {"y": nodes.data["y"] + 1}
Minjie Wang's avatar
Minjie Wang committed
1848
1849
1850
1851
1852

    #############################################################
    #  send_and_recv
    #############################################################

1853
1854
1855
1856
    g.nodes["user"].data["h"] = F.ones((3, 2))
    g.send_and_recv([2, 3], mfunc, rfunc, etype="plays")
    y = g.nodes["game"].data["y"]
    assert F.array_equal(y, F.tensor([[0.0, 0.0], [2.0, 2.0]]))
Minjie Wang's avatar
Minjie Wang committed
1857
1858

    # only one type
1859
1860
1861
    g["plays"].send_and_recv([2, 3], mfunc, rfunc)
    y = g.nodes["game"].data["y"]
    assert F.array_equal(y, F.tensor([[0.0, 0.0], [2.0, 2.0]]))
1862

Minjie Wang's avatar
Minjie Wang committed
1863
1864
    # test fail case
    # fail due to multiple types
1865
    with pytest.raises(DGLError):
Minjie Wang's avatar
Minjie Wang committed
1866
1867
        g.send_and_recv([2, 3], mfunc, rfunc)

1868
    g.nodes["game"].data.clear()
Minjie Wang's avatar
Minjie Wang committed
1869
1870
1871
1872
1873

    #############################################################
    #  pull
    #############################################################

1874
1875
1876
1877
    g.nodes["user"].data["h"] = F.ones((3, 2))
    g.pull(1, mfunc, rfunc, etype="plays")
    y = g.nodes["game"].data["y"]
    assert F.array_equal(y, F.tensor([[0.0, 0.0], [2.0, 2.0]]))
Minjie Wang's avatar
Minjie Wang committed
1878
1879

    # only one type
1880
1881
1882
    g["plays"].pull(1, mfunc, rfunc)
    y = g.nodes["game"].data["y"]
    assert F.array_equal(y, F.tensor([[0.0, 0.0], [2.0, 2.0]]))
Minjie Wang's avatar
Minjie Wang committed
1883
1884

    # test fail case
1885
    with pytest.raises(DGLError):
Minjie Wang's avatar
Minjie Wang committed
1886
1887
        g.pull(1, mfunc, rfunc)

1888
    g.nodes["game"].data.clear()
Minjie Wang's avatar
Minjie Wang committed
1889
1890
1891
1892
1893

    #############################################################
    #  update_all
    #############################################################

1894
1895
1896
1897
    g.nodes["user"].data["h"] = F.ones((3, 2))
    g.update_all(mfunc, rfunc, etype="plays")
    y = g.nodes["game"].data["y"]
    assert F.array_equal(y, F.tensor([[2.0, 2.0], [2.0, 2.0]]))
Minjie Wang's avatar
Minjie Wang committed
1898
1899

    # only one type
1900
1901
1902
    g["plays"].update_all(mfunc, rfunc)
    y = g.nodes["game"].data["y"]
    assert F.array_equal(y, F.tensor([[2.0, 2.0], [2.0, 2.0]]))
Minjie Wang's avatar
Minjie Wang committed
1903
1904
1905

    # test fail case
    # fail due to multiple types
1906
    with pytest.raises(DGLError):
Minjie Wang's avatar
Minjie Wang committed
1907
1908
1909
1910
        g.update_all(mfunc, rfunc)

    # test multi
    g.multi_update_all(
1911
1912
1913
1914
1915
1916
        {"plays": (mfunc, rfunc), ("user", "wishes", "game"): (mfunc, rfunc2)},
        "sum",
    )
    assert F.array_equal(
        g.nodes["game"].data["y"], F.tensor([[3.0, 3.0], [3.0, 3.0]])
    )
Minjie Wang's avatar
Minjie Wang committed
1917
1918
1919

    # test multi
    g.multi_update_all(
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
        {
            "plays": (mfunc, rfunc, afunc),
            ("user", "wishes", "game"): (mfunc, rfunc2),
        },
        "sum",
        afunc,
    )
    assert F.array_equal(
        g.nodes["game"].data["y"], F.tensor([[5.0, 5.0], [5.0, 5.0]])
    )
Minjie Wang's avatar
Minjie Wang committed
1930
1931

    # test cross reducer
1932
1933
    g.nodes["user"].data["h"] = F.randn((3, 2))
    for cred in ["sum", "max", "min", "mean", "stack"]:
Minjie Wang's avatar
Minjie Wang committed
1934
        g.multi_update_all(
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
            {"plays": (mfunc, rfunc, afunc), "wishes": (mfunc, rfunc2)},
            cred,
            afunc,
        )
        y = g.nodes["game"].data["y"]
        g["plays"].update_all(mfunc, rfunc, afunc)
        y1 = g.nodes["game"].data["y"]
        g["wishes"].update_all(mfunc, rfunc2)
        y2 = g.nodes["game"].data["y"]
        if cred == "stack":
1945
1946
1947
1948
            # stack has an internal order by edge type id
            yy = F.stack([y1, y2], 1)
            yy = yy + 1  # final afunc
            assert F.array_equal(y, yy)
Minjie Wang's avatar
Minjie Wang committed
1949
1950
1951
1952
1953
1954
1955
        else:
            yy = get_redfn(cred)(F.stack([y1, y2], 0), 0)
            yy = yy + 1  # final afunc
            assert F.array_equal(y, yy)

    # test fail case
    # fail because cannot infer ntype
1956
    with pytest.raises(DGLError):
Minjie Wang's avatar
Minjie Wang committed
1957
        g.update_all(
1958
1959
1960
1961
            {"plays": (mfunc, rfunc), "follows": (mfunc, rfunc2)}, "sum"
        )

    g.nodes["game"].data.clear()
Minjie Wang's avatar
Minjie Wang committed
1962

1963

nv-dlasalle's avatar
nv-dlasalle committed
1964
@parametrize_idtype
1965
1966
1967
@unittest.skipIf(
    F._default_context_str == "cpu", reason="Need gpu for this test"
)
1968
def test_more_nnz(idtype):
1969
1970
1971
1972
1973
1974
    g = dgl.graph(
        ([0, 0, 0, 0, 0], [1, 1, 1, 1, 1]), idtype=idtype, device=F.ctx()
    )
    g.ndata["x"] = F.copy_to(F.ones((2, 5)), ctx=F.ctx())
    g.update_all(fn.copy_u("x", "m"), fn.sum("m", "y"))
    y = g.ndata["y"]
1975
1976
1977
1978
1979
    ans = np.zeros((2, 5))
    ans[1] = 5
    ans = F.copy_to(F.tensor(ans, dtype=F.dtype(y)), ctx=F.ctx())
    assert F.array_equal(y, ans)

1980

nv-dlasalle's avatar
nv-dlasalle committed
1981
@parametrize_idtype
1982
def test_updates(idtype):
1983
    def msg_func(edges):
1984
1985
        return {"m": edges.src["h"]}

1986
    def reduce_func(nodes):
1987
1988
        return {"y": F.sum(nodes.mailbox["m"], 1)}

1989
    def apply_func(nodes):
1990
1991
        return {"y": nodes.data["y"] * 2}

1992
    g = create_test_heterograph(idtype)
1993
    x = F.randn((3, 5))
1994
    g.nodes["user"].data["h"] = x
1995
1996

    for msg, red, apply in itertools.product(
1997
1998
1999
2000
        [fn.copy_u("h", "m"), msg_func],
        [fn.sum("m", "y"), reduce_func],
        [None, apply_func],
    ):
2001
2002
        multiplier = 1 if apply is None else 2

2003
2004
        g["user", "plays", "game"].update_all(msg, red, apply)
        y = g.nodes["game"].data["y"]
2005
2006
        assert F.array_equal(y[0], (x[0] + x[1]) * multiplier)
        assert F.array_equal(y[1], (x[1] + x[2]) * multiplier)
2007
        del g.nodes["game"].data["y"]
2008

2009
2010
2011
2012
        g["user", "plays", "game"].send_and_recv(
            ([0, 1, 2], [0, 1, 1]), msg, red, apply
        )
        y = g.nodes["game"].data["y"]
2013
2014
        assert F.array_equal(y[0], x[0] * multiplier)
        assert F.array_equal(y[1], (x[1] + x[2]) * multiplier)
2015
        del g.nodes["game"].data["y"]
2016
2017

        # pulls from destination (game) node 0
2018
2019
        g["user", "plays", "game"].pull(0, msg, red, apply)
        y = g.nodes["game"].data["y"]
2020
        assert F.array_equal(y[0], (x[0] + x[1]) * multiplier)
2021
        del g.nodes["game"].data["y"]
2022
2023

        # pushes from source (user) node 0
2024
2025
        g["user", "plays", "game"].push(0, msg, red, apply)
        y = g.nodes["game"].data["y"]
2026
        assert F.array_equal(y[0], x[0] * multiplier)
2027
        del g.nodes["game"].data["y"]
Minjie Wang's avatar
Minjie Wang committed
2028

2029

nv-dlasalle's avatar
nv-dlasalle committed
2030
@parametrize_idtype
2031
2032
def test_backward(idtype):
    g = create_test_heterograph(idtype)
Minjie Wang's avatar
Minjie Wang committed
2033
2034
    x = F.randn((3, 5))
    F.attach_grad(x)
2035
    g.nodes["user"].data["h"] = x
Minjie Wang's avatar
Minjie Wang committed
2036
2037
    with F.record_grad():
        g.multi_update_all(
2038
2039
2040
2041
2042
2043
2044
            {
                "plays": (fn.copy_u("h", "m"), fn.sum("m", "y")),
                "wishes": (fn.copy_u("h", "m"), fn.sum("m", "y")),
            },
            "sum",
        )
        y = g.nodes["game"].data["y"]
Minjie Wang's avatar
Minjie Wang committed
2045
2046
        F.backward(y, F.ones(y.shape))
    print(F.grad(x))
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
    assert F.array_equal(
        F.grad(x),
        F.tensor(
            [
                [2.0, 2.0, 2.0, 2.0, 2.0],
                [2.0, 2.0, 2.0, 2.0, 2.0],
                [2.0, 2.0, 2.0, 2.0, 2.0],
            ]
        ),
    )
2057

2058

nv-dlasalle's avatar
nv-dlasalle committed
2059
@parametrize_idtype
2060
def test_empty_heterograph(idtype):
2061
    def assert_empty(g):
Hongzhi (Steve), Chen's avatar
Hongzhi (Steve), Chen committed
2062
2063
2064
        assert g.num_nodes("user") == 0
        assert g.num_edges("plays") == 0
        assert g.num_nodes("game") == 0
2065
2066

    # empty src-dst pair
2067
    assert_empty(dgl.heterograph({("user", "plays", "game"): ([], [])}))
2068

2069
2070
2071
    g = dgl.heterograph(
        {("user", "follows", "user"): ([], [])}, idtype=idtype, device=F.ctx()
    )
2072
2073
    assert g.idtype == idtype
    assert g.device == F.ctx()
Hongzhi (Steve), Chen's avatar
Hongzhi (Steve), Chen committed
2074
2075
    assert g.num_nodes("user") == 0
    assert g.num_edges("follows") == 0
2076
2077

    # empty relation graph with others
2078
2079
2080
2081
2082
2083
2084
2085
    g = dgl.heterograph(
        {
            ("user", "plays", "game"): ([], []),
            ("developer", "develops", "game"): ([0, 1], [0, 1]),
        },
        idtype=idtype,
        device=F.ctx(),
    )
2086
2087
    assert g.idtype == idtype
    assert g.device == F.ctx()
Hongzhi (Steve), Chen's avatar
Hongzhi (Steve), Chen committed
2088
2089
2090
2091
2092
    assert g.num_nodes("user") == 0
    assert g.num_edges("plays") == 0
    assert g.num_nodes("game") == 2
    assert g.num_edges("develops") == 2
    assert g.num_nodes("developer") == 2
2093

2094

nv-dlasalle's avatar
nv-dlasalle committed
2095
@parametrize_idtype
2096
def test_types_in_function(idtype):
2097
    def mfunc1(edges):
2098
        assert edges.canonical_etype == ("user", "follow", "user")
2099
2100
2101
        return {}

    def rfunc1(nodes):
2102
        assert nodes.ntype == "user"
2103
2104
2105
        return {}

    def filter_nodes1(nodes):
2106
        assert nodes.ntype == "user"
2107
2108
2109
        return F.zeros((3,))

    def filter_edges1(edges):
2110
        assert edges.canonical_etype == ("user", "follow", "user")
2111
2112
2113
        return F.zeros((2,))

    def mfunc2(edges):
2114
        assert edges.canonical_etype == ("user", "plays", "game")
2115
2116
2117
        return {}

    def rfunc2(nodes):
2118
        assert nodes.ntype == "game"
2119
2120
2121
        return {}

    def filter_nodes2(nodes):
2122
        assert nodes.ntype == "game"
2123
2124
2125
        return F.zeros((3,))

    def filter_edges2(edges):
2126
        assert edges.canonical_etype == ("user", "plays", "game")
2127
2128
        return F.zeros((2,))

2129
2130
2131
2132
2133
    g = dgl.heterograph(
        {("user", "follow", "user"): ((0, 1), (1, 2))},
        idtype=idtype,
        device=F.ctx(),
    )
2134
2135
2136
2137
2138
2139
2140
2141
2142
    g.apply_nodes(rfunc1)
    g.apply_edges(mfunc1)
    g.update_all(mfunc1, rfunc1)
    g.send_and_recv([0, 1], mfunc1, rfunc1)
    g.push([0], mfunc1, rfunc1)
    g.pull([1], mfunc1, rfunc1)
    g.filter_nodes(filter_nodes1)
    g.filter_edges(filter_edges1)

2143
2144
2145
2146
2147
2148
    g = dgl.heterograph(
        {("user", "plays", "game"): ([0, 1], [1, 2])},
        idtype=idtype,
        device=F.ctx(),
    )
    g.apply_nodes(rfunc2, ntype="game")
2149
2150
2151
2152
2153
    g.apply_edges(mfunc2)
    g.update_all(mfunc2, rfunc2)
    g.send_and_recv([0, 1], mfunc2, rfunc2)
    g.push([0], mfunc2, rfunc2)
    g.pull([1], mfunc2, rfunc2)
2154
    g.filter_nodes(filter_nodes2, ntype="game")
2155
2156
    g.filter_edges(filter_edges2)

2157

nv-dlasalle's avatar
nv-dlasalle committed
2158
@parametrize_idtype
2159
def test_stack_reduce(idtype):
2160
    # edges = {
2161
2162
2163
2164
    #    'follows': ([0, 1], [1, 2]),
    #    'plays': ([0, 1, 2, 1], [0, 0, 1, 1]),
    #    'wishes': ([0, 2], [1, 0]),
    #    'develops': ([0, 1], [0, 1]),
2165
    # }
2166
    g = create_test_heterograph(idtype)
2167
2168
    g.nodes["user"].data["h"] = F.randn((3, 200))

2169
    def rfunc(nodes):
2170
2171
        return {"y": F.sum(nodes.mailbox["m"], 1)}

2172
    def rfunc2(nodes):
2173
2174
        return {"y": F.max(nodes.mailbox["m"], 1)}

2175
    def mfunc(edges):
2176
2177
        return {"m": edges.src["h"]}

2178
    g.multi_update_all(
2179
2180
2181
        {"plays": (mfunc, rfunc), "wishes": (mfunc, rfunc2)}, "stack"
    )
    assert g.nodes["game"].data["y"].shape == (
Hongzhi (Steve), Chen's avatar
Hongzhi (Steve), Chen committed
2182
        g.num_nodes("game"),
2183
2184
2185
        2,
        200,
    )
2186
    # only one type-wise update_all, stack still adds one dimension
2187
2188
    g.multi_update_all({"plays": (mfunc, rfunc)}, "stack")
    assert g.nodes["game"].data["y"].shape == (
Hongzhi (Steve), Chen's avatar
Hongzhi (Steve), Chen committed
2189
        g.num_nodes("game"),
2190
2191
2192
2193
        1,
        200,
    )

2194

nv-dlasalle's avatar
nv-dlasalle committed
2195
@parametrize_idtype
2196
def test_isolated_ntype(idtype):
2197
2198
2199
2200
2201
2202
    g = dgl.heterograph(
        {("A", "AB", "B"): ([0, 1, 2], [1, 2, 3])},
        num_nodes_dict={"A": 3, "B": 4, "C": 4},
        idtype=idtype,
        device=F.ctx(),
    )
Hongzhi (Steve), Chen's avatar
Hongzhi (Steve), Chen committed
2203
2204
2205
    assert g.num_nodes("A") == 3
    assert g.num_nodes("B") == 4
    assert g.num_nodes("C") == 4
2206
2207
2208
2209
2210
2211
2212

    g = dgl.heterograph(
        {("A", "AC", "C"): ([0, 1, 2], [1, 2, 3])},
        num_nodes_dict={"A": 3, "B": 4, "C": 4},
        idtype=idtype,
        device=F.ctx(),
    )
Hongzhi (Steve), Chen's avatar
Hongzhi (Steve), Chen committed
2213
2214
2215
    assert g.num_nodes("A") == 3
    assert g.num_nodes("B") == 4
    assert g.num_nodes("C") == 4
2216
2217
2218
2219
2220
2221
2222

    G = dgl.graph(
        ([0, 1, 2], [4, 5, 6]), num_nodes=11, idtype=idtype, device=F.ctx()
    )
    G.ndata[dgl.NTYPE] = F.tensor(
        [0, 0, 0, 1, 1, 1, 1, 2, 2, 2, 2], dtype=F.int64
    )
2223
    G.edata[dgl.ETYPE] = F.tensor([0, 0, 0], dtype=F.int64)
2224
    g = dgl.to_heterogeneous(G, ["A", "B", "C"], ["AB"])
Hongzhi (Steve), Chen's avatar
Hongzhi (Steve), Chen committed
2225
2226
2227
    assert g.num_nodes("A") == 3
    assert g.num_nodes("B") == 4
    assert g.num_nodes("C") == 4
2228

2229

nv-dlasalle's avatar
nv-dlasalle committed
2230
@parametrize_idtype
2231
def test_ismultigraph(idtype):
2232
2233
2234
2235
2236
2237
    g1 = dgl.heterograph(
        {("A", "AB", "B"): ([0, 0, 1, 2], [1, 2, 5, 5])},
        {"A": 6, "B": 6},
        idtype=idtype,
        device=F.ctx(),
    )
2238
    assert g1.is_multigraph == False
2239
2240
2241
2242
2243
2244
    g2 = dgl.heterograph(
        {("A", "AC", "C"): ([0, 0, 0, 1], [1, 1, 2, 5])},
        {"A": 6, "C": 6},
        idtype=idtype,
        device=F.ctx(),
    )
2245
    assert g2.is_multigraph == True
2246
    g3 = dgl.graph(((0, 1), (1, 2)), num_nodes=6, idtype=idtype, device=F.ctx())
2247
    assert g3.is_multigraph == False
2248
2249
2250
    g4 = dgl.graph(
        ([0, 0, 1], [1, 1, 2]), num_nodes=6, idtype=idtype, device=F.ctx()
    )
2251
    assert g4.is_multigraph == True
2252
2253
2254
2255
2256
2257
2258
2259
2260
    g = dgl.heterograph(
        {
            ("A", "AB", "B"): ([0, 0, 1, 2], [1, 2, 5, 5]),
            ("A", "AA", "A"): ([0, 1], [1, 2]),
        },
        {"A": 6, "B": 6},
        idtype=idtype,
        device=F.ctx(),
    )
2261
    assert g.is_multigraph == False
2262
2263
2264
2265
2266
2267
2268
2269
2270
    g = dgl.heterograph(
        {
            ("A", "AB", "B"): ([0, 0, 1, 2], [1, 2, 5, 5]),
            ("A", "AC", "C"): ([0, 0, 0, 1], [1, 1, 2, 5]),
        },
        {"A": 6, "B": 6, "C": 6},
        idtype=idtype,
        device=F.ctx(),
    )
2271
    assert g.is_multigraph == True
2272
2273
2274
2275
2276
2277
2278
2279
2280
    g = dgl.heterograph(
        {
            ("A", "AB", "B"): ([0, 0, 1, 2], [1, 2, 5, 5]),
            ("A", "AA", "A"): ([0, 0, 1], [1, 1, 2]),
        },
        {"A": 6, "B": 6},
        idtype=idtype,
        device=F.ctx(),
    )
2281
    assert g.is_multigraph == True
2282
2283
2284
2285
2286
2287
2288
2289
2290
    g = dgl.heterograph(
        {
            ("A", "AC", "C"): ([0, 0, 0, 1], [1, 1, 2, 5]),
            ("A", "AA", "A"): ([0, 1], [1, 2]),
        },
        {"A": 6, "C": 6},
        idtype=idtype,
        device=F.ctx(),
    )
2291
2292
    assert g.is_multigraph == True

2293
2294
2295

@parametrize_idtype
def test_graph_index_is_unibipartite(idtype):
2296
2297
2298
2299
2300
    g1 = dgl.heterograph(
        {("A", "AB", "B"): ([0, 0, 1], [1, 2, 5])},
        idtype=idtype,
        device=F.ctx(),
    )
2301
2302
2303
    assert g1._graph.is_metagraph_unibipartite()

    # more complicated bipartite
2304
2305
2306
2307
2308
2309
2310
2311
    g2 = dgl.heterograph(
        {
            ("A", "AB", "B"): ([0, 0, 1], [1, 2, 5]),
            ("A", "AC", "C"): ([1, 0], [0, 0]),
        },
        idtype=idtype,
        device=F.ctx(),
    )
2312
2313
    assert g2._graph.is_metagraph_unibipartite()

2314
2315
2316
2317
2318
2319
2320
2321
2322
    g3 = dgl.heterograph(
        {
            ("A", "AB", "B"): ([0, 0, 1], [1, 2, 5]),
            ("A", "AC", "C"): ([1, 0], [0, 0]),
            ("A", "AA", "A"): ([0, 1], [0, 1]),
        },
        idtype=idtype,
        device=F.ctx(),
    )
2323
2324
    assert not g3._graph.is_metagraph_unibipartite()

2325
2326
2327
2328
2329
2330
2331
2332
    g4 = dgl.heterograph(
        {
            ("A", "AB", "B"): ([0, 0, 1], [1, 2, 5]),
            ("C", "CA", "A"): ([1, 0], [0, 0]),
        },
        idtype=idtype,
        device=F.ctx(),
    )
2333
2334
2335
2336

    assert not g4._graph.is_metagraph_unibipartite()


nv-dlasalle's avatar
nv-dlasalle committed
2337
@parametrize_idtype
2338
def test_bipartite(idtype):
2339
2340
2341
2342
2343
    g1 = dgl.heterograph(
        {("A", "AB", "B"): ([0, 0, 1], [1, 2, 5])},
        idtype=idtype,
        device=F.ctx(),
    )
2344
2345
    assert g1.is_unibipartite
    assert len(g1.ntypes) == 2
2346
2347
2348
    assert g1.etypes == ["AB"]
    assert g1.srctypes == ["A"]
    assert g1.dsttypes == ["B"]
Hongzhi (Steve), Chen's avatar
Hongzhi (Steve), Chen committed
2349
2350
    assert g1.num_nodes("A") == 2
    assert g1.num_nodes("B") == 6
2351
    assert g1.number_of_src_nodes("A") == 2
2352
    assert g1.number_of_src_nodes() == 2
2353
    assert g1.number_of_dst_nodes("B") == 6
2354
    assert g1.number_of_dst_nodes() == 6
Hongzhi (Steve), Chen's avatar
Hongzhi (Steve), Chen committed
2355
    assert g1.num_edges() == 3
2356
2357
2358
2359
2360
2361
2362
2363
    g1.srcdata["h"] = F.randn((2, 5))
    assert F.array_equal(g1.srcnodes["A"].data["h"], g1.srcdata["h"])
    assert F.array_equal(g1.nodes["A"].data["h"], g1.srcdata["h"])
    assert F.array_equal(g1.nodes["SRC/A"].data["h"], g1.srcdata["h"])
    g1.dstdata["h"] = F.randn((6, 3))
    assert F.array_equal(g1.dstnodes["B"].data["h"], g1.dstdata["h"])
    assert F.array_equal(g1.nodes["B"].data["h"], g1.dstdata["h"])
    assert F.array_equal(g1.nodes["DST/B"].data["h"], g1.dstdata["h"])
2364
2365

    # more complicated bipartite
2366
2367
2368
2369
2370
2371
2372
2373
    g2 = dgl.heterograph(
        {
            ("A", "AB", "B"): ([0, 0, 1], [1, 2, 5]),
            ("A", "AC", "C"): ([1, 0], [0, 0]),
        },
        idtype=idtype,
        device=F.ctx(),
    )
2374
2375

    assert g2.is_unibipartite
2376
2377
    assert g2.srctypes == ["A"]
    assert set(g2.dsttypes) == {"B", "C"}
Hongzhi (Steve), Chen's avatar
Hongzhi (Steve), Chen committed
2378
2379
2380
    assert g2.num_nodes("A") == 2
    assert g2.num_nodes("B") == 6
    assert g2.num_nodes("C") == 1
2381
    assert g2.number_of_src_nodes("A") == 2
2382
    assert g2.number_of_src_nodes() == 2
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
    assert g2.number_of_dst_nodes("B") == 6
    assert g2.number_of_dst_nodes("C") == 1
    g2.srcdata["h"] = F.randn((2, 5))
    assert F.array_equal(g2.srcnodes["A"].data["h"], g2.srcdata["h"])
    assert F.array_equal(g2.nodes["A"].data["h"], g2.srcdata["h"])
    assert F.array_equal(g2.nodes["SRC/A"].data["h"], g2.srcdata["h"])

    g3 = dgl.heterograph(
        {
            ("A", "AB", "B"): ([0, 0, 1], [1, 2, 5]),
            ("A", "AC", "C"): ([1, 0], [0, 0]),
            ("A", "AA", "A"): ([0, 1], [0, 1]),
        },
        idtype=idtype,
        device=F.ctx(),
    )
2399
    assert not g3.is_unibipartite
2400

2401
2402
2403
2404
2405
2406
2407
2408
    g4 = dgl.heterograph(
        {
            ("A", "AB", "B"): ([0, 0, 1], [1, 2, 5]),
            ("C", "CA", "A"): ([1, 0], [0, 0]),
        },
        idtype=idtype,
        device=F.ctx(),
    )
2409
2410
2411

    assert not g4.is_unibipartite

2412

nv-dlasalle's avatar
nv-dlasalle committed
2413
@parametrize_idtype
2414
def test_dtype_cast(idtype):
2415
    g = dgl.graph(([0, 1, 0, 2], [0, 1, 1, 0]), idtype=idtype, device=F.ctx())
2416
    assert g.idtype == idtype
2417
2418
    g.ndata["feat"] = F.tensor([3, 4, 5])
    g.edata["h"] = F.tensor([3, 4, 5, 6])
2419
    if idtype == "int32":
2420
        g_cast = g.long()
2421
        assert g_cast.idtype == F.int64
2422
2423
    else:
        g_cast = g.int()
2424
        assert g_cast.idtype == F.int32
2425
    check_graph_equal(g, g_cast, check_idtype=False)
2426

2427

2428
2429
2430
def test_float_cast():
    for t in [F.float16, F.float32, F.float64]:
        idtype = F.int32
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
        g = dgl.heterograph(
            {
                ("user", "follows", "user"): (
                    F.tensor([0, 1, 1, 2, 2, 3], dtype=idtype),
                    F.tensor([0, 0, 1, 1, 2, 2], dtype=idtype),
                ),
                ("user", "plays", "game"): (
                    F.tensor([0, 1, 1], dtype=idtype),
                    F.tensor([0, 0, 1], dtype=idtype),
                ),
            },
            idtype=idtype,
            device=F.ctx(),
        )
2445
2446
2447
2448
2449
        uvalues = [1, 2, 3, 4]
        gvalues = [5, 6]
        fvalues = [7, 8, 9, 10, 11, 12]
        pvalues = [13, 14, 15]
        dataNamesTypes = [
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
            ("a", F.float16),
            ("b", F.float32),
            ("c", F.float64),
            ("d", F.int32),
            ("e", F.int64),
        ]
        for name, type in dataNamesTypes:
            g.nodes["user"].data[name] = F.copy_to(
                F.tensor(uvalues, dtype=type), ctx=F.ctx()
            )
        for name, type in dataNamesTypes:
            g.nodes["game"].data[name] = F.copy_to(
                F.tensor(gvalues, dtype=type), ctx=F.ctx()
            )
        for name, type in dataNamesTypes:
            g.edges["follows"].data[name] = F.copy_to(
                F.tensor(fvalues, dtype=type), ctx=F.ctx()
            )
        for name, type in dataNamesTypes:
            g.edges["plays"].data[name] = F.copy_to(
                F.tensor(pvalues, dtype=type), ctx=F.ctx()
            )
2472
2473
2474
2475
2476
2477
2478
2479

        if t == F.float16:
            g = dgl.transforms.functional.to_half(g)
        if t == F.float32:
            g = dgl.transforms.functional.to_float(g)
        if t == F.float64:
            g = dgl.transforms.functional.to_double(g)

2480
        for name, origType in dataNamesTypes:
2481
            # integer tensors shouldn't be converted
2482
2483
2484
2485
2486
            reqType = (
                t
                if (origType in [F.float16, F.float32, F.float64])
                else origType
            )
2487

2488
            values = g.nodes["user"].data[name]
2489
2490
2491
2492
            assert values.dtype == reqType
            assert len(values) == len(uvalues)
            assert F.allclose(values, F.tensor(uvalues), 0, 0)

2493
            values = g.nodes["game"].data[name]
2494
2495
2496
2497
            assert values.dtype == reqType
            assert len(values) == len(gvalues)
            assert F.allclose(values, F.tensor(gvalues), 0, 0)

2498
            values = g.edges["follows"].data[name]
2499
2500
2501
2502
            assert values.dtype == reqType
            assert len(values) == len(fvalues)
            assert F.allclose(values, F.tensor(fvalues), 0, 0)

2503
            values = g.edges["plays"].data[name]
2504
2505
2506
2507
            assert values.dtype == reqType
            assert len(values) == len(pvalues)
            assert F.allclose(values, F.tensor(pvalues), 0, 0)

2508

nv-dlasalle's avatar
nv-dlasalle committed
2509
@parametrize_idtype
2510
def test_format(idtype):
2511
    # single relation
2512
    g = dgl.graph(([0, 1, 0, 2], [0, 1, 1, 0]), idtype=idtype, device=F.ctx())
2513
2514
2515
    assert g.formats()["created"] == ["coo"]
    g1 = g.formats(["coo", "csr", "csc"])
    assert len(g1.formats()["created"]) + len(g1.formats()["not created"]) == 3
2516
    g1.create_formats_()
2517
2518
    assert len(g1.formats()["created"]) == 3
    assert g.formats()["created"] == ["coo"]
2519
2520

    # multiple relation
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
    g = dgl.heterograph(
        {
            ("user", "follows", "user"): ([0, 1], [1, 2]),
            ("user", "plays", "game"): ([0, 1, 1, 2], [0, 0, 1, 1]),
            ("developer", "develops", "game"): ([0, 1], [0, 1]),
        },
        idtype=idtype,
        device=F.ctx(),
    )
    user_feat = F.randn((g["follows"].number_of_src_nodes(), 5))
    g["follows"].srcdata["h"] = user_feat
    g1 = g.formats("csc")
2533
    # test frame
2534
    assert F.array_equal(g1["follows"].srcdata["h"], user_feat)
2535
    # test each relation graph
2536
2537
    assert g1.formats()["created"] == ["csc"]
    assert len(g1.formats()["not created"]) == 0
2538

2539
2540
2541
2542
2543
2544
    # in_degrees
    g = dgl.rand_graph(100, 2340).to(F.ctx())
    ind_arr = []
    for vid in range(0, 100):
        ind_arr.append(g.in_degrees(vid))
    in_degrees = g.in_degrees()
2545
    g = g.formats("coo")
2546
2547
2548
2549
    for vid in range(0, 100):
        assert g.in_degrees(vid) == ind_arr[vid]
    assert F.array_equal(in_degrees, g.in_degrees())

2550

nv-dlasalle's avatar
nv-dlasalle committed
2551
@parametrize_idtype
2552
def test_edges_order(idtype):
2553
    # (0, 2), (1, 2), (0, 1), (0, 1), (2, 1)
2554
2555
2556
2557
2558
    g = dgl.graph(
        (np.array([0, 1, 0, 0, 2]), np.array([2, 2, 1, 1, 1])),
        idtype=idtype,
        device=F.ctx(),
    )
2559

2560
    print(g.formats())
2561
    src, dst = g.all_edges(order="srcdst")
2562
2563
    assert F.array_equal(src, F.tensor([0, 0, 0, 1, 2], dtype=idtype))
    assert F.array_equal(dst, F.tensor([1, 1, 2, 2, 1], dtype=idtype))
2564

2565

nv-dlasalle's avatar
nv-dlasalle committed
2566
@parametrize_idtype
2567
def test_reverse(idtype):
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
    g = dgl.heterograph(
        {
            ("user", "follows", "user"): (
                [0, 1, 2, 4, 3, 1, 3],
                [1, 2, 3, 2, 0, 0, 1],
            )
        },
        idtype=idtype,
        device=F.ctx(),
    )
2578
    gidx = g._graph
2579
    r_gidx = gidx.reverse()
2580

Hongzhi (Steve), Chen's avatar
Hongzhi (Steve), Chen committed
2581
2582
    assert gidx.num_nodes(0) == r_gidx.num_nodes(0)
    assert gidx.num_edges(0) == r_gidx.num_edges(0)
2583
2584
    g_s, g_d, _ = gidx.edges(0)
    rg_s, rg_d, _ = r_gidx.edges(0)
2585
2586
    assert F.array_equal(g_s, rg_d)
    assert F.array_equal(g_d, rg_s)
2587
2588

    # force to start with 'csr'
2589
2590
    gidx = gidx.formats("csr")
    gidx = gidx.formats(["coo", "csr", "csc"])
2591
    r_gidx = gidx.reverse()
2592
2593
    assert "csr" in gidx.formats()["created"]
    assert "csc" in r_gidx.formats()["created"]
Hongzhi (Steve), Chen's avatar
Hongzhi (Steve), Chen committed
2594
2595
    assert gidx.num_nodes(0) == r_gidx.num_nodes(0)
    assert gidx.num_edges(0) == r_gidx.num_edges(0)
2596
2597
    g_s, g_d, _ = gidx.edges(0)
    rg_s, rg_d, _ = r_gidx.edges(0)
2598
2599
    assert F.array_equal(g_s, rg_d)
    assert F.array_equal(g_d, rg_s)
2600
2601

    # force to start with 'csc'
2602
2603
    gidx = gidx.formats("csc")
    gidx = gidx.formats(["coo", "csr", "csc"])
2604
    r_gidx = gidx.reverse()
2605
2606
    assert "csc" in gidx.formats()["created"]
    assert "csr" in r_gidx.formats()["created"]
Hongzhi (Steve), Chen's avatar
Hongzhi (Steve), Chen committed
2607
2608
    assert gidx.num_nodes(0) == r_gidx.num_nodes(0)
    assert gidx.num_edges(0) == r_gidx.num_edges(0)
2609
2610
    g_s, g_d, _ = gidx.edges(0)
    rg_s, rg_d, _ = r_gidx.edges(0)
2611
2612
    assert F.array_equal(g_s, rg_d)
    assert F.array_equal(g_d, rg_s)
2613

2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
    g = dgl.heterograph(
        {
            ("user", "follows", "user"): (
                [0, 1, 2, 4, 3, 1, 3],
                [1, 2, 3, 2, 0, 0, 1],
            ),
            ("user", "plays", "game"): (
                [0, 0, 2, 3, 3, 4, 1],
                [1, 0, 1, 0, 1, 0, 0],
            ),
            ("developer", "develops", "game"): ([0, 1, 1, 2], [0, 0, 1, 1]),
        },
        idtype=idtype,
        device=F.ctx(),
    )
2629
    gidx = g._graph
2630
2631
2632
2633
2634
2635
2636
2637
    r_gidx = gidx.reverse()

    # metagraph
    mg = gidx.metagraph
    r_mg = r_gidx.metagraph
    for etype in range(3):
        assert mg.find_edge(etype) == r_mg.find_edge(etype)[::-1]

2638
    # three node types and three edge types
Hongzhi (Steve), Chen's avatar
Hongzhi (Steve), Chen committed
2639
2640
2641
2642
2643
2644
    assert gidx.num_nodes(0) == r_gidx.num_nodes(0)
    assert gidx.num_nodes(1) == r_gidx.num_nodes(1)
    assert gidx.num_nodes(2) == r_gidx.num_nodes(2)
    assert gidx.num_edges(0) == r_gidx.num_edges(0)
    assert gidx.num_edges(1) == r_gidx.num_edges(1)
    assert gidx.num_edges(2) == r_gidx.num_edges(2)
2645
2646
    g_s, g_d, _ = gidx.edges(0)
    rg_s, rg_d, _ = r_gidx.edges(0)
2647
2648
    assert F.array_equal(g_s, rg_d)
    assert F.array_equal(g_d, rg_s)
2649
2650
    g_s, g_d, _ = gidx.edges(1)
    rg_s, rg_d, _ = r_gidx.edges(1)
2651
2652
    assert F.array_equal(g_s, rg_d)
    assert F.array_equal(g_d, rg_s)
2653
2654
    g_s, g_d, _ = gidx.edges(2)
    rg_s, rg_d, _ = r_gidx.edges(2)
2655
2656
    assert F.array_equal(g_s, rg_d)
    assert F.array_equal(g_d, rg_s)
2657
2658

    # force to start with 'csr'
2659
2660
    gidx = gidx.formats("csr")
    gidx = gidx.formats(["coo", "csr", "csc"])
2661
    r_gidx = gidx.reverse()
2662
    # three node types and three edge types
2663
2664
    assert "csr" in gidx.formats()["created"]
    assert "csc" in r_gidx.formats()["created"]
Hongzhi (Steve), Chen's avatar
Hongzhi (Steve), Chen committed
2665
2666
2667
2668
2669
2670
    assert gidx.num_nodes(0) == r_gidx.num_nodes(0)
    assert gidx.num_nodes(1) == r_gidx.num_nodes(1)
    assert gidx.num_nodes(2) == r_gidx.num_nodes(2)
    assert gidx.num_edges(0) == r_gidx.num_edges(0)
    assert gidx.num_edges(1) == r_gidx.num_edges(1)
    assert gidx.num_edges(2) == r_gidx.num_edges(2)
2671
2672
    g_s, g_d, _ = gidx.edges(0)
    rg_s, rg_d, _ = r_gidx.edges(0)
2673
2674
    assert F.array_equal(g_s, rg_d)
    assert F.array_equal(g_d, rg_s)
2675
2676
    g_s, g_d, _ = gidx.edges(1)
    rg_s, rg_d, _ = r_gidx.edges(1)
2677
2678
    assert F.array_equal(g_s, rg_d)
    assert F.array_equal(g_d, rg_s)
2679
2680
    g_s, g_d, _ = gidx.edges(2)
    rg_s, rg_d, _ = r_gidx.edges(2)
2681
2682
    assert F.array_equal(g_s, rg_d)
    assert F.array_equal(g_d, rg_s)
2683
2684

    # force to start with 'csc'
2685
2686
    gidx = gidx.formats("csc")
    gidx = gidx.formats(["coo", "csr", "csc"])
2687
    r_gidx = gidx.reverse()
2688
    # three node types and three edge types
2689
2690
    assert "csc" in gidx.formats()["created"]
    assert "csr" in r_gidx.formats()["created"]
Hongzhi (Steve), Chen's avatar
Hongzhi (Steve), Chen committed
2691
2692
2693
2694
2695
2696
    assert gidx.num_nodes(0) == r_gidx.num_nodes(0)
    assert gidx.num_nodes(1) == r_gidx.num_nodes(1)
    assert gidx.num_nodes(2) == r_gidx.num_nodes(2)
    assert gidx.num_edges(0) == r_gidx.num_edges(0)
    assert gidx.num_edges(1) == r_gidx.num_edges(1)
    assert gidx.num_edges(2) == r_gidx.num_edges(2)
2697
2698
    g_s, g_d, _ = gidx.edges(0)
    rg_s, rg_d, _ = r_gidx.edges(0)
2699
2700
    assert F.array_equal(g_s, rg_d)
    assert F.array_equal(g_d, rg_s)
2701
2702
    g_s, g_d, _ = gidx.edges(1)
    rg_s, rg_d, _ = r_gidx.edges(1)
2703
2704
    assert F.array_equal(g_s, rg_d)
    assert F.array_equal(g_d, rg_s)
2705
2706
    g_s, g_d, _ = gidx.edges(2)
    rg_s, rg_d, _ = r_gidx.edges(2)
2707
2708
2709
    assert F.array_equal(g_s, rg_d)
    assert F.array_equal(g_d, rg_s)

2710

nv-dlasalle's avatar
nv-dlasalle committed
2711
@parametrize_idtype
2712
2713
def test_clone(idtype):
    g = dgl.graph(([0, 1], [1, 2]), idtype=idtype, device=F.ctx())
2714
2715
    g.ndata["h"] = F.copy_to(F.tensor([1, 1, 1], dtype=idtype), ctx=F.ctx())
    g.edata["h"] = F.copy_to(F.tensor([1, 1], dtype=idtype), ctx=F.ctx())
2716
2717

    new_g = g.clone()
Hongzhi (Steve), Chen's avatar
Hongzhi (Steve), Chen committed
2718
2719
    assert g.num_nodes() == new_g.num_nodes()
    assert g.num_edges() == new_g.num_edges()
2720
2721
    assert g.device == new_g.device
    assert g.idtype == new_g.idtype
2722
2723
    assert F.array_equal(g.ndata["h"], new_g.ndata["h"])
    assert F.array_equal(g.edata["h"], new_g.edata["h"])
2724
    # data change
2725
2726
2727
2728
    new_g.ndata["h"] = F.copy_to(F.tensor([2, 2, 2], dtype=idtype), ctx=F.ctx())
    assert F.array_equal(g.ndata["h"], new_g.ndata["h"]) == False
    g.edata["h"] = F.copy_to(F.tensor([2, 2], dtype=idtype), ctx=F.ctx())
    assert F.array_equal(g.edata["h"], new_g.edata["h"]) == False
2729
2730
    # graph structure change
    g.add_nodes(1)
Hongzhi (Steve), Chen's avatar
Hongzhi (Steve), Chen committed
2731
    assert g.num_nodes() != new_g.num_nodes()
2732
    new_g.add_edges(1, 1)
Hongzhi (Steve), Chen's avatar
Hongzhi (Steve), Chen committed
2733
    assert g.num_edges() != new_g.num_edges()
2734
2735

    # zero data graph
2736
    g = dgl.graph(([], []), num_nodes=0, idtype=idtype, device=F.ctx())
2737
    new_g = g.clone()
Hongzhi (Steve), Chen's avatar
Hongzhi (Steve), Chen committed
2738
2739
    assert g.num_nodes() == new_g.num_nodes()
    assert g.num_edges() == new_g.num_edges()
2740
2741

    # heterograph
2742
    g = create_test_heterograph3(idtype)
2743
2744
2745
    g.edges["plays"].data["h"] = F.copy_to(
        F.tensor([1, 2, 3, 4], dtype=idtype), ctx=F.ctx()
    )
2746
    new_g = g.clone()
Hongzhi (Steve), Chen's avatar
Hongzhi (Steve), Chen committed
2747
2748
2749
2750
2751
    assert g.num_nodes("user") == new_g.num_nodes("user")
    assert g.num_nodes("game") == new_g.num_nodes("game")
    assert g.num_nodes("developer") == new_g.num_nodes("developer")
    assert g.num_edges("plays") == new_g.num_edges("plays")
    assert g.num_edges("develops") == new_g.num_edges("develops")
2752
2753
2754
2755
2756
2757
2758
2759
2760
    assert F.array_equal(
        g.nodes["user"].data["h"], new_g.nodes["user"].data["h"]
    )
    assert F.array_equal(
        g.nodes["game"].data["h"], new_g.nodes["game"].data["h"]
    )
    assert F.array_equal(
        g.edges["plays"].data["h"], new_g.edges["plays"].data["h"]
    )
2761
2762
    assert g.device == new_g.device
    assert g.idtype == new_g.idtype
2763
2764
    u, v = g.edges(form="uv", order="eid", etype="plays")
    nu, nv = new_g.edges(form="uv", order="eid", etype="plays")
2765
2766
2767
2768
2769
    assert F.array_equal(u, nu)
    assert F.array_equal(v, nv)
    # graph structure change
    u = F.tensor([0, 4], dtype=idtype)
    v = F.tensor([2, 6], dtype=idtype)
2770
2771
    g.add_edges(u, v, etype="plays")
    u, v = g.edges(form="uv", order="eid", etype="plays")
2772
2773
    assert u.shape[0] != nu.shape[0]
    assert v.shape[0] != nv.shape[0]
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
    assert (
        g.nodes["user"].data["h"].shape[0]
        != new_g.nodes["user"].data["h"].shape[0]
    )
    assert (
        g.nodes["game"].data["h"].shape[0]
        != new_g.nodes["game"].data["h"].shape[0]
    )
    assert (
        g.edges["plays"].data["h"].shape[0]
        != new_g.edges["plays"].data["h"].shape[0]
    )
2786
2787


nv-dlasalle's avatar
nv-dlasalle committed
2788
@parametrize_idtype
2789
2790
2791
2792
2793
2794
2795
def test_add_edges(idtype):
    # homogeneous graph
    g = dgl.graph(([0, 1], [1, 2]), idtype=idtype, device=F.ctx())
    u = 0
    v = 1
    g.add_edges(u, v)
    assert g.device == F.ctx()
Hongzhi (Steve), Chen's avatar
Hongzhi (Steve), Chen committed
2796
2797
    assert g.num_nodes() == 3
    assert g.num_edges() == 3
2798
2799
2800
2801
    u = [0]
    v = [1]
    g.add_edges(u, v)
    assert g.device == F.ctx()
Hongzhi (Steve), Chen's avatar
Hongzhi (Steve), Chen committed
2802
2803
    assert g.num_nodes() == 3
    assert g.num_edges() == 4
2804
2805
2806
2807
    u = F.tensor(u, dtype=idtype)
    v = F.tensor(v, dtype=idtype)
    g.add_edges(u, v)
    assert g.device == F.ctx()
Hongzhi (Steve), Chen's avatar
Hongzhi (Steve), Chen committed
2808
2809
    assert g.num_nodes() == 3
    assert g.num_edges() == 5
2810
    u, v = g.edges(form="uv", order="eid")
2811
2812
2813
2814
2815
2816
2817
2818
    assert F.array_equal(u, F.tensor([0, 1, 0, 0, 0], dtype=idtype))
    assert F.array_equal(v, F.tensor([1, 2, 1, 1, 1], dtype=idtype))

    # node id larger than current max node id
    g = dgl.graph(([0, 1], [1, 2]), idtype=idtype, device=F.ctx())
    u = F.tensor([0, 1], dtype=idtype)
    v = F.tensor([2, 3], dtype=idtype)
    g.add_edges(u, v)
Hongzhi (Steve), Chen's avatar
Hongzhi (Steve), Chen committed
2819
2820
    assert g.num_nodes() == 4
    assert g.num_edges() == 4
2821
    u, v = g.edges(form="uv", order="eid")
2822
2823
2824
2825
2826
    assert F.array_equal(u, F.tensor([0, 1, 0, 1], dtype=idtype))
    assert F.array_equal(v, F.tensor([1, 2, 2, 3], dtype=idtype))

    # has data
    g = dgl.graph(([0, 1], [1, 2]), idtype=idtype, device=F.ctx())
2827
2828
    g.ndata["h"] = F.copy_to(F.tensor([1, 1, 1], dtype=idtype), ctx=F.ctx())
    g.edata["h"] = F.copy_to(F.tensor([1, 1], dtype=idtype), ctx=F.ctx())
2829
2830
    u = F.tensor([0, 1], dtype=idtype)
    v = F.tensor([2, 3], dtype=idtype)
2831
2832
2833
2834
    e_feat = {
        "h": F.copy_to(F.tensor([2, 2], dtype=idtype), ctx=F.ctx()),
        "hh": F.copy_to(F.tensor([2, 2], dtype=idtype), ctx=F.ctx()),
    }
2835
    g.add_edges(u, v, e_feat)
Hongzhi (Steve), Chen's avatar
Hongzhi (Steve), Chen committed
2836
2837
    assert g.num_nodes() == 4
    assert g.num_edges() == 4
2838
    u, v = g.edges(form="uv", order="eid")
2839
2840
    assert F.array_equal(u, F.tensor([0, 1, 0, 1], dtype=idtype))
    assert F.array_equal(v, F.tensor([1, 2, 2, 3], dtype=idtype))
2841
2842
2843
    assert F.array_equal(g.ndata["h"], F.tensor([1, 1, 1, 0], dtype=idtype))
    assert F.array_equal(g.edata["h"], F.tensor([1, 1, 2, 2], dtype=idtype))
    assert F.array_equal(g.edata["hh"], F.tensor([0, 0, 2, 2], dtype=idtype))
2844
2845

    # zero data graph
2846
    g = dgl.graph(([], []), num_nodes=0, idtype=idtype, device=F.ctx())
2847
2848
    u = F.tensor([0, 1], dtype=idtype)
    v = F.tensor([2, 2], dtype=idtype)
2849
2850
2851
2852
    e_feat = {
        "h": F.copy_to(F.tensor([2, 2], dtype=idtype), ctx=F.ctx()),
        "hh": F.copy_to(F.tensor([2, 2], dtype=idtype), ctx=F.ctx()),
    }
2853
    g.add_edges(u, v, e_feat)
Hongzhi (Steve), Chen's avatar
Hongzhi (Steve), Chen committed
2854
2855
    assert g.num_nodes() == 3
    assert g.num_edges() == 2
2856
    u, v = g.edges(form="uv", order="eid")
2857
2858
    assert F.array_equal(u, F.tensor([0, 1], dtype=idtype))
    assert F.array_equal(v, F.tensor([2, 2], dtype=idtype))
2859
2860
    assert F.array_equal(g.edata["h"], F.tensor([2, 2], dtype=idtype))
    assert F.array_equal(g.edata["hh"], F.tensor([2, 2], dtype=idtype))
2861
2862

    # bipartite graph
2863
2864
2865
2866
2867
    g = dgl.heterograph(
        {("user", "plays", "game"): ([0, 1], [1, 2])},
        idtype=idtype,
        device=F.ctx(),
    )
2868
2869
2870
2871
    u = 0
    v = 1
    g.add_edges(u, v)
    assert g.device == F.ctx()
Hongzhi (Steve), Chen's avatar
Hongzhi (Steve), Chen committed
2872
2873
2874
    assert g.num_nodes("user") == 2
    assert g.num_nodes("game") == 3
    assert g.num_edges() == 3
2875
2876
2877
2878
    u = [0]
    v = [1]
    g.add_edges(u, v)
    assert g.device == F.ctx()
Hongzhi (Steve), Chen's avatar
Hongzhi (Steve), Chen committed
2879
2880
2881
    assert g.num_nodes("user") == 2
    assert g.num_nodes("game") == 3
    assert g.num_edges() == 4
2882
2883
2884
2885
    u = F.tensor(u, dtype=idtype)
    v = F.tensor(v, dtype=idtype)
    g.add_edges(u, v)
    assert g.device == F.ctx()
Hongzhi (Steve), Chen's avatar
Hongzhi (Steve), Chen committed
2886
2887
2888
    assert g.num_nodes("user") == 2
    assert g.num_nodes("game") == 3
    assert g.num_edges() == 5
2889
    u, v = g.edges(form="uv")
2890
2891
2892
2893
    assert F.array_equal(u, F.tensor([0, 1, 0, 0, 0], dtype=idtype))
    assert F.array_equal(v, F.tensor([1, 2, 1, 1, 1], dtype=idtype))

    # node id larger than current max node id
2894
2895
2896
2897
2898
    g = dgl.heterograph(
        {("user", "plays", "game"): ([0, 1], [1, 2])},
        idtype=idtype,
        device=F.ctx(),
    )
2899
2900
2901
2902
    u = F.tensor([0, 2], dtype=idtype)
    v = F.tensor([2, 3], dtype=idtype)
    g.add_edges(u, v)
    assert g.device == F.ctx()
Hongzhi (Steve), Chen's avatar
Hongzhi (Steve), Chen committed
2903
2904
2905
    assert g.num_nodes("user") == 3
    assert g.num_nodes("game") == 4
    assert g.num_edges() == 4
2906
    u, v = g.edges(form="uv", order="eid")
2907
2908
2909
2910
    assert F.array_equal(u, F.tensor([0, 1, 0, 2], dtype=idtype))
    assert F.array_equal(v, F.tensor([1, 2, 2, 3], dtype=idtype))

    # has data
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
    g = dgl.heterograph(
        {("user", "plays", "game"): ([0, 1], [1, 2])},
        idtype=idtype,
        device=F.ctx(),
    )
    g.nodes["user"].data["h"] = F.copy_to(
        F.tensor([1, 1], dtype=idtype), ctx=F.ctx()
    )
    g.nodes["game"].data["h"] = F.copy_to(
        F.tensor([2, 2, 2], dtype=idtype), ctx=F.ctx()
    )
    g.edata["h"] = F.copy_to(F.tensor([1, 1], dtype=idtype), ctx=F.ctx())
2923
2924
    u = F.tensor([0, 2], dtype=idtype)
    v = F.tensor([2, 3], dtype=idtype)
2925
2926
2927
2928
    e_feat = {
        "h": F.copy_to(F.tensor([2, 2], dtype=idtype), ctx=F.ctx()),
        "hh": F.copy_to(F.tensor([2, 2], dtype=idtype), ctx=F.ctx()),
    }
2929
    g.add_edges(u, v, e_feat)
Hongzhi (Steve), Chen's avatar
Hongzhi (Steve), Chen committed
2930
2931
2932
    assert g.num_nodes("user") == 3
    assert g.num_nodes("game") == 4
    assert g.num_edges() == 4
2933
    u, v = g.edges(form="uv", order="eid")
2934
2935
    assert F.array_equal(u, F.tensor([0, 1, 0, 2], dtype=idtype))
    assert F.array_equal(v, F.tensor([1, 2, 2, 3], dtype=idtype))
2936
2937
2938
2939
2940
2941
2942
2943
    assert F.array_equal(
        g.nodes["user"].data["h"], F.tensor([1, 1, 0], dtype=idtype)
    )
    assert F.array_equal(
        g.nodes["game"].data["h"], F.tensor([2, 2, 2, 0], dtype=idtype)
    )
    assert F.array_equal(g.edata["h"], F.tensor([1, 1, 2, 2], dtype=idtype))
    assert F.array_equal(g.edata["hh"], F.tensor([0, 0, 2, 2], dtype=idtype))
2944
2945

    # heterogeneous graph
2946
    g = create_test_heterograph3(idtype)
2947
2948
    u = F.tensor([0, 2], dtype=idtype)
    v = F.tensor([2, 3], dtype=idtype)
2949
    g.add_edges(u, v, etype="plays")
Hongzhi (Steve), Chen's avatar
Hongzhi (Steve), Chen committed
2950
2951
2952
2953
2954
    assert g.num_nodes("user") == 3
    assert g.num_nodes("game") == 4
    assert g.num_nodes("developer") == 2
    assert g.num_edges("plays") == 6
    assert g.num_edges("develops") == 2
2955
    u, v = g.edges(form="uv", order="eid", etype="plays")
2956
2957
    assert F.array_equal(u, F.tensor([0, 1, 1, 2, 0, 2], dtype=idtype))
    assert F.array_equal(v, F.tensor([0, 0, 1, 1, 2, 3], dtype=idtype))
2958
2959
2960
2961
2962
2963
2964
2965
2966
    assert F.array_equal(
        g.nodes["user"].data["h"], F.tensor([1, 1, 1], dtype=idtype)
    )
    assert F.array_equal(
        g.nodes["game"].data["h"], F.tensor([2, 2, 0, 0], dtype=idtype)
    )
    assert F.array_equal(
        g.edges["plays"].data["h"], F.tensor([1, 1, 1, 1, 0, 0], dtype=idtype)
    )
2967
2968

    # add with feature
2969
    e_feat = {"h": F.copy_to(F.tensor([2, 2], dtype=idtype), ctx=F.ctx())}
2970
2971
    u = F.tensor([0, 2], dtype=idtype)
    v = F.tensor([2, 3], dtype=idtype)
2972
2973
2974
2975
    g.nodes["game"].data["h"] = F.copy_to(
        F.tensor([2, 2, 1, 1], dtype=idtype), ctx=F.ctx()
    )
    g.add_edges(u, v, data=e_feat, etype="develops")
Hongzhi (Steve), Chen's avatar
Hongzhi (Steve), Chen committed
2976
2977
2978
2979
2980
    assert g.num_nodes("user") == 3
    assert g.num_nodes("game") == 4
    assert g.num_nodes("developer") == 3
    assert g.num_edges("plays") == 6
    assert g.num_edges("develops") == 4
2981
    u, v = g.edges(form="uv", order="eid", etype="develops")
2982
2983
    assert F.array_equal(u, F.tensor([0, 1, 0, 2], dtype=idtype))
    assert F.array_equal(v, F.tensor([0, 1, 2, 3], dtype=idtype))
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
    assert F.array_equal(
        g.nodes["developer"].data["h"], F.tensor([3, 3, 0], dtype=idtype)
    )
    assert F.array_equal(
        g.nodes["game"].data["h"], F.tensor([2, 2, 1, 1], dtype=idtype)
    )
    assert F.array_equal(
        g.edges["develops"].data["h"], F.tensor([0, 0, 2, 2], dtype=idtype)
    )

2994

nv-dlasalle's avatar
nv-dlasalle committed
2995
@parametrize_idtype
2996
2997
2998
def test_add_nodes(idtype):
    # homogeneous Graphs
    g = dgl.graph(([0, 1], [1, 2]), idtype=idtype, device=F.ctx())
2999
    g.ndata["h"] = F.copy_to(F.tensor([1, 1, 1], dtype=idtype), ctx=F.ctx())
3000
    g.add_nodes(1)
Hongzhi (Steve), Chen's avatar
Hongzhi (Steve), Chen committed
3001
    assert g.num_nodes() == 4
3002
    assert F.array_equal(g.ndata["h"], F.tensor([1, 1, 1, 0], dtype=idtype))
3003
3004

    # zero node graph
3005
    g = dgl.graph(([], []), num_nodes=3, idtype=idtype, device=F.ctx())
3006
3007
3008
3009
    g.ndata["h"] = F.copy_to(F.tensor([1, 1, 1], dtype=idtype), ctx=F.ctx())
    g.add_nodes(
        1, data={"h": F.copy_to(F.tensor([2], dtype=idtype), ctx=F.ctx())}
    )
Hongzhi (Steve), Chen's avatar
Hongzhi (Steve), Chen committed
3010
    assert g.num_nodes() == 4
3011
    assert F.array_equal(g.ndata["h"], F.tensor([1, 1, 1, 2], dtype=idtype))
3012
3013

    # bipartite graph
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
    g = dgl.heterograph(
        {("user", "plays", "game"): ([0, 1], [1, 2])},
        idtype=idtype,
        device=F.ctx(),
    )
    g.add_nodes(
        2,
        data={"h": F.copy_to(F.tensor([2, 2], dtype=idtype), ctx=F.ctx())},
        ntype="user",
    )
Hongzhi (Steve), Chen's avatar
Hongzhi (Steve), Chen committed
3024
    assert g.num_nodes("user") == 4
3025
3026
3027
3028
    assert F.array_equal(
        g.nodes["user"].data["h"], F.tensor([0, 0, 2, 2], dtype=idtype)
    )
    g.add_nodes(2, ntype="game")
Hongzhi (Steve), Chen's avatar
Hongzhi (Steve), Chen committed
3029
    assert g.num_nodes("game") == 5
3030
3031

    # heterogeneous graph
3032
    g = create_test_heterograph3(idtype)
3033
3034
3035
3036
3037
3038
3039
    g.add_nodes(1, ntype="user")
    g.add_nodes(
        2,
        data={"h": F.copy_to(F.tensor([2, 2], dtype=idtype), ctx=F.ctx())},
        ntype="game",
    )
    g.add_nodes(0, ntype="developer")
Hongzhi (Steve), Chen's avatar
Hongzhi (Steve), Chen committed
3040
3041
3042
    assert g.num_nodes("user") == 4
    assert g.num_nodes("game") == 4
    assert g.num_nodes("developer") == 2
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
    assert F.array_equal(
        g.nodes["user"].data["h"], F.tensor([1, 1, 1, 0], dtype=idtype)
    )
    assert F.array_equal(
        g.nodes["game"].data["h"], F.tensor([2, 2, 2, 2], dtype=idtype)
    )


@unittest.skipIf(
    dgl.backend.backend_name == "mxnet",
    reason="MXNet has error with (0,) shape tensor.",
)
nv-dlasalle's avatar
nv-dlasalle committed
3055
@parametrize_idtype
3056
3057
3058
3059
3060
def test_remove_edges(idtype):
    # homogeneous Graphs
    g = dgl.graph(([0, 1], [1, 2]), idtype=idtype, device=F.ctx())
    e = 0
    g.remove_edges(e)
Hongzhi (Steve), Chen's avatar
Hongzhi (Steve), Chen committed
3061
    assert g.num_edges() == 1
3062
    u, v = g.edges(form="uv", order="eid")
3063
3064
3065
3066
3067
    assert F.array_equal(u, F.tensor([1], dtype=idtype))
    assert F.array_equal(v, F.tensor([2], dtype=idtype))
    g = dgl.graph(([0, 1], [1, 2]), idtype=idtype, device=F.ctx())
    e = [0]
    g.remove_edges(e)
Hongzhi (Steve), Chen's avatar
Hongzhi (Steve), Chen committed
3068
    assert g.num_edges() == 1
3069
    u, v = g.edges(form="uv", order="eid")
3070
3071
3072
3073
    assert F.array_equal(u, F.tensor([1], dtype=idtype))
    assert F.array_equal(v, F.tensor([2], dtype=idtype))
    e = F.tensor([0], dtype=idtype)
    g.remove_edges(e)
Hongzhi (Steve), Chen's avatar
Hongzhi (Steve), Chen committed
3074
    assert g.num_edges() == 0
3075
3076
3077

    # has node data
    g = dgl.graph(([0, 1], [1, 2]), idtype=idtype, device=F.ctx())
3078
    g.ndata["h"] = F.copy_to(F.tensor([1, 2, 3], dtype=idtype), ctx=F.ctx())
3079
    g.remove_edges(1)
Hongzhi (Steve), Chen's avatar
Hongzhi (Steve), Chen committed
3080
    assert g.num_edges() == 1
3081
    assert F.array_equal(g.ndata["h"], F.tensor([1, 2, 3], dtype=idtype))
3082
3083
3084

    # has edge data
    g = dgl.graph(([0, 1], [1, 2]), idtype=idtype, device=F.ctx())
3085
    g.edata["h"] = F.copy_to(F.tensor([1, 2], dtype=idtype), ctx=F.ctx())
3086
    g.remove_edges(0)
Hongzhi (Steve), Chen's avatar
Hongzhi (Steve), Chen committed
3087
    assert g.num_edges() == 1
3088
    assert F.array_equal(g.edata["h"], F.tensor([2], dtype=idtype))
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098

    # invalid eid
    assert_fail = False
    try:
        g.remove_edges(1)
    except:
        assert_fail = True
    assert assert_fail

    # bipartite graph
3099
3100
3101
3102
3103
    g = dgl.heterograph(
        {("user", "plays", "game"): ([0, 1], [1, 2])},
        idtype=idtype,
        device=F.ctx(),
    )
3104
3105
    e = 0
    g.remove_edges(e)
Hongzhi (Steve), Chen's avatar
Hongzhi (Steve), Chen committed
3106
    assert g.num_edges() == 1
3107
    u, v = g.edges(form="uv", order="eid")
3108
3109
    assert F.array_equal(u, F.tensor([1], dtype=idtype))
    assert F.array_equal(v, F.tensor([2], dtype=idtype))
3110
    g = dgl.heterograph(
3111
3112
3113
3114
        {("user", "plays", "game"): ([0, 1], [1, 2])},
        idtype=idtype,
        device=F.ctx(),
    )
3115
3116
    e = [0]
    g.remove_edges(e)
Hongzhi (Steve), Chen's avatar
Hongzhi (Steve), Chen committed
3117
    assert g.num_edges() == 1
3118
    u, v = g.edges(form="uv", order="eid")
3119
3120
3121
3122
    assert F.array_equal(u, F.tensor([1], dtype=idtype))
    assert F.array_equal(v, F.tensor([2], dtype=idtype))
    e = F.tensor([0], dtype=idtype)
    g.remove_edges(e)
Hongzhi (Steve), Chen's avatar
Hongzhi (Steve), Chen committed
3123
    assert g.num_edges() == 0
3124
3125

    # has data
3126
    g = dgl.heterograph(
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
        {("user", "plays", "game"): ([0, 1], [1, 2])},
        idtype=idtype,
        device=F.ctx(),
    )
    g.nodes["user"].data["h"] = F.copy_to(
        F.tensor([1, 1], dtype=idtype), ctx=F.ctx()
    )
    g.nodes["game"].data["h"] = F.copy_to(
        F.tensor([2, 2, 2], dtype=idtype), ctx=F.ctx()
    )
    g.edata["h"] = F.copy_to(F.tensor([1, 2], dtype=idtype), ctx=F.ctx())
3138
    g.remove_edges(1)
Hongzhi (Steve), Chen's avatar
Hongzhi (Steve), Chen committed
3139
    assert g.num_edges() == 1
3140
3141
3142
3143
3144
3145
3146
    assert F.array_equal(
        g.nodes["user"].data["h"], F.tensor([1, 1], dtype=idtype)
    )
    assert F.array_equal(
        g.nodes["game"].data["h"], F.tensor([2, 2, 2], dtype=idtype)
    )
    assert F.array_equal(g.edata["h"], F.tensor([1], dtype=idtype))
3147
3148

    # heterogeneous graph
3149
    g = create_test_heterograph3(idtype)
3150
3151
3152
3153
    g.edges["plays"].data["h"] = F.copy_to(
        F.tensor([1, 2, 3, 4], dtype=idtype), ctx=F.ctx()
    )
    g.remove_edges(1, etype="plays")
Hongzhi (Steve), Chen's avatar
Hongzhi (Steve), Chen committed
3154
    assert g.num_edges("plays") == 3
3155
    u, v = g.edges(form="uv", order="eid", etype="plays")
3156
3157
    assert F.array_equal(u, F.tensor([0, 1, 2], dtype=idtype))
    assert F.array_equal(v, F.tensor([0, 1, 1], dtype=idtype))
3158
3159
3160
    assert F.array_equal(
        g.edges["plays"].data["h"], F.tensor([1, 3, 4], dtype=idtype)
    )
3161
    # remove all edges of 'develops'
3162
    g.remove_edges([0, 1], etype="develops")
Hongzhi (Steve), Chen's avatar
Hongzhi (Steve), Chen committed
3163
    assert g.num_edges("develops") == 0
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
    assert F.array_equal(
        g.nodes["user"].data["h"], F.tensor([1, 1, 1], dtype=idtype)
    )
    assert F.array_equal(
        g.nodes["game"].data["h"], F.tensor([2, 2], dtype=idtype)
    )
    assert F.array_equal(
        g.nodes["developer"].data["h"], F.tensor([3, 3], dtype=idtype)
    )

3174

nv-dlasalle's avatar
nv-dlasalle committed
3175
@parametrize_idtype
3176
3177
3178
3179
3180
def test_remove_nodes(idtype):
    # homogeneous Graphs
    g = dgl.graph(([0, 1], [1, 2]), idtype=idtype, device=F.ctx())
    n = 0
    g.remove_nodes(n)
Hongzhi (Steve), Chen's avatar
Hongzhi (Steve), Chen committed
3181
3182
    assert g.num_nodes() == 2
    assert g.num_edges() == 1
3183
    u, v = g.edges(form="uv", order="eid")
3184
3185
3186
3187
3188
    assert F.array_equal(u, F.tensor([0], dtype=idtype))
    assert F.array_equal(v, F.tensor([1], dtype=idtype))
    g = dgl.graph(([0, 1], [1, 2]), idtype=idtype, device=F.ctx())
    n = [1]
    g.remove_nodes(n)
Hongzhi (Steve), Chen's avatar
Hongzhi (Steve), Chen committed
3189
3190
    assert g.num_nodes() == 2
    assert g.num_edges() == 0
3191
3192
3193
    g = dgl.graph(([0, 1], [1, 2]), idtype=idtype, device=F.ctx())
    n = F.tensor([2], dtype=idtype)
    g.remove_nodes(n)
Hongzhi (Steve), Chen's avatar
Hongzhi (Steve), Chen committed
3194
3195
    assert g.num_nodes() == 2
    assert g.num_edges() == 1
3196
    u, v = g.edges(form="uv", order="eid")
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
    assert F.array_equal(u, F.tensor([0], dtype=idtype))
    assert F.array_equal(v, F.tensor([1], dtype=idtype))

    # invalid nid
    assert_fail = False
    try:
        g.remove_nodes(3)
    except:
        assert_fail = True
    assert assert_fail

    # has node and edge data
    g = dgl.graph(([0, 0, 2], [0, 1, 2]), idtype=idtype, device=F.ctx())
3210
3211
    g.ndata["hv"] = F.copy_to(F.tensor([1, 2, 3], dtype=idtype), ctx=F.ctx())
    g.edata["he"] = F.copy_to(F.tensor([1, 2, 3], dtype=idtype), ctx=F.ctx())
3212
    g.remove_nodes(F.tensor([0], dtype=idtype))
Hongzhi (Steve), Chen's avatar
Hongzhi (Steve), Chen committed
3213
3214
    assert g.num_nodes() == 2
    assert g.num_edges() == 1
3215
    u, v = g.edges(form="uv", order="eid")
3216
3217
    assert F.array_equal(u, F.tensor([1], dtype=idtype))
    assert F.array_equal(v, F.tensor([1], dtype=idtype))
3218
3219
    assert F.array_equal(g.ndata["hv"], F.tensor([2, 3], dtype=idtype))
    assert F.array_equal(g.edata["he"], F.tensor([3], dtype=idtype))
3220
3221

    # node id larger than current max node id
3222
    g = dgl.heterograph(
3223
3224
3225
3226
        {("user", "plays", "game"): ([0, 1], [1, 2])},
        idtype=idtype,
        device=F.ctx(),
    )
3227
    n = 0
3228
    g.remove_nodes(n, ntype="user")
Hongzhi (Steve), Chen's avatar
Hongzhi (Steve), Chen committed
3229
3230
3231
    assert g.num_nodes("user") == 1
    assert g.num_nodes("game") == 3
    assert g.num_edges() == 1
3232
    u, v = g.edges(form="uv", order="eid")
3233
3234
    assert F.array_equal(u, F.tensor([0], dtype=idtype))
    assert F.array_equal(v, F.tensor([2], dtype=idtype))
3235
    g = dgl.heterograph(
3236
3237
3238
3239
        {("user", "plays", "game"): ([0, 1], [1, 2])},
        idtype=idtype,
        device=F.ctx(),
    )
3240
    n = [1]
3241
    g.remove_nodes(n, ntype="user")
Hongzhi (Steve), Chen's avatar
Hongzhi (Steve), Chen committed
3242
3243
3244
    assert g.num_nodes("user") == 1
    assert g.num_nodes("game") == 3
    assert g.num_edges() == 1
3245
    u, v = g.edges(form="uv", order="eid")
3246
3247
    assert F.array_equal(u, F.tensor([0], dtype=idtype))
    assert F.array_equal(v, F.tensor([1], dtype=idtype))
3248
    g = dgl.heterograph(
3249
3250
3251
3252
        {("user", "plays", "game"): ([0, 1], [1, 2])},
        idtype=idtype,
        device=F.ctx(),
    )
3253
    n = F.tensor([0], dtype=idtype)
3254
    g.remove_nodes(n, ntype="game")
Hongzhi (Steve), Chen's avatar
Hongzhi (Steve), Chen committed
3255
3256
3257
    assert g.num_nodes("user") == 2
    assert g.num_nodes("game") == 2
    assert g.num_edges() == 2
3258
    u, v = g.edges(form="uv", order="eid")
3259
    assert F.array_equal(u, F.tensor([0, 1], dtype=idtype))
3260
    assert F.array_equal(v, F.tensor([0, 1], dtype=idtype))
3261
3262

    # heterogeneous graph
3263
    g = create_test_heterograph3(idtype)
3264
3265
3266
3267
    g.edges["plays"].data["h"] = F.copy_to(
        F.tensor([1, 2, 3, 4], dtype=idtype), ctx=F.ctx()
    )
    g.remove_nodes(0, ntype="game")
Hongzhi (Steve), Chen's avatar
Hongzhi (Steve), Chen committed
3268
3269
3270
3271
3272
    assert g.num_nodes("user") == 3
    assert g.num_nodes("game") == 1
    assert g.num_nodes("developer") == 2
    assert g.num_edges("plays") == 2
    assert g.num_edges("develops") == 1
3273
3274
3275
3276
3277
3278
3279
3280
    assert F.array_equal(
        g.nodes["user"].data["h"], F.tensor([1, 1, 1], dtype=idtype)
    )
    assert F.array_equal(g.nodes["game"].data["h"], F.tensor([2], dtype=idtype))
    assert F.array_equal(
        g.nodes["developer"].data["h"], F.tensor([3, 3], dtype=idtype)
    )
    u, v = g.edges(form="uv", order="eid", etype="plays")
3281
3282
    assert F.array_equal(u, F.tensor([1, 2], dtype=idtype))
    assert F.array_equal(v, F.tensor([0, 0], dtype=idtype))
3283
3284
3285
3286
    assert F.array_equal(
        g.edges["plays"].data["h"], F.tensor([3, 4], dtype=idtype)
    )
    u, v = g.edges(form="uv", order="eid", etype="develops")
3287
3288
    assert F.array_equal(u, F.tensor([1], dtype=idtype))
    assert F.array_equal(v, F.tensor([0], dtype=idtype))
3289

3290

nv-dlasalle's avatar
nv-dlasalle committed
3291
@parametrize_idtype
3292
3293
def test_frame(idtype):
    g = dgl.graph(([0, 1, 2], [1, 2, 3]), idtype=idtype, device=F.ctx())
3294
3295
    g.ndata["h"] = F.copy_to(F.tensor([0, 1, 2, 3], dtype=idtype), ctx=F.ctx())
    g.edata["h"] = F.copy_to(F.tensor([0, 1, 2], dtype=idtype), ctx=F.ctx())
3296
3297
3298
3299

    # remove nodes
    sg = dgl.remove_nodes(g, [3])
    # check for lazy update
3300
3301
3302
3303
    assert F.array_equal(sg._node_frames[0]._columns["h"].storage, g.ndata["h"])
    assert F.array_equal(sg._edge_frames[0]._columns["h"].storage, g.edata["h"])
    assert sg.ndata["h"].shape[0] == 3
    assert sg.edata["h"].shape[0] == 2
3304
    # update after read
3305
3306
3307
3308
3309
3310
3311
    assert F.array_equal(
        sg._node_frames[0]._columns["h"].storage,
        F.tensor([0, 1, 2], dtype=idtype),
    )
    assert F.array_equal(
        sg._edge_frames[0]._columns["h"].storage, F.tensor([0, 1], dtype=idtype)
    )
3312
3313

    ng = dgl.add_nodes(sg, 1)
3314
3315
3316
3317
3318
    assert ng.ndata["h"].shape[0] == 4
    assert F.array_equal(
        ng._node_frames[0]._columns["h"].storage,
        F.tensor([0, 1, 2, 0], dtype=idtype),
    )
3319
    ng = dgl.add_edges(ng, [3], [1])
3320
3321
3322
3323
3324
    assert ng.edata["h"].shape[0] == 3
    assert F.array_equal(
        ng._edge_frames[0]._columns["h"].storage,
        F.tensor([0, 1, 0], dtype=idtype),
    )
3325
3326
3327

    # multi level lazy update
    sg = dgl.remove_nodes(g, [3])
3328
3329
    assert F.array_equal(sg._node_frames[0]._columns["h"].storage, g.ndata["h"])
    assert F.array_equal(sg._edge_frames[0]._columns["h"].storage, g.edata["h"])
3330
    ssg = dgl.remove_nodes(sg, [1])
3331
3332
3333
3334
3335
3336
    assert F.array_equal(
        ssg._node_frames[0]._columns["h"].storage, g.ndata["h"]
    )
    assert F.array_equal(
        ssg._edge_frames[0]._columns["h"].storage, g.edata["h"]
    )
3337
    # ssg is changed
3338
3339
3340
3341
3342
3343
    assert ssg.ndata["h"].shape[0] == 2
    assert ssg.edata["h"].shape[0] == 0
    assert F.array_equal(
        ssg._node_frames[0]._columns["h"].storage,
        F.tensor([0, 2], dtype=idtype),
    )
3344
    # sg still in lazy model
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
    assert F.array_equal(sg._node_frames[0]._columns["h"].storage, g.ndata["h"])
    assert F.array_equal(sg._edge_frames[0]._columns["h"].storage, g.edata["h"])


@unittest.skipIf(
    dgl.backend.backend_name == "tensorflow",
    reason="TensorFlow always create a new tensor",
)
@unittest.skipIf(
    F._default_context_str == "cpu",
    reason="cpu do not have context change problem",
)
nv-dlasalle's avatar
nv-dlasalle committed
3357
@parametrize_idtype
3358
def test_frame_device(idtype):
3359
3360
3361
3362
    g = dgl.graph(([0, 1, 2], [2, 3, 1]))
    g.ndata["h"] = F.copy_to(F.tensor([1, 1, 1, 2], dtype=idtype), ctx=F.cpu())
    g.ndata["hh"] = F.copy_to(F.ones((4, 3), dtype=idtype), ctx=F.cpu())
    g.edata["h"] = F.copy_to(F.tensor([1, 2, 3], dtype=idtype), ctx=F.cpu())
3363
3364
3365

    g = g.to(F.ctx())
    # lazy device copy
3366
3367
3368
3369
3370
3371
    assert F.context(g._node_frames[0]._columns["h"].storage) == F.cpu()
    assert F.context(g._node_frames[0]._columns["hh"].storage) == F.cpu()
    print(g.ndata["h"])
    assert F.context(g._node_frames[0]._columns["h"].storage) == F.ctx()
    assert F.context(g._node_frames[0]._columns["hh"].storage) == F.cpu()
    assert F.context(g._edge_frames[0]._columns["h"].storage) == F.cpu()
3372
3373

    # lazy device copy in subgraph
3374
3375
3376
3377
3378
3379
3380
    sg = dgl.node_subgraph(g, [0, 1, 2])
    assert F.context(sg._node_frames[0]._columns["h"].storage) == F.ctx()
    assert F.context(sg._node_frames[0]._columns["hh"].storage) == F.cpu()
    assert F.context(sg._edge_frames[0]._columns["h"].storage) == F.cpu()
    print(sg.ndata["hh"])
    assert F.context(sg._node_frames[0]._columns["hh"].storage) == F.ctx()
    assert F.context(sg._edge_frames[0]._columns["h"].storage) == F.cpu()
3381
3382
3383

    # back to cpu
    sg = sg.to(F.cpu())
3384
3385
3386
3387
3388
3389
3390
3391
3392
    assert F.context(sg._node_frames[0]._columns["h"].storage) == F.ctx()
    assert F.context(sg._node_frames[0]._columns["hh"].storage) == F.ctx()
    assert F.context(sg._edge_frames[0]._columns["h"].storage) == F.cpu()
    print(sg.ndata["h"])
    print(sg.ndata["hh"])
    print(sg.edata["h"])
    assert F.context(sg._node_frames[0]._columns["h"].storage) == F.cpu()
    assert F.context(sg._node_frames[0]._columns["hh"].storage) == F.cpu()
    assert F.context(sg._edge_frames[0]._columns["h"].storage) == F.cpu()
3393
3394
3395

    # set some field
    sg = sg.to(F.ctx())
3396
3397
3398
3399
3400
    assert F.context(sg._node_frames[0]._columns["h"].storage) == F.cpu()
    sg.ndata["h"][0] = 5
    assert F.context(sg._node_frames[0]._columns["h"].storage) == F.ctx()
    assert F.context(sg._node_frames[0]._columns["hh"].storage) == F.cpu()
    assert F.context(sg._edge_frames[0]._columns["h"].storage) == F.cpu()
3401
3402
3403

    # add nodes
    ng = dgl.add_nodes(sg, 3)
3404
3405
3406
3407
    assert F.context(ng._node_frames[0]._columns["h"].storage) == F.ctx()
    assert F.context(ng._node_frames[0]._columns["hh"].storage) == F.ctx()
    assert F.context(ng._edge_frames[0]._columns["h"].storage) == F.cpu()

3408

nv-dlasalle's avatar
nv-dlasalle committed
3409
@parametrize_idtype
3410
def test_create_block(idtype):
3411
3412
3413
    block = dgl.create_block(
        ([0, 1, 2], [1, 2, 3]), idtype=idtype, device=F.ctx()
    )
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
    assert block.num_src_nodes() == 3
    assert block.num_dst_nodes() == 4
    assert block.num_edges() == 3

    block = dgl.create_block(([], []), idtype=idtype, device=F.ctx())
    assert block.num_src_nodes() == 0
    assert block.num_dst_nodes() == 0
    assert block.num_edges() == 0

    block = dgl.create_block(([], []), 3, 4, idtype=idtype, device=F.ctx())
    assert block.num_src_nodes() == 3
    assert block.num_dst_nodes() == 4
    assert block.num_edges() == 0

3428
3429
3430
    block = dgl.create_block(
        ([0, 1, 2], [1, 2, 3]), 4, 5, idtype=idtype, device=F.ctx()
    )
3431
3432
3433
3434
3435
3436
3437
    assert block.num_src_nodes() == 4
    assert block.num_dst_nodes() == 5
    assert block.num_edges() == 3

    sx = F.randn((4, 5))
    dx = F.randn((5, 6))
    ex = F.randn((3, 4))
3438
3439
3440
    block.srcdata["x"] = sx
    block.dstdata["x"] = dx
    block.edata["x"] = ex
3441
3442
3443
3444
3445

    g = dgl.block_to_graph(block)
    assert g.num_src_nodes() == 4
    assert g.num_dst_nodes() == 5
    assert g.num_edges() == 3
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
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
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
    assert g.srcdata["x"] is sx
    assert g.dstdata["x"] is dx
    assert g.edata["x"] is ex

    block = dgl.create_block(
        {
            ("A", "AB", "B"): ([1, 2, 3], [2, 1, 0]),
            ("B", "BA", "A"): ([2, 3], [3, 4]),
        },
        idtype=idtype,
        device=F.ctx(),
    )
    assert block.num_src_nodes("A") == 4
    assert block.num_src_nodes("B") == 4
    assert block.num_dst_nodes("B") == 3
    assert block.num_dst_nodes("A") == 5
    assert block.num_edges("AB") == 3
    assert block.num_edges("BA") == 2

    block = dgl.create_block(
        {("A", "AB", "B"): ([], []), ("B", "BA", "A"): ([], [])},
        idtype=idtype,
        device=F.ctx(),
    )
    assert block.num_src_nodes("A") == 0
    assert block.num_src_nodes("B") == 0
    assert block.num_dst_nodes("B") == 0
    assert block.num_dst_nodes("A") == 0
    assert block.num_edges("AB") == 0
    assert block.num_edges("BA") == 0

    block = dgl.create_block(
        {("A", "AB", "B"): ([], []), ("B", "BA", "A"): ([], [])},
        num_src_nodes={"A": 5, "B": 5},
        num_dst_nodes={"A": 6, "B": 4},
        idtype=idtype,
        device=F.ctx(),
    )
    assert block.num_src_nodes("A") == 5
    assert block.num_src_nodes("B") == 5
    assert block.num_dst_nodes("B") == 4
    assert block.num_dst_nodes("A") == 6
    assert block.num_edges("AB") == 0
    assert block.num_edges("BA") == 0

    block = dgl.create_block(
        {
            ("A", "AB", "B"): ([1, 2, 3], [2, 1, 0]),
            ("B", "BA", "A"): ([2, 3], [3, 4]),
        },
        num_src_nodes={"A": 5, "B": 5},
        num_dst_nodes={"A": 6, "B": 4},
        idtype=idtype,
        device=F.ctx(),
    )
    assert block.num_src_nodes("A") == 5
    assert block.num_src_nodes("B") == 5
    assert block.num_dst_nodes("B") == 4
    assert block.num_dst_nodes("A") == 6
    assert block.num_edges(("A", "AB", "B")) == 3
    assert block.num_edges(("B", "BA", "A")) == 2
3507
3508
3509
3510
3511
3512
3513

    sax = F.randn((5, 3))
    sbx = F.randn((5, 4))
    dax = F.randn((6, 5))
    dbx = F.randn((4, 6))
    eabx = F.randn((3, 7))
    ebax = F.randn((2, 8))
3514
3515
3516
3517
3518
3519
    block.srcnodes["A"].data["x"] = sax
    block.srcnodes["B"].data["x"] = sbx
    block.dstnodes["A"].data["x"] = dax
    block.dstnodes["B"].data["x"] = dbx
    block.edges["AB"].data["x"] = eabx
    block.edges["BA"].data["x"] = ebax
3520
3521

    hg = dgl.block_to_graph(block)
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
    assert hg.num_nodes("A_src") == 5
    assert hg.num_nodes("B_src") == 5
    assert hg.num_nodes("A_dst") == 6
    assert hg.num_nodes("B_dst") == 4
    assert hg.num_edges(("A_src", "AB", "B_dst")) == 3
    assert hg.num_edges(("B_src", "BA", "A_dst")) == 2
    assert hg.nodes["A_src"].data["x"] is sax
    assert hg.nodes["B_src"].data["x"] is sbx
    assert hg.nodes["A_dst"].data["x"] is dax
    assert hg.nodes["B_dst"].data["x"] is dbx
    assert hg.edges["AB"].data["x"] is eabx
    assert hg.edges["BA"].data["x"] is ebax

3535

nv-dlasalle's avatar
nv-dlasalle committed
3536
@parametrize_idtype
3537
@pytest.mark.parametrize("fmt", ["coo", "csr", "csc"])
3538
def test_adj_sparse(idtype, fmt):
3539
    if fmt == "coo":
3540
3541
3542
3543
3544
        A = ssp.random(10, 10, 0.2).tocoo()
        A.data = np.arange(20)
        row = F.tensor(A.row, idtype)
        col = F.tensor(A.col, idtype)
        g = dgl.graph((row, col))
3545
    elif fmt == "csr":
3546
3547
3548
3549
        A = ssp.random(10, 10, 0.2).tocsr()
        A.data = np.arange(20)
        indptr = F.tensor(A.indptr, idtype)
        indices = F.tensor(A.indices, idtype)
3550
        g = dgl.graph(("csr", (indptr, indices, [])))
3551
        with pytest.raises(DGLError):
3552
3553
            g2 = dgl.graph(("csr", (indptr[:-1], indices, [])), num_nodes=10)
    elif fmt == "csc":
3554
3555
3556
3557
        A = ssp.random(10, 10, 0.2).tocsc()
        A.data = np.arange(20)
        indptr = F.tensor(A.indptr, idtype)
        indices = F.tensor(A.indices, idtype)
3558
        g = dgl.graph(("csc", (indptr, indices, [])))
3559
        with pytest.raises(DGLError):
3560
            g2 = dgl.graph(("csr", (indptr[:-1], indices, [])), num_nodes=10)
3561
3562
3563
3564

    A_coo = A.tocoo()
    A_csr = A.tocsr()
    A_csc = A.tocsc()
3565
    row, col = g.adj_sparse("coo")
3566
3567
3568
    assert np.array_equal(F.asnumpy(row), A_coo.row)
    assert np.array_equal(F.asnumpy(col), A_coo.col)

3569
    indptr, indices, eids = g.adj_sparse("csr")
3570
    assert np.array_equal(F.asnumpy(indptr), A_csr.indptr)
3571
    if fmt == "csr":
3572
3573
3574
3575
3576
3577
3578
3579
3580
        assert len(eids) == 0
        assert np.array_equal(F.asnumpy(indices), A_csr.indices)
    else:
        indices_sorted = F.zeros(len(indices), idtype)
        indices_sorted = F.scatter_row(indices_sorted, eids, indices)
        indices_sorted_np = np.zeros(len(indices), dtype=A_csr.indices.dtype)
        indices_sorted_np[A_csr.data] = A_csr.indices
        assert np.array_equal(F.asnumpy(indices_sorted), indices_sorted_np)

3581
    indptr, indices, eids = g.adj_sparse("csc")
3582
    assert np.array_equal(F.asnumpy(indptr), A_csc.indptr)
3583
    if fmt == "csc":
3584
3585
3586
3587
3588
3589
3590
3591
3592
        assert len(eids) == 0
        assert np.array_equal(F.asnumpy(indices), A_csc.indices)
    else:
        indices_sorted = F.zeros(len(indices), idtype)
        indices_sorted = F.scatter_row(indices_sorted, eids, indices)
        indices_sorted_np = np.zeros(len(indices), dtype=A_csc.indices.dtype)
        indices_sorted_np[A_csc.data] = A_csc.indices
        assert np.array_equal(F.asnumpy(indices_sorted), indices_sorted_np)

3593

3594
3595
3596
def _test_forking_pickler_entry(g, q):
    q.put(g.formats())

3597
3598
3599
3600

@unittest.skipIf(
    dgl.backend.backend_name == "mxnet", reason="MXNet doesn't support spawning"
)
3601
def test_forking_pickler():
3602
3603
    ctx = mp.get_context("spawn")
    g = dgl.graph(([0, 1, 2], [1, 2, 3]))
3604
3605
3606
3607
    g.create_formats_()
    q = ctx.Queue(1)
    proc = ctx.Process(target=_test_forking_pickler_entry, args=(g, q))
    proc.start()
3608
    fmt = q.get()["created"]
3609
    proc.join()
3610
3611
3612
    assert "coo" in fmt
    assert "csr" in fmt
    assert "csc" in fmt
3613
3614


3615
if __name__ == "__main__":
3616
3617
3618
3619
3620
    # test_create()
    # test_query()
    # test_hypersparse()
    # test_adj("int32")
    # test_inc()
3621
    # test_view("int32")
3622
    # test_view1("int32")
3623
    # test_flatten(F.int32)
3624
3625
    # test_convert_bound()
    # test_convert()
3626
    # test_to_device("int32")
3627
    # test_transform("int32")
3628
3629
    # test_subgraph("int32")
    # test_subgraph_mask("int32")
3630
3631
3632
3633
3634
    # test_apply()
    # test_level1()
    # test_level2()
    # test_updates()
    # test_backward()
3635
    # test_empty_heterograph('int32')
3636
3637
3638
3639
    # test_types_in_function()
    # test_stack_reduce()
    # test_isolated_ntype()
    # test_bipartite()
3640
    # test_dtype_cast()
3641
    # test_float_cast()
3642
    # test_reverse("int32")
3643
    # test_format()
3644
3645
3646
3647
3648
3649
3650
3651
3652
    # test_add_edges(F.int32)
    # test_add_nodes(F.int32)
    # test_remove_edges(F.int32)
    # test_remove_nodes(F.int32)
    # test_clone(F.int32)
    # test_frame(F.int32)
    # test_frame_device(F.int32)
    # test_empty_query(F.int32)
    # test_create_block(F.int32)
3653
    pass