"tests/python/mxnet/test_nn.py" did not exist on "7ea777e1222686b2e07534526ebd152ff694bbde"
test_sampling.py 59.9 KB
Newer Older
1
import unittest
2
from collections import defaultdict
3
4
5
6
7

import backend as F

import dgl
import numpy as np
8
import pytest
9

10

Quan (Andy) Gan's avatar
Quan (Andy) Gan committed
11
def check_random_walk(g, metapath, traces, ntypes, prob=None, trace_eids=None):
12
13
14
15
    traces = F.asnumpy(traces)
    ntypes = F.asnumpy(ntypes)
    for j in range(traces.shape[1] - 1):
        assert ntypes[j] == g.get_ntype_id(g.to_canonical_etype(metapath[j])[0])
16
17
18
        assert ntypes[j + 1] == g.get_ntype_id(
            g.to_canonical_etype(metapath[j])[2]
        )
19
20
21

    for i in range(traces.shape[0]):
        for j in range(traces.shape[1] - 1):
22
            assert g.has_edges_between(
23
24
                traces[i, j], traces[i, j + 1], etype=metapath[j]
            )
25
            if prob is not None and prob in g.edges[metapath[j]].data:
26
27
28
29
                p = F.asnumpy(g.edges[metapath[j]].data["p"])
                eids = g.edge_ids(
                    traces[i, j], traces[i, j + 1], etype=metapath[j]
                )
30
                assert p[eids] != 0
Quan (Andy) Gan's avatar
Quan (Andy) Gan committed
31
32
33
            if trace_eids is not None:
                u, v = g.find_edges(trace_eids[i, j], etype=metapath[j])
                assert (u == traces[i, j]) and (v == traces[i, j + 1])
34

35
36

@pytest.mark.parametrize("use_uva", [True, False])
37
38
39
def test_non_uniform_random_walk(use_uva):
    if use_uva:
        if F.ctx() == F.cpu():
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
            pytest.skip("UVA biased random walk requires a GPU.")
        if dgl.backend.backend_name != "pytorch":
            pytest.skip(
                "UVA biased random walk is only supported with PyTorch."
            )
    g2 = dgl.heterograph(
        {("user", "follow", "user"): ([0, 1, 1, 2, 3], [1, 2, 3, 0, 0])}
    )
    g4 = dgl.heterograph(
        {
            ("user", "follow", "user"): ([0, 1, 1, 2, 3], [1, 2, 3, 0, 0]),
            ("user", "view", "item"): ([0, 0, 1, 2, 3, 3], [0, 1, 1, 2, 2, 1]),
            ("item", "viewed-by", "user"): (
                [0, 1, 1, 2, 2, 1],
                [0, 0, 1, 2, 3, 3],
            ),
        }
    )

    g2.edata["p"] = F.copy_to(
        F.tensor([3, 0, 3, 3, 3], dtype=F.float32), F.cpu()
    )
    g2.edata["p2"] = F.copy_to(
        F.tensor([[3], [0], [3], [3], [3]], dtype=F.float32), F.cpu()
    )
    g4.edges["follow"].data["p"] = F.copy_to(
        F.tensor([3, 0, 3, 3, 3], dtype=F.float32), F.cpu()
    )
    g4.edges["viewed-by"].data["p"] = F.copy_to(
        F.tensor([1, 1, 1, 1, 1, 1], dtype=F.float32), F.cpu()
    )
71

72
73
74
75
    if use_uva:
        for g in (g2, g4):
            g.create_formats_()
            g.pin_memory_()
76
    elif F._default_context_str == "gpu":
77
78
        g2 = g2.to(F.ctx())
        g4 = g4.to(F.ctx())
79

80
    try:
81
        traces, eids, ntypes = dgl.sampling.random_walk(
82
83
84
85
86
87
88
89
90
            g2,
            F.tensor([0, 1, 2, 3, 0, 1, 2, 3], dtype=g2.idtype),
            length=4,
            prob="p",
            return_eids=True,
        )
        check_random_walk(
            g2, ["follow"] * 4, traces, ntypes, "p", trace_eids=eids
        )
91
92
93

        with pytest.raises(dgl.DGLError):
            traces, ntypes = dgl.sampling.random_walk(
94
95
96
97
98
                g2,
                F.tensor([0, 1, 2, 3, 0, 1, 2, 3], dtype=g2.idtype),
                length=4,
                prob="p2",
            )
99

100
        metapath = ["follow", "view", "viewed-by"] * 2
101
        traces, eids, ntypes = dgl.sampling.random_walk(
102
103
104
105
106
107
108
            g4,
            F.tensor([0, 1, 2, 3, 0, 1, 2, 3], dtype=g4.idtype),
            metapath=metapath,
            prob="p",
            return_eids=True,
        )
        check_random_walk(g4, metapath, traces, ntypes, "p", trace_eids=eids)
109
        traces, eids, ntypes = dgl.sampling.random_walk(
110
111
112
113
114
115
116
117
            g4,
            F.tensor([0, 1, 2, 3, 0, 1, 2, 3], dtype=g4.idtype),
            metapath=metapath,
            prob="p",
            restart_prob=0.0,
            return_eids=True,
        )
        check_random_walk(g4, metapath, traces, ntypes, "p", trace_eids=eids)
118
        traces, eids, ntypes = dgl.sampling.random_walk(
119
120
121
122
123
124
125
126
            g4,
            F.tensor([0, 1, 2, 3, 0, 1, 2, 3], dtype=g4.idtype),
            metapath=metapath,
            prob="p",
            restart_prob=F.zeros((6,), F.float32, F.ctx()),
            return_eids=True,
        )
        check_random_walk(g4, metapath, traces, ntypes, "p", trace_eids=eids)
127
        traces, eids, ntypes = dgl.sampling.random_walk(
128
129
130
131
132
133
134
135
136
137
            g4,
            F.tensor([0, 1, 2, 3, 0, 1, 2, 3], dtype=g4.idtype),
            metapath=metapath + ["follow"],
            prob="p",
            restart_prob=F.tensor([0, 0, 0, 0, 0, 0, 1], F.float32),
            return_eids=True,
        )
        check_random_walk(
            g4, metapath, traces[:, :7], ntypes[:7], "p", trace_eids=eids
        )
138
139
140
141
142
        assert (F.asnumpy(traces[:, 7]) == -1).all()
    finally:
        for g in (g2, g4):
            g.unpin_memory_()

143
144

@pytest.mark.parametrize("use_uva", [True, False])
145
def test_uniform_random_walk(use_uva):
146
    if use_uva and F.ctx() == F.cpu():
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
        pytest.skip("UVA random walk requires a GPU.")
    g1 = dgl.heterograph({("user", "follow", "user"): ([0, 1, 2], [1, 2, 0])})
    g2 = dgl.heterograph(
        {("user", "follow", "user"): ([0, 1, 1, 2, 3], [1, 2, 3, 0, 0])}
    )
    g3 = dgl.heterograph(
        {
            ("user", "follow", "user"): ([0, 1, 2], [1, 2, 0]),
            ("user", "view", "item"): ([0, 1, 2], [0, 1, 2]),
            ("item", "viewed-by", "user"): ([0, 1, 2], [0, 1, 2]),
        }
    )
    g4 = dgl.heterograph(
        {
            ("user", "follow", "user"): ([0, 1, 1, 2, 3], [1, 2, 3, 0, 0]),
            ("user", "view", "item"): ([0, 0, 1, 2, 3, 3], [0, 1, 1, 2, 2, 1]),
            ("item", "viewed-by", "user"): (
                [0, 1, 1, 2, 2, 1],
                [0, 0, 1, 2, 3, 3],
            ),
        }
    )
169
170
171
172
173

    if use_uva:
        for g in (g1, g2, g3, g4):
            g.create_formats_()
            g.pin_memory_()
174
    elif F._default_context_str == "gpu":
175
176
177
178
179
180
181
        g1 = g1.to(F.ctx())
        g2 = g2.to(F.ctx())
        g3 = g3.to(F.ctx())
        g4 = g4.to(F.ctx())

    try:
        traces, eids, ntypes = dgl.sampling.random_walk(
182
183
184
185
186
187
188
            g1,
            F.tensor([0, 1, 2, 0, 1, 2], dtype=g1.idtype),
            length=4,
            return_eids=True,
        )
        check_random_walk(g1, ["follow"] * 4, traces, ntypes, trace_eids=eids)
        if F._default_context_str == "cpu":
189
            with pytest.raises(dgl.DGLError):
190
191
192
193
194
195
                dgl.sampling.random_walk(
                    g1,
                    F.tensor([0, 1, 2, 10], dtype=g1.idtype),
                    length=4,
                    return_eids=True,
                )
196
        traces, eids, ntypes = dgl.sampling.random_walk(
197
198
199
200
201
202
203
            g1,
            F.tensor([0, 1, 2, 0, 1, 2], dtype=g1.idtype),
            length=4,
            restart_prob=0.0,
            return_eids=True,
        )
        check_random_walk(g1, ["follow"] * 4, traces, ntypes, trace_eids=eids)
204
        traces, ntypes = dgl.sampling.random_walk(
205
206
207
208
209
210
            g1,
            F.tensor([0, 1, 2, 0, 1, 2], dtype=g1.idtype),
            length=4,
            restart_prob=F.zeros((4,), F.float32),
        )
        check_random_walk(g1, ["follow"] * 4, traces, ntypes)
211
        traces, ntypes = dgl.sampling.random_walk(
212
213
214
215
216
            g1,
            F.tensor([0, 1, 2, 0, 1, 2], dtype=g1.idtype),
            length=5,
            restart_prob=F.tensor([0, 0, 0, 0, 1], dtype=F.float32),
        )
217
        check_random_walk(
218
219
220
221
222
            g1,
            ["follow"] * 4,
            F.slice_axis(traces, 1, 0, 5),
            F.slice_axis(ntypes, 0, 0, 5),
        )
223
224
225
        assert (F.asnumpy(traces)[:, 5] == -1).all()

        traces, eids, ntypes = dgl.sampling.random_walk(
226
227
228
229
230
231
232
233
            g2,
            F.tensor([0, 1, 2, 3, 0, 1, 2, 3], dtype=g2.idtype),
            length=4,
            return_eids=True,
        )
        check_random_walk(g2, ["follow"] * 4, traces, ntypes, trace_eids=eids)

        metapath = ["follow", "view", "viewed-by"] * 2
234
        traces, eids, ntypes = dgl.sampling.random_walk(
235
236
237
238
239
            g3,
            F.tensor([0, 1, 2, 0, 1, 2], dtype=g3.idtype),
            metapath=metapath,
            return_eids=True,
        )
240
241
        check_random_walk(g3, metapath, traces, ntypes, trace_eids=eids)

242
        metapath = ["follow", "view", "viewed-by"] * 2
243
        traces, eids, ntypes = dgl.sampling.random_walk(
244
245
246
247
248
            g4,
            F.tensor([0, 1, 2, 3, 0, 1, 2, 3], dtype=g4.idtype),
            metapath=metapath,
            return_eids=True,
        )
249
250
251
        check_random_walk(g4, metapath, traces, ntypes, trace_eids=eids)

        traces, eids, ntypes = dgl.sampling.random_walk(
252
253
254
255
256
            g4,
            F.tensor([0, 1, 2, 0, 1, 2], dtype=g4.idtype),
            metapath=metapath,
            return_eids=True,
        )
257
        check_random_walk(g4, metapath, traces, ntypes, trace_eids=eids)
258
    finally:  # make sure to unpin the graphs even if some test fails
259
260
261
262
        for g in (g1, g2, g3, g4):
            if g.is_pinned():
                g.unpin_memory_()

263
264
265
266

@unittest.skipIf(
    F._default_context_str == "gpu", reason="GPU random walk not implemented"
)
Quan (Andy) Gan's avatar
Quan (Andy) Gan committed
267
def test_node2vec():
268
269
270
271
272
    g1 = dgl.heterograph({("user", "follow", "user"): ([0, 1, 2], [1, 2, 0])})
    g2 = dgl.heterograph(
        {("user", "follow", "user"): ([0, 1, 1, 2, 3], [1, 2, 3, 0, 0])}
    )
    g2.edata["p"] = F.tensor([3, 0, 3, 3, 3], dtype=F.float32)
Quan (Andy) Gan's avatar
Quan (Andy) Gan committed
273
274
275

    ntypes = F.zeros((5,), dtype=F.int64)

276
277
278
279
    traces, eids = dgl.sampling.node2vec_random_walk(
        g1, [0, 1, 2, 0, 1, 2], 1, 1, 4, return_eids=True
    )
    check_random_walk(g1, ["follow"] * 4, traces, ntypes, trace_eids=eids)
Quan (Andy) Gan's avatar
Quan (Andy) Gan committed
280
281

    traces, eids = dgl.sampling.node2vec_random_walk(
282
283
284
285
        g2, [0, 1, 2, 3, 0, 1, 2, 3], 1, 1, 4, prob="p", return_eids=True
    )
    check_random_walk(g2, ["follow"] * 4, traces, ntypes, "p", trace_eids=eids)

Quan (Andy) Gan's avatar
Quan (Andy) Gan committed
286

287
288
289
@unittest.skipIf(
    F._default_context_str == "gpu", reason="GPU pack traces not implemented"
)
290
def test_pack_traces():
291
292
293
294
295
296
    traces, types = (
        np.array(
            [[0, 1, -1, -1, -1, -1, -1], [0, 1, 1, 3, 0, 0, 0]], dtype="int64"
        ),
        np.array([0, 0, 1, 0, 0, 1, 0], dtype="int64"),
    )
297
298
299
    traces = F.zerocopy_from_numpy(traces)
    types = F.zerocopy_from_numpy(types)
    result = dgl.sampling.pack_traces(traces, types)
300
301
302
303
304
305
    assert F.array_equal(
        result[0], F.tensor([0, 1, 0, 1, 1, 3, 0, 0, 0], dtype=F.int64)
    )
    assert F.array_equal(
        result[1], F.tensor([0, 0, 0, 0, 1, 0, 0, 1, 0], dtype=F.int64)
    )
306
307
308
    assert F.array_equal(result[2], F.tensor([2, 7], dtype=F.int64))
    assert F.array_equal(result[3], F.tensor([0, 2], dtype=F.int64))

309
310

@pytest.mark.parametrize("use_uva", [True, False])
311
def test_pinsage_sampling(use_uva):
312
    if use_uva and F.ctx() == F.cpu():
313
314
        pytest.skip("UVA sampling requires a GPU.")

315
    def _test_sampler(g, sampler, ntype):
316
        seeds = F.copy_to(F.tensor([0, 2], dtype=g.idtype), F.ctx())
317
        neighbor_g = sampler(seeds)
318
        assert neighbor_g.ntypes == [ntype]
319
        u, v = neighbor_g.all_edges(form="uv", order="eid")
320
321
322
323
        uv = list(zip(F.asnumpy(u).tolist(), F.asnumpy(v).tolist()))
        assert (1, 0) in uv or (0, 0) in uv
        assert (2, 2) in uv or (3, 2) in uv

324
325
326
327
328
329
330
331
332
333
334
335
    g = dgl.heterograph(
        {
            ("item", "bought-by", "user"): (
                [0, 0, 1, 1, 2, 2, 3, 3],
                [0, 1, 0, 1, 2, 3, 2, 3],
            ),
            ("user", "bought", "item"): (
                [0, 1, 0, 1, 2, 3, 2, 3],
                [0, 0, 1, 1, 2, 2, 3, 3],
            ),
        }
    )
336
337
338
    if use_uva:
        g.create_formats_()
        g.pin_memory_()
339
    elif F._default_context_str == "gpu":
340
341
        g = g.to(F.ctx())
    try:
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
        sampler = dgl.sampling.PinSAGESampler(g, "item", "user", 4, 0.5, 3, 2)
        _test_sampler(g, sampler, "item")
        sampler = dgl.sampling.RandomWalkNeighborSampler(
            g, 4, 0.5, 3, 2, ["bought-by", "bought"]
        )
        _test_sampler(g, sampler, "item")
        sampler = dgl.sampling.RandomWalkNeighborSampler(
            g,
            4,
            0.5,
            3,
            2,
            [("item", "bought-by", "user"), ("user", "bought", "item")],
        )
        _test_sampler(g, sampler, "item")
357
358
359
360
    finally:
        if g.is_pinned():
            g.unpin_memory_()

361
    g = dgl.graph(([0, 0, 1, 1, 2, 2, 3, 3], [0, 1, 0, 1, 2, 3, 2, 3]))
362
363
364
    if use_uva:
        g.create_formats_()
        g.pin_memory_()
365
    elif F._default_context_str == "gpu":
366
367
368
369
370
371
372
373
        g = g.to(F.ctx())
    try:
        sampler = dgl.sampling.RandomWalkNeighborSampler(g, 4, 0.5, 3, 2)
        _test_sampler(g, sampler, g.ntypes[0])
    finally:
        if g.is_pinned():
            g.unpin_memory_()

374
375
376
377
378
379
380
    g = dgl.heterograph(
        {
            ("A", "AB", "B"): ([0, 2], [1, 3]),
            ("B", "BC", "C"): ([1, 3], [2, 1]),
            ("C", "CA", "A"): ([2, 1], [0, 2]),
        }
    )
381
382
383
    if use_uva:
        g.create_formats_()
        g.pin_memory_()
384
    elif F._default_context_str == "gpu":
385
386
        g = g.to(F.ctx())
    try:
387
388
389
390
        sampler = dgl.sampling.RandomWalkNeighborSampler(
            g, 4, 0.5, 3, 2, ["AB", "BC", "CA"]
        )
        _test_sampler(g, sampler, "A")
391
392
393
    finally:
        if g.is_pinned():
            g.unpin_memory_()
394

395

396
397
398
399
def _gen_neighbor_sampling_test_graph(hypersparse, reverse):
    if hypersparse:
        # should crash if allocated a CSR
        card = 1 << 50
400
        num_nodes_dict = {"user": card, "game": card, "coin": card}
401
402
    else:
        card = None
403
404
        num_nodes_dict = None

405
    if reverse:
406
407
408
409
410
411
412
413
414
        g = dgl.heterograph(
            {
                ("user", "follow", "user"): (
                    [0, 0, 0, 1, 1, 1, 2],
                    [1, 2, 3, 0, 2, 3, 0],
                )
            },
            {"user": card if card is not None else 4},
        )
415
        g = g.to(F.ctx())
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
        g.edata["prob"] = F.tensor(
            [0.5, 0.5, 0.0, 0.5, 0.5, 0.0, 1.0], dtype=F.float32
        )
        g.edata["mask"] = F.tensor([True, True, False, True, True, False, True])
        hg = dgl.heterograph(
            {
                ("user", "follow", "user"): (
                    [0, 0, 0, 1, 1, 1, 2],
                    [1, 2, 3, 0, 2, 3, 0],
                ),
                ("game", "play", "user"): ([0, 1, 2, 2], [0, 0, 1, 3]),
                ("user", "liked-by", "game"): (
                    [0, 1, 2, 0, 3, 0],
                    [2, 2, 2, 1, 1, 0],
                ),
                ("coin", "flips", "user"): ([0, 0, 0, 0], [0, 1, 2, 3]),
            },
            num_nodes_dict,
        )
435
        hg = hg.to(F.ctx())
436
    else:
437
438
439
440
441
442
443
444
445
        g = dgl.heterograph(
            {
                ("user", "follow", "user"): (
                    [1, 2, 3, 0, 2, 3, 0],
                    [0, 0, 0, 1, 1, 1, 2],
                )
            },
            {"user": card if card is not None else 4},
        )
446
        g = g.to(F.ctx())
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
        g.edata["prob"] = F.tensor(
            [0.5, 0.5, 0.0, 0.5, 0.5, 0.0, 1.0], dtype=F.float32
        )
        g.edata["mask"] = F.tensor([True, True, False, True, True, False, True])
        hg = dgl.heterograph(
            {
                ("user", "follow", "user"): (
                    [1, 2, 3, 0, 2, 3, 0],
                    [0, 0, 0, 1, 1, 1, 2],
                ),
                ("user", "play", "game"): ([0, 0, 1, 3], [0, 1, 2, 2]),
                ("game", "liked-by", "user"): (
                    [2, 2, 2, 1, 1, 0],
                    [0, 1, 2, 0, 3, 0],
                ),
                ("user", "flips", "coin"): ([0, 1, 2, 3], [0, 0, 0, 0]),
            },
            num_nodes_dict,
        )
466
        hg = hg.to(F.ctx())
467
468
469
470
471
472
473
474
475
    hg.edges["follow"].data["prob"] = F.tensor(
        [0.5, 0.5, 0.0, 0.5, 0.5, 0.0, 1.0], dtype=F.float32
    )
    hg.edges["follow"].data["mask"] = F.tensor(
        [True, True, False, True, True, False, True]
    )
    hg.edges["play"].data["prob"] = F.tensor(
        [0.8, 0.5, 0.5, 0.5], dtype=F.float32
    )
476
    # Leave out the mask of play and liked-by since all of them are True anyway.
477
478
479
    hg.edges["liked-by"].data["prob"] = F.tensor(
        [0.3, 0.5, 0.2, 0.5, 0.1, 0.1], dtype=F.float32
    )
480
481
482

    return g, hg

483

484
485
486
487
488
489
def _gen_neighbor_topk_test_graph(hypersparse, reverse):
    if hypersparse:
        # should crash if allocated a CSR
        card = 1 << 50
    else:
        card = None
490

491
    if reverse:
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
        g = dgl.heterograph(
            {
                ("user", "follow", "user"): (
                    [0, 0, 0, 1, 1, 1, 2],
                    [1, 2, 3, 0, 2, 3, 0],
                )
            }
        )
        g.edata["weight"] = F.tensor(
            [0.5, 0.3, 0.0, -5.0, 22.0, 0.0, 1.0], dtype=F.float32
        )
        hg = dgl.heterograph(
            {
                ("user", "follow", "user"): (
                    [0, 0, 0, 1, 1, 1, 2],
                    [1, 2, 3, 0, 2, 3, 0],
                ),
                ("game", "play", "user"): ([0, 1, 2, 2], [0, 0, 1, 3]),
                ("user", "liked-by", "game"): (
                    [0, 1, 2, 0, 3, 0],
                    [2, 2, 2, 1, 1, 0],
                ),
                ("coin", "flips", "user"): ([0, 0, 0, 0], [0, 1, 2, 3]),
            }
        )
517
    else:
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
        g = dgl.heterograph(
            {
                ("user", "follow", "user"): (
                    [1, 2, 3, 0, 2, 3, 0],
                    [0, 0, 0, 1, 1, 1, 2],
                )
            }
        )
        g.edata["weight"] = F.tensor(
            [0.5, 0.3, 0.0, -5.0, 22.0, 0.0, 1.0], dtype=F.float32
        )
        hg = dgl.heterograph(
            {
                ("user", "follow", "user"): (
                    [1, 2, 3, 0, 2, 3, 0],
                    [0, 0, 0, 1, 1, 1, 2],
                ),
                ("user", "play", "game"): ([0, 0, 1, 3], [0, 1, 2, 2]),
                ("game", "liked-by", "user"): (
                    [2, 2, 2, 1, 1, 0],
                    [0, 1, 2, 0, 3, 0],
                ),
                ("user", "flips", "coin"): ([0, 1, 2, 3], [0, 0, 0, 0]),
            }
        )
    hg.edges["follow"].data["weight"] = F.tensor(
        [0.5, 0.3, 0.0, -5.0, 22.0, 0.0, 1.0], dtype=F.float32
    )
    hg.edges["play"].data["weight"] = F.tensor(
        [0.8, 0.5, 0.4, 0.5], dtype=F.float32
    )
    hg.edges["liked-by"].data["weight"] = F.tensor(
        [0.3, 0.5, 0.2, 0.5, 0.1, 0.1], dtype=F.float32
    )
    hg.edges["flips"].data["weight"] = F.tensor(
        [10, 2, 13, -1], dtype=F.float32
    )
555
556
    return g, hg

557

558
def _test_sample_neighbors(hypersparse, prob):
559
560
561
    g, hg = _gen_neighbor_sampling_test_graph(hypersparse, False)

    def _test1(p, replace):
562
563
564
        subg = dgl.sampling.sample_neighbors(
            g, [0, 1], -1, prob=p, replace=replace
        )
Hongzhi (Steve), Chen's avatar
Hongzhi (Steve), Chen committed
565
        assert subg.num_nodes() == g.num_nodes()
566
        u, v = subg.edges()
567
        u_ans, v_ans, e_ans = g.in_edges([0, 1], form="all")
568
569
        if p is not None:
            emask = F.gather_row(g.edata[p], e_ans)
570
571
            if p == "prob":
                emask = emask != 0
572
573
            u_ans = F.boolean_mask(u_ans, emask)
            v_ans = F.boolean_mask(v_ans, emask)
574
575
576
577
        uv = set(zip(F.asnumpy(u), F.asnumpy(v)))
        uv_ans = set(zip(F.asnumpy(u_ans), F.asnumpy(v_ans)))
        assert uv == uv_ans

578
        for i in range(10):
579
580
581
            subg = dgl.sampling.sample_neighbors(
                g, [0, 1], 2, prob=p, replace=replace
            )
Hongzhi (Steve), Chen's avatar
Hongzhi (Steve), Chen committed
582
583
            assert subg.num_nodes() == g.num_nodes()
            assert subg.num_edges() == 4
584
585
            u, v = subg.edges()
            assert set(F.asnumpy(F.unique(v))) == {0, 1}
586
587
588
589
            assert F.array_equal(
                F.astype(g.has_edges_between(u, v), F.int64),
                F.ones((4,), dtype=F.int64),
            )
590
591
592
593
594
595
596
597
            assert F.array_equal(g.edge_ids(u, v), subg.edata[dgl.EID])
            edge_set = set(zip(list(F.asnumpy(u)), list(F.asnumpy(v))))
            if not replace:
                # check no duplication
                assert len(edge_set) == 4
            if p is not None:
                assert not (3, 0) in edge_set
                assert not (3, 1) in edge_set
598
599

    _test1(prob, True)  # w/ replacement, uniform
600
    _test1(prob, False)  # w/o replacement, uniform
601
602

    def _test2(p, replace):  # fanout > #neighbors
603
604
605
        subg = dgl.sampling.sample_neighbors(
            g, [0, 2], -1, prob=p, replace=replace
        )
Hongzhi (Steve), Chen's avatar
Hongzhi (Steve), Chen committed
606
        assert subg.num_nodes() == g.num_nodes()
607
        u, v = subg.edges()
608
        u_ans, v_ans, e_ans = g.in_edges([0, 2], form="all")
609
610
        if p is not None:
            emask = F.gather_row(g.edata[p], e_ans)
611
612
            if p == "prob":
                emask = emask != 0
613
614
            u_ans = F.boolean_mask(u_ans, emask)
            v_ans = F.boolean_mask(v_ans, emask)
615
616
617
618
        uv = set(zip(F.asnumpy(u), F.asnumpy(v)))
        uv_ans = set(zip(F.asnumpy(u_ans), F.asnumpy(v_ans)))
        assert uv == uv_ans

619
        for i in range(10):
620
621
622
            subg = dgl.sampling.sample_neighbors(
                g, [0, 2], 2, prob=p, replace=replace
            )
Hongzhi (Steve), Chen's avatar
Hongzhi (Steve), Chen committed
623
            assert subg.num_nodes() == g.num_nodes()
624
            num_edges = 4 if replace else 3
Hongzhi (Steve), Chen's avatar
Hongzhi (Steve), Chen committed
625
            assert subg.num_edges() == num_edges
626
627
            u, v = subg.edges()
            assert set(F.asnumpy(F.unique(v))) == {0, 2}
628
629
630
631
            assert F.array_equal(
                F.astype(g.has_edges_between(u, v), F.int64),
                F.ones((num_edges,), dtype=F.int64),
            )
632
633
634
635
636
637
638
            assert F.array_equal(g.edge_ids(u, v), subg.edata[dgl.EID])
            edge_set = set(zip(list(F.asnumpy(u)), list(F.asnumpy(v))))
            if not replace:
                # check no duplication
                assert len(edge_set) == num_edges
            if p is not None:
                assert not (3, 0) in edge_set
639
640

    _test2(prob, True)  # w/ replacement, uniform
641
    _test2(prob, False)  # w/o replacement, uniform
642
643

    def _test3(p, replace):
644
645
646
        subg = dgl.sampling.sample_neighbors(
            hg, {"user": [0, 1], "game": 0}, -1, prob=p, replace=replace
        )
647
648
        assert len(subg.ntypes) == 3
        assert len(subg.etypes) == 4
Hongzhi (Steve), Chen's avatar
Hongzhi (Steve), Chen committed
649
650
651
652
        assert subg["follow"].num_edges() == 6 if p is None else 4
        assert subg["play"].num_edges() == 1
        assert subg["liked-by"].num_edges() == 4
        assert subg["flips"].num_edges() == 0
653

654
        for i in range(10):
655
656
657
            subg = dgl.sampling.sample_neighbors(
                hg, {"user": [0, 1], "game": 0}, 2, prob=p, replace=replace
            )
658
659
            assert len(subg.ntypes) == 3
            assert len(subg.etypes) == 4
Hongzhi (Steve), Chen's avatar
Hongzhi (Steve), Chen committed
660
661
662
663
            assert subg["follow"].num_edges() == 4
            assert subg["play"].num_edges() == 2 if replace else 1
            assert subg["liked-by"].num_edges() == 4 if replace else 3
            assert subg["flips"].num_edges() == 0
664

665
    _test3(prob, True)  # w/ replacement, uniform
666
    _test3(prob, False)  # w/o replacement, uniform
667
668
669

    # test different fanouts for different relations
    for i in range(10):
670
671
        subg = dgl.sampling.sample_neighbors(
            hg,
672
673
674
675
            {"user": [0, 1], "game": 0, "coin": 0},
            {"follow": 1, "play": 2, "liked-by": 0, "flips": -1},
            replace=True,
        )
676
677
        assert len(subg.ntypes) == 3
        assert len(subg.etypes) == 4
Hongzhi (Steve), Chen's avatar
Hongzhi (Steve), Chen committed
678
679
680
681
        assert subg["follow"].num_edges() == 2
        assert subg["play"].num_edges() == 2
        assert subg["liked-by"].num_edges() == 0
        assert subg["flips"].num_edges() == 4
682

683

684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
def _test_sample_labors(hypersparse, prob):
    g, hg = _gen_neighbor_sampling_test_graph(hypersparse, False)

    # test with seed nodes [0, 1]
    def _test1(p):
        subg = dgl.sampling.sample_labors(g, [0, 1], -1, prob=p)[0]
        assert subg.num_nodes() == g.num_nodes()
        u, v = subg.edges()
        u_ans, v_ans, e_ans = g.in_edges([0, 1], form="all")
        if p is not None:
            emask = F.gather_row(g.edata[p], e_ans)
            if p == "prob":
                emask = emask != 0
            u_ans = F.boolean_mask(u_ans, emask)
            v_ans = F.boolean_mask(v_ans, emask)
        uv = set(zip(F.asnumpy(u), F.asnumpy(v)))
        uv_ans = set(zip(F.asnumpy(u_ans), F.asnumpy(v_ans)))
        assert uv == uv_ans

        for i in range(10):
            subg = dgl.sampling.sample_labors(g, [0, 1], 2, prob=p)[0]
            assert subg.num_nodes() == g.num_nodes()
            assert subg.num_edges() >= 0
            u, v = subg.edges()
            assert set(F.asnumpy(F.unique(v))).issubset({0, 1})
            assert F.array_equal(
                F.astype(g.has_edges_between(u, v), F.int64),
                F.ones((subg.num_edges(),), dtype=F.int64),
            )
            assert F.array_equal(g.edge_ids(u, v), subg.edata[dgl.EID])
            edge_set = set(zip(list(F.asnumpy(u)), list(F.asnumpy(v))))
            # check no duplication
            assert len(edge_set) == subg.num_edges()
            if p is not None:
                assert not (3, 0) in edge_set
                assert not (3, 1) in edge_set

    _test1(prob)

    # test with seed nodes [0, 2]
    def _test2(p):
        subg = dgl.sampling.sample_labors(g, [0, 2], -1, prob=p)[0]
        assert subg.num_nodes() == g.num_nodes()
        u, v = subg.edges()
        u_ans, v_ans, e_ans = g.in_edges([0, 2], form="all")
        if p is not None:
            emask = F.gather_row(g.edata[p], e_ans)
            if p == "prob":
                emask = emask != 0
            u_ans = F.boolean_mask(u_ans, emask)
            v_ans = F.boolean_mask(v_ans, emask)
        uv = set(zip(F.asnumpy(u), F.asnumpy(v)))
        uv_ans = set(zip(F.asnumpy(u_ans), F.asnumpy(v_ans)))
        assert uv == uv_ans

        for i in range(10):
            subg = dgl.sampling.sample_labors(g, [0, 2], 2, prob=p)[0]
            assert subg.num_nodes() == g.num_nodes()
            assert subg.num_edges() >= 0
            u, v = subg.edges()
            assert set(F.asnumpy(F.unique(v))).issubset({0, 2})
            assert F.array_equal(
                F.astype(g.has_edges_between(u, v), F.int64),
                F.ones((subg.num_edges(),), dtype=F.int64),
            )
            assert F.array_equal(g.edge_ids(u, v), subg.edata[dgl.EID])
            edge_set = set(zip(list(F.asnumpy(u)), list(F.asnumpy(v))))
            # check no duplication
            assert len(edge_set) == subg.num_edges()
            if p is not None:
                assert not (3, 0) in edge_set

    _test2(prob)

    # test with heterogenous seed nodes
    def _test3(p):
        subg = dgl.sampling.sample_labors(
            hg, {"user": [0, 1], "game": 0}, -1, prob=p
        )[0]
        assert len(subg.ntypes) == 3
        assert len(subg.etypes) == 4
        assert subg["follow"].num_edges() == 6 if p is None else 4
        assert subg["play"].num_edges() == 1
        assert subg["liked-by"].num_edges() == 4
        assert subg["flips"].num_edges() == 0

        for i in range(10):
            subg = dgl.sampling.sample_labors(
                hg, {"user": [0, 1], "game": 0}, 2, prob=p
            )[0]
            assert len(subg.ntypes) == 3
            assert len(subg.etypes) == 4
            assert subg["follow"].num_edges() >= 0
            assert subg["play"].num_edges() >= 0
            assert subg["liked-by"].num_edges() >= 0
            assert subg["flips"].num_edges() >= 0

    _test3(prob)

    # test different fanouts for different relations
    for i in range(10):
        subg = dgl.sampling.sample_labors(
            hg,
            {"user": [0, 1], "game": 0, "coin": 0},
            {"follow": 1, "play": 2, "liked-by": 0, "flips": g.num_nodes()},
        )[0]
        assert len(subg.ntypes) == 3
        assert len(subg.etypes) == 4
        assert subg["follow"].num_edges() >= 0
        assert subg["play"].num_edges() >= 0
        assert subg["liked-by"].num_edges() == 0
        assert subg["flips"].num_edges() == 4


798
799
800
801
def _test_sample_neighbors_outedge(hypersparse):
    g, hg = _gen_neighbor_sampling_test_graph(hypersparse, True)

    def _test1(p, replace):
802
803
804
        subg = dgl.sampling.sample_neighbors(
            g, [0, 1], -1, prob=p, replace=replace, edge_dir="out"
        )
Hongzhi (Steve), Chen's avatar
Hongzhi (Steve), Chen committed
805
        assert subg.num_nodes() == g.num_nodes()
806
        u, v = subg.edges()
807
        u_ans, v_ans, e_ans = g.out_edges([0, 1], form="all")
808
809
        if p is not None:
            emask = F.gather_row(g.edata[p], e_ans)
810
811
            if p == "prob":
                emask = emask != 0
812
813
            u_ans = F.boolean_mask(u_ans, emask)
            v_ans = F.boolean_mask(v_ans, emask)
814
815
816
817
        uv = set(zip(F.asnumpy(u), F.asnumpy(v)))
        uv_ans = set(zip(F.asnumpy(u_ans), F.asnumpy(v_ans)))
        assert uv == uv_ans

818
        for i in range(10):
819
820
821
            subg = dgl.sampling.sample_neighbors(
                g, [0, 1], 2, prob=p, replace=replace, edge_dir="out"
            )
Hongzhi (Steve), Chen's avatar
Hongzhi (Steve), Chen committed
822
823
            assert subg.num_nodes() == g.num_nodes()
            assert subg.num_edges() == 4
824
825
            u, v = subg.edges()
            assert set(F.asnumpy(F.unique(u))) == {0, 1}
826
827
828
829
            assert F.array_equal(
                F.astype(g.has_edges_between(u, v), F.int64),
                F.ones((4,), dtype=F.int64),
            )
830
831
832
833
834
835
836
837
            assert F.array_equal(g.edge_ids(u, v), subg.edata[dgl.EID])
            edge_set = set(zip(list(F.asnumpy(u)), list(F.asnumpy(v))))
            if not replace:
                # check no duplication
                assert len(edge_set) == 4
            if p is not None:
                assert not (0, 3) in edge_set
                assert not (1, 3) in edge_set
838
839

    _test1(None, True)  # w/ replacement, uniform
840
    _test1(None, False)  # w/o replacement, uniform
841
842
    _test1("prob", True)  # w/ replacement
    _test1("prob", False)  # w/o replacement
843
844

    def _test2(p, replace):  # fanout > #neighbors
845
846
847
        subg = dgl.sampling.sample_neighbors(
            g, [0, 2], -1, prob=p, replace=replace, edge_dir="out"
        )
Hongzhi (Steve), Chen's avatar
Hongzhi (Steve), Chen committed
848
        assert subg.num_nodes() == g.num_nodes()
849
        u, v = subg.edges()
850
        u_ans, v_ans, e_ans = g.out_edges([0, 2], form="all")
851
852
        if p is not None:
            emask = F.gather_row(g.edata[p], e_ans)
853
854
            if p == "prob":
                emask = emask != 0
855
856
            u_ans = F.boolean_mask(u_ans, emask)
            v_ans = F.boolean_mask(v_ans, emask)
857
858
859
860
        uv = set(zip(F.asnumpy(u), F.asnumpy(v)))
        uv_ans = set(zip(F.asnumpy(u_ans), F.asnumpy(v_ans)))
        assert uv == uv_ans

861
        for i in range(10):
862
863
864
            subg = dgl.sampling.sample_neighbors(
                g, [0, 2], 2, prob=p, replace=replace, edge_dir="out"
            )
Hongzhi (Steve), Chen's avatar
Hongzhi (Steve), Chen committed
865
            assert subg.num_nodes() == g.num_nodes()
866
            num_edges = 4 if replace else 3
Hongzhi (Steve), Chen's avatar
Hongzhi (Steve), Chen committed
867
            assert subg.num_edges() == num_edges
868
869
            u, v = subg.edges()
            assert set(F.asnumpy(F.unique(u))) == {0, 2}
870
871
872
873
            assert F.array_equal(
                F.astype(g.has_edges_between(u, v), F.int64),
                F.ones((num_edges,), dtype=F.int64),
            )
874
875
876
877
878
879
880
            assert F.array_equal(g.edge_ids(u, v), subg.edata[dgl.EID])
            edge_set = set(zip(list(F.asnumpy(u)), list(F.asnumpy(v))))
            if not replace:
                # check no duplication
                assert len(edge_set) == num_edges
            if p is not None:
                assert not (0, 3) in edge_set
881
882

    _test2(None, True)  # w/ replacement, uniform
883
    _test2(None, False)  # w/o replacement, uniform
884
885
    _test2("prob", True)  # w/ replacement
    _test2("prob", False)  # w/o replacement
886
887

    def _test3(p, replace):
888
889
890
891
892
893
894
895
        subg = dgl.sampling.sample_neighbors(
            hg,
            {"user": [0, 1], "game": 0},
            -1,
            prob=p,
            replace=replace,
            edge_dir="out",
        )
896
897
        assert len(subg.ntypes) == 3
        assert len(subg.etypes) == 4
Hongzhi (Steve), Chen's avatar
Hongzhi (Steve), Chen committed
898
899
900
901
        assert subg["follow"].num_edges() == 6 if p is None else 4
        assert subg["play"].num_edges() == 1
        assert subg["liked-by"].num_edges() == 4
        assert subg["flips"].num_edges() == 0
902

903
        for i in range(10):
904
905
906
907
908
909
910
911
            subg = dgl.sampling.sample_neighbors(
                hg,
                {"user": [0, 1], "game": 0},
                2,
                prob=p,
                replace=replace,
                edge_dir="out",
            )
912
913
            assert len(subg.ntypes) == 3
            assert len(subg.etypes) == 4
Hongzhi (Steve), Chen's avatar
Hongzhi (Steve), Chen committed
914
915
916
917
            assert subg["follow"].num_edges() == 4
            assert subg["play"].num_edges() == 2 if replace else 1
            assert subg["liked-by"].num_edges() == 4 if replace else 3
            assert subg["flips"].num_edges() == 0
918

919
    _test3(None, True)  # w/ replacement, uniform
920
    _test3(None, False)  # w/o replacement, uniform
921
922
923
    _test3("prob", True)  # w/ replacement
    _test3("prob", False)  # w/o replacement

924
925
926
927
928

def _test_sample_neighbors_topk(hypersparse):
    g, hg = _gen_neighbor_topk_test_graph(hypersparse, False)

    def _test1():
929
        subg = dgl.sampling.select_topk(g, -1, "weight", [0, 1])
Hongzhi (Steve), Chen's avatar
Hongzhi (Steve), Chen committed
930
        assert subg.num_nodes() == g.num_nodes()
931
932
933
934
935
936
        u, v = subg.edges()
        u_ans, v_ans = subg.in_edges([0, 1])
        uv = set(zip(F.asnumpy(u), F.asnumpy(v)))
        uv_ans = set(zip(F.asnumpy(u_ans), F.asnumpy(v_ans)))
        assert uv == uv_ans

937
        subg = dgl.sampling.select_topk(g, 2, "weight", [0, 1])
Hongzhi (Steve), Chen's avatar
Hongzhi (Steve), Chen committed
938
939
        assert subg.num_nodes() == g.num_nodes()
        assert subg.num_edges() == 4
940
941
942
        u, v = subg.edges()
        edge_set = set(zip(list(F.asnumpy(u)), list(F.asnumpy(v))))
        assert F.array_equal(g.edge_ids(u, v), subg.edata[dgl.EID])
943
944
        assert edge_set == {(2, 0), (1, 0), (2, 1), (3, 1)}

945
946
947
    _test1()

    def _test2():  # k > #neighbors
948
        subg = dgl.sampling.select_topk(g, -1, "weight", [0, 2])
Hongzhi (Steve), Chen's avatar
Hongzhi (Steve), Chen committed
949
        assert subg.num_nodes() == g.num_nodes()
950
951
952
953
954
955
        u, v = subg.edges()
        u_ans, v_ans = subg.in_edges([0, 2])
        uv = set(zip(F.asnumpy(u), F.asnumpy(v)))
        uv_ans = set(zip(F.asnumpy(u_ans), F.asnumpy(v_ans)))
        assert uv == uv_ans

956
        subg = dgl.sampling.select_topk(g, 2, "weight", [0, 2])
Hongzhi (Steve), Chen's avatar
Hongzhi (Steve), Chen committed
957
958
        assert subg.num_nodes() == g.num_nodes()
        assert subg.num_edges() == 3
959
960
961
        u, v = subg.edges()
        assert F.array_equal(g.edge_ids(u, v), subg.edata[dgl.EID])
        edge_set = set(zip(list(F.asnumpy(u)), list(F.asnumpy(v))))
962
963
        assert edge_set == {(2, 0), (1, 0), (0, 2)}

964
965
966
    _test2()

    def _test3():
967
968
969
        subg = dgl.sampling.select_topk(
            hg, 2, "weight", {"user": [0, 1], "game": 0}
        )
970
971
        assert len(subg.ntypes) == 3
        assert len(subg.etypes) == 4
972
        u, v = subg["follow"].edges()
973
        edge_set = set(zip(list(F.asnumpy(u)), list(F.asnumpy(v))))
974
975
976
977
978
        assert F.array_equal(
            hg["follow"].edge_ids(u, v), subg["follow"].edata[dgl.EID]
        )
        assert edge_set == {(2, 0), (1, 0), (2, 1), (3, 1)}
        u, v = subg["play"].edges()
979
        edge_set = set(zip(list(F.asnumpy(u)), list(F.asnumpy(v))))
980
981
982
983
984
        assert F.array_equal(
            hg["play"].edge_ids(u, v), subg["play"].edata[dgl.EID]
        )
        assert edge_set == {(0, 0)}
        u, v = subg["liked-by"].edges()
985
        edge_set = set(zip(list(F.asnumpy(u)), list(F.asnumpy(v))))
986
987
988
989
        assert F.array_equal(
            hg["liked-by"].edge_ids(u, v), subg["liked-by"].edata[dgl.EID]
        )
        assert edge_set == {(2, 0), (2, 1), (1, 0)}
Hongzhi (Steve), Chen's avatar
Hongzhi (Steve), Chen committed
990
        assert subg["flips"].num_edges() == 0
991

992
993
994
    _test3()

    # test different k for different relations
995
    subg = dgl.sampling.select_topk(
996
997
998
999
1000
        hg,
        {"follow": 1, "play": 2, "liked-by": 0, "flips": -1},
        "weight",
        {"user": [0, 1], "game": 0, "coin": 0},
    )
1001
1002
    assert len(subg.ntypes) == 3
    assert len(subg.etypes) == 4
Hongzhi (Steve), Chen's avatar
Hongzhi (Steve), Chen committed
1003
1004
1005
1006
    assert subg["follow"].num_edges() == 2
    assert subg["play"].num_edges() == 1
    assert subg["liked-by"].num_edges() == 0
    assert subg["flips"].num_edges() == 4
1007

1008
1009
1010
1011
1012

def _test_sample_neighbors_topk_outedge(hypersparse):
    g, hg = _gen_neighbor_topk_test_graph(hypersparse, True)

    def _test1():
1013
        subg = dgl.sampling.select_topk(g, -1, "weight", [0, 1], edge_dir="out")
Hongzhi (Steve), Chen's avatar
Hongzhi (Steve), Chen committed
1014
        assert subg.num_nodes() == g.num_nodes()
1015
1016
1017
1018
1019
1020
        u, v = subg.edges()
        u_ans, v_ans = subg.out_edges([0, 1])
        uv = set(zip(F.asnumpy(u), F.asnumpy(v)))
        uv_ans = set(zip(F.asnumpy(u_ans), F.asnumpy(v_ans)))
        assert uv == uv_ans

1021
        subg = dgl.sampling.select_topk(g, 2, "weight", [0, 1], edge_dir="out")
Hongzhi (Steve), Chen's avatar
Hongzhi (Steve), Chen committed
1022
1023
        assert subg.num_nodes() == g.num_nodes()
        assert subg.num_edges() == 4
1024
1025
1026
        u, v = subg.edges()
        edge_set = set(zip(list(F.asnumpy(u)), list(F.asnumpy(v))))
        assert F.array_equal(g.edge_ids(u, v), subg.edata[dgl.EID])
1027
1028
        assert edge_set == {(0, 2), (0, 1), (1, 2), (1, 3)}

1029
1030
1031
    _test1()

    def _test2():  # k > #neighbors
1032
        subg = dgl.sampling.select_topk(g, -1, "weight", [0, 2], edge_dir="out")
Hongzhi (Steve), Chen's avatar
Hongzhi (Steve), Chen committed
1033
        assert subg.num_nodes() == g.num_nodes()
1034
1035
1036
1037
1038
1039
        u, v = subg.edges()
        u_ans, v_ans = subg.out_edges([0, 2])
        uv = set(zip(F.asnumpy(u), F.asnumpy(v)))
        uv_ans = set(zip(F.asnumpy(u_ans), F.asnumpy(v_ans)))
        assert uv == uv_ans

1040
        subg = dgl.sampling.select_topk(g, 2, "weight", [0, 2], edge_dir="out")
Hongzhi (Steve), Chen's avatar
Hongzhi (Steve), Chen committed
1041
1042
        assert subg.num_nodes() == g.num_nodes()
        assert subg.num_edges() == 3
1043
1044
1045
        u, v = subg.edges()
        edge_set = set(zip(list(F.asnumpy(u)), list(F.asnumpy(v))))
        assert F.array_equal(g.edge_ids(u, v), subg.edata[dgl.EID])
1046
1047
        assert edge_set == {(0, 2), (0, 1), (2, 0)}

1048
1049
1050
    _test2()

    def _test3():
1051
1052
1053
        subg = dgl.sampling.select_topk(
            hg, 2, "weight", {"user": [0, 1], "game": 0}, edge_dir="out"
        )
1054
1055
        assert len(subg.ntypes) == 3
        assert len(subg.etypes) == 4
1056
        u, v = subg["follow"].edges()
1057
        edge_set = set(zip(list(F.asnumpy(u)), list(F.asnumpy(v))))
1058
1059
1060
1061
1062
        assert F.array_equal(
            hg["follow"].edge_ids(u, v), subg["follow"].edata[dgl.EID]
        )
        assert edge_set == {(0, 2), (0, 1), (1, 2), (1, 3)}
        u, v = subg["play"].edges()
1063
        edge_set = set(zip(list(F.asnumpy(u)), list(F.asnumpy(v))))
1064
1065
1066
1067
1068
        assert F.array_equal(
            hg["play"].edge_ids(u, v), subg["play"].edata[dgl.EID]
        )
        assert edge_set == {(0, 0)}
        u, v = subg["liked-by"].edges()
1069
        edge_set = set(zip(list(F.asnumpy(u)), list(F.asnumpy(v))))
1070
1071
1072
1073
        assert F.array_equal(
            hg["liked-by"].edge_ids(u, v), subg["liked-by"].edata[dgl.EID]
        )
        assert edge_set == {(0, 2), (1, 2), (0, 1)}
Hongzhi (Steve), Chen's avatar
Hongzhi (Steve), Chen committed
1074
        assert subg["flips"].num_edges() == 0
1075

1076
1077
    _test3()

1078

1079
1080
def test_sample_neighbors_noprob():
    _test_sample_neighbors(False, None)
1081
1082
    # _test_sample_neighbors(True)

1083

1084
1085
1086
1087
def test_sample_labors_noprob():
    _test_sample_labors(False, None)


1088
def test_sample_neighbors_prob():
1089
1090
1091
    _test_sample_neighbors(False, "prob")
    # _test_sample_neighbors(True)

1092

1093
1094
1095
1096
def test_sample_labors_prob():
    _test_sample_labors(False, "prob")


1097
1098
def test_sample_neighbors_outedge():
    _test_sample_neighbors_outedge(False)
1099
1100
    # _test_sample_neighbors_outedge(True)

1101

1102
1103
1104
1105
1106
1107
1108
@unittest.skipIf(
    F.backend_name == "mxnet", reason="MXNet has problem converting bool arrays"
)
@unittest.skipIf(
    F._default_context_str == "gpu",
    reason="GPU sample neighbors with mask not implemented",
)
1109
def test_sample_neighbors_mask():
1110
    _test_sample_neighbors(False, "mask")
1111

1112
1113
1114
1115
1116

@unittest.skipIf(
    F._default_context_str == "gpu",
    reason="GPU sample neighbors not implemented",
)
1117
1118
def test_sample_neighbors_topk():
    _test_sample_neighbors_topk(False)
1119
1120
    # _test_sample_neighbors_topk(True)

1121

1122
1123
1124
1125
@unittest.skipIf(
    F._default_context_str == "gpu",
    reason="GPU sample neighbors not implemented",
)
1126
1127
def test_sample_neighbors_topk_outedge():
    _test_sample_neighbors_topk_outedge(False)
1128
1129
    # _test_sample_neighbors_topk_outedge(True)

1130

1131
def test_sample_neighbors_with_0deg():
1132
    g = dgl.graph(([], []), num_nodes=5).to(F.ctx())
1133
1134
1135
    sg = dgl.sampling.sample_neighbors(
        g, F.tensor([1, 2], dtype=F.int64), 2, edge_dir="in", replace=False
    )
Hongzhi (Steve), Chen's avatar
Hongzhi (Steve), Chen committed
1136
    assert sg.num_edges() == 0
1137
1138
1139
    sg = dgl.sampling.sample_neighbors(
        g, F.tensor([1, 2], dtype=F.int64), 2, edge_dir="in", replace=True
    )
Hongzhi (Steve), Chen's avatar
Hongzhi (Steve), Chen committed
1140
    assert sg.num_edges() == 0
1141
1142
1143
    sg = dgl.sampling.sample_neighbors(
        g, F.tensor([1, 2], dtype=F.int64), 2, edge_dir="out", replace=False
    )
Hongzhi (Steve), Chen's avatar
Hongzhi (Steve), Chen committed
1144
    assert sg.num_edges() == 0
1145
1146
1147
    sg = dgl.sampling.sample_neighbors(
        g, F.tensor([1, 2], dtype=F.int64), 2, edge_dir="out", replace=True
    )
Hongzhi (Steve), Chen's avatar
Hongzhi (Steve), Chen committed
1148
    assert sg.num_edges() == 0
1149

1150

1151
1152
def create_test_graph(num_nodes, num_edges_per_node, bipartite=False):
    src = np.concatenate(
1153
1154
        [np.array([i] * num_edges_per_node) for i in range(num_nodes)]
    )
1155
    dst = np.concatenate(
1156
1157
1158
1159
        [
            np.random.choice(num_nodes, num_edges_per_node, replace=False)
            for i in range(num_nodes)
        ]
1160
1161
    )
    if bipartite:
1162
        g = dgl.heterograph({("u", "e", "v"): (src, dst)})
1163
1164
1165
1166
    else:
        g = dgl.graph((src, dst))
    return g

1167

1168
1169
def create_etype_test_graph(num_nodes, num_edges_per_node, rare_cnt):
    src = np.concatenate(
1170
1171
1172
1173
        [
            np.random.choice(num_nodes, num_edges_per_node, replace=False)
            for i in range(num_nodes)
        ]
1174
1175
    )
    dst = np.concatenate(
1176
1177
        [np.array([i] * num_edges_per_node) for i in range(num_nodes)]
    )
1178
1179

    minor_src = np.concatenate(
1180
1181
1182
1183
        [
            np.random.choice(num_nodes, 2, replace=False)
            for i in range(num_nodes)
        ]
1184
    )
1185
    minor_dst = np.concatenate([np.array([i] * 2) for i in range(num_nodes)])
1186
1187

    most_zero_src = np.concatenate(
1188
1189
1190
1191
        [
            np.random.choice(num_nodes, num_edges_per_node, replace=False)
            for i in range(rare_cnt)
        ]
1192
1193
    )
    most_zero_dst = np.concatenate(
1194
1195
        [np.array([i] * num_edges_per_node) for i in range(rare_cnt)]
    )
1196

1197
1198
1199
1200
1201
1202
1203
1204
1205
    g = dgl.heterograph(
        {
            ("v", "e_major", "u"): (src, dst),
            ("u", "e_major_rev", "v"): (dst, src),
            ("v2", "e_minor", "u"): (minor_src, minor_dst),
            ("v2", "most_zero", "u"): (most_zero_src, most_zero_dst),
            ("u", "e_minor_rev", "v2"): (minor_dst, minor_src),
        }
    )
1206
1207
1208
    for etype in g.etypes:
        prob = np.random.rand(g.num_edges(etype))
        prob[prob > 0.2] = 0
1209
1210
        g.edges[etype].data["p"] = F.zerocopy_from_numpy(prob)
        g.edges[etype].data["mask"] = F.zerocopy_from_numpy(prob != 0)
1211
1212
1213

    return g

1214
1215
1216
1217
1218

@unittest.skipIf(
    F._default_context_str == "gpu",
    reason="GPU sample neighbors not implemented",
)
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
def test_sample_neighbors_biased_homogeneous():
    g = create_test_graph(100, 30)

    def check_num(nodes, tag):
        nodes, tag = F.asnumpy(nodes), F.asnumpy(tag)
        cnt = [sum(tag[nodes] == i) for i in range(4)]
        # No tag 0
        assert cnt[0] == 0

        # very rare tag 1
        assert cnt[2] > 2 * cnt[1]
        assert cnt[3] > 2 * cnt[1]

    tag = F.tensor(np.random.choice(4, 100))
    bias = F.tensor([0, 0.1, 10, 10], dtype=F.float32)
    # inedge / without replacement
1235
    g_sorted = dgl.sort_csc_by_tag(g, tag)
1236
    for _ in range(5):
1237
1238
1239
        subg = dgl.sampling.sample_neighbors_biased(
            g_sorted, g.nodes(), 5, bias, replace=False
        )
1240
1241
1242
        check_num(subg.edges()[0], tag)
        u, v = subg.edges()
        edge_set = set(zip(list(F.asnumpy(u)), list(F.asnumpy(v))))
Hongzhi (Steve), Chen's avatar
Hongzhi (Steve), Chen committed
1243
        assert len(edge_set) == subg.num_edges()
1244
1245
1246

    # inedge / with replacement
    for _ in range(5):
1247
1248
1249
        subg = dgl.sampling.sample_neighbors_biased(
            g_sorted, g.nodes(), 5, bias, replace=True
        )
1250
1251
1252
        check_num(subg.edges()[0], tag)

    # outedge / without replacement
1253
    g_sorted = dgl.sort_csr_by_tag(g, tag)
1254
    for _ in range(5):
1255
1256
1257
        subg = dgl.sampling.sample_neighbors_biased(
            g_sorted, g.nodes(), 5, bias, edge_dir="out", replace=False
        )
1258
1259
1260
        check_num(subg.edges()[1], tag)
        u, v = subg.edges()
        edge_set = set(zip(list(F.asnumpy(u)), list(F.asnumpy(v))))
Hongzhi (Steve), Chen's avatar
Hongzhi (Steve), Chen committed
1261
        assert len(edge_set) == subg.num_edges()
1262
1263
1264

    # outedge / with replacement
    for _ in range(5):
1265
1266
1267
        subg = dgl.sampling.sample_neighbors_biased(
            g_sorted, g.nodes(), 5, bias, edge_dir="out", replace=True
        )
1268
1269
        check_num(subg.edges()[1], tag)

1270
1271
1272
1273
1274

@unittest.skipIf(
    F._default_context_str == "gpu",
    reason="GPU sample neighbors not implemented",
)
1275
1276
1277
1278
def test_sample_neighbors_biased_bipartite():
    g = create_test_graph(100, 30, True)
    num_dst = g.number_of_dst_nodes()
    bias = F.tensor([0, 0.01, 10, 10], dtype=F.float32)
1279

1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
    def check_num(nodes, tag):
        nodes, tag = F.asnumpy(nodes), F.asnumpy(tag)
        cnt = [sum(tag[nodes] == i) for i in range(4)]
        # No tag 0
        assert cnt[0] == 0

        # very rare tag 1
        assert cnt[2] > 2 * cnt[1]
        assert cnt[3] > 2 * cnt[1]

    # inedge / without replacement
    tag = F.tensor(np.random.choice(4, 100))
1292
    g_sorted = dgl.sort_csc_by_tag(g, tag)
1293
    for _ in range(5):
1294
1295
1296
        subg = dgl.sampling.sample_neighbors_biased(
            g_sorted, g.dstnodes(), 5, bias, replace=False
        )
1297
1298
1299
        check_num(subg.edges()[0], tag)
        u, v = subg.edges()
        edge_set = set(zip(list(F.asnumpy(u)), list(F.asnumpy(v))))
Hongzhi (Steve), Chen's avatar
Hongzhi (Steve), Chen committed
1300
        assert len(edge_set) == subg.num_edges()
1301
1302
1303

    # inedge / with replacement
    for _ in range(5):
1304
1305
1306
        subg = dgl.sampling.sample_neighbors_biased(
            g_sorted, g.dstnodes(), 5, bias, replace=True
        )
1307
1308
1309
1310
        check_num(subg.edges()[0], tag)

    # outedge / without replacement
    tag = F.tensor(np.random.choice(4, num_dst))
1311
    g_sorted = dgl.sort_csr_by_tag(g, tag)
1312
    for _ in range(5):
1313
1314
1315
        subg = dgl.sampling.sample_neighbors_biased(
            g_sorted, g.srcnodes(), 5, bias, edge_dir="out", replace=False
        )
1316
1317
1318
        check_num(subg.edges()[1], tag)
        u, v = subg.edges()
        edge_set = set(zip(list(F.asnumpy(u)), list(F.asnumpy(v))))
Hongzhi (Steve), Chen's avatar
Hongzhi (Steve), Chen committed
1319
        assert len(edge_set) == subg.num_edges()
1320
1321
1322

    # outedge / with replacement
    for _ in range(5):
1323
1324
1325
        subg = dgl.sampling.sample_neighbors_biased(
            g_sorted, g.srcnodes(), 5, bias, edge_dir="out", replace=True
        )
1326
1327
        check_num(subg.edges()[1], tag)

1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338

@unittest.skipIf(
    F._default_context_str == "gpu",
    reason="GPU sample neighbors not implemented",
)
@unittest.skipIf(
    F.backend_name == "mxnet", reason="MXNet has problem converting bool arrays"
)
@pytest.mark.parametrize("format_", ["coo", "csr", "csc"])
@pytest.mark.parametrize("direction", ["in", "out"])
@pytest.mark.parametrize("replace", [False, True])
1339
def test_sample_neighbors_etype_homogeneous(format_, direction, replace):
1340
1341
1342
    num_nodes = 100
    rare_cnt = 4
    g = create_etype_test_graph(100, 30, rare_cnt)
1343
    h_g = dgl.to_homogeneous(g, edata=["p", "mask"])
1344
1345
    h_g_etype = F.asnumpy(h_g.edata[dgl.ETYPE])
    h_g_offset = np.cumsum(np.insert(np.bincount(h_g_etype), 0, 0)).tolist()
1346
1347
    sg = g.edge_subgraph(g.edata["mask"], relabel_nodes=False)
    h_sg = h_g.edge_subgraph(h_g.edata["mask"], relabel_nodes=False)
1348
1349
1350
    h_sg_etype = F.asnumpy(h_sg.edata[dgl.ETYPE])
    h_sg_offset = np.cumsum(np.insert(np.bincount(h_sg_etype), 0, 0)).tolist()

1351
1352
    seed_ntype = g.get_ntype_id("u")
    seeds = F.nonzero_1d(h_g.ndata[dgl.NTYPE] == seed_ntype)
1353
1354
1355
1356
    fanouts = F.tensor([6, 5, 4, 3, 2], dtype=F.int64)

    def check_num(h_g, all_src, all_dst, subg, replace, fanouts, direction):
        src, dst = subg.edges()
1357
1358
        all_etype_array = F.asnumpy(h_g.edata[dgl.ETYPE])
        num_etypes = all_etype_array.max() + 1
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
        etype_array = F.asnumpy(subg.edata[dgl.ETYPE])
        src = F.asnumpy(src)
        dst = F.asnumpy(dst)
        fanouts = F.asnumpy(fanouts)

        all_src = F.asnumpy(all_src)
        all_dst = F.asnumpy(all_dst)

        src_per_etype = []
        dst_per_etype = []
1369
1370
        all_src_per_etype = []
        all_dst_per_etype = []
1371
1372
1373
        for etype in range(num_etypes):
            src_per_etype.append(src[etype_array == etype])
            dst_per_etype.append(dst[etype_array == etype])
1374
1375
            all_src_per_etype.append(all_src[all_etype_array == etype])
            all_dst_per_etype.append(all_dst[all_etype_array == etype])
1376
1377

        if replace:
1378
            if direction == "in":
1379
                in_degree_per_etype = [np.bincount(d) for d in dst_per_etype]
1380
1381
1382
1383
1384
1385
1386
                for etype in range(len(fanouts)):
                    in_degree = in_degree_per_etype[etype]
                    fanout = fanouts[etype]
                    ans = np.zeros_like(in_degree)
                    if len(in_degree) > 0:
                        ans[all_dst_per_etype[etype]] = fanout
                    assert np.all(in_degree == ans)
1387
            else:
1388
                out_degree_per_etype = [np.bincount(s) for s in src_per_etype]
1389
1390
1391
1392
1393
1394
1395
                for etype in range(len(fanouts)):
                    out_degree = out_degree_per_etype[etype]
                    fanout = fanouts[etype]
                    ans = np.zeros_like(out_degree)
                    if len(out_degree) > 0:
                        ans[all_src_per_etype[etype]] = fanout
                    assert np.all(out_degree == ans)
1396
        else:
1397
            if direction == "in":
1398
1399
1400
1401
1402
1403
1404
1405
                for v in set(dst):
                    u = src[dst == v]
                    et = etype_array[dst == v]
                    all_u = all_src[all_dst == v]
                    all_et = all_etype_array[all_dst == v]
                    for etype in set(et):
                        u_etype = set(u[et == etype])
                        all_u_etype = set(all_u[all_et == etype])
1406
1407
1408
                        assert (len(u_etype) == fanouts[etype]) or (
                            u_etype == all_u_etype
                        )
1409
            else:
1410
1411
1412
1413
1414
1415
1416
1417
                for u in set(src):
                    v = dst[src == u]
                    et = etype_array[src == u]
                    all_v = all_dst[all_src == u]
                    all_et = all_etype_array[all_src == u]
                    for etype in set(et):
                        v_etype = set(v[et == etype])
                        all_v_etype = set(all_v[all_et == etype])
1418
1419
1420
                        assert (len(v_etype) == fanouts[etype]) or (
                            v_etype == all_v_etype
                        )
1421
1422

    all_src, all_dst = h_g.edges()
1423
    all_sub_src, all_sub_dst = h_sg.edges()
1424
    h_g = h_g.formats(format_)
1425
1426
    if (direction, format_) in [("in", "csr"), ("out", "csc")]:
        h_g = h_g.formats(["csc", "csr", "coo"])
1427
1428
    for _ in range(5):
        subg = dgl.sampling.sample_etype_neighbors(
1429
1430
            h_g, seeds, h_g_offset, fanouts, replace=replace, edge_dir=direction
        )
1431
        check_num(h_g, all_src, all_dst, subg, replace, fanouts, direction)
1432

1433
        p = [g.edges[etype].data["p"] for etype in g.etypes]
1434
        subg = dgl.sampling.sample_etype_neighbors(
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
            h_g,
            seeds,
            h_g_offset,
            fanouts,
            replace=replace,
            edge_dir=direction,
            prob=p,
        )
        check_num(
            h_sg, all_sub_src, all_sub_dst, subg, replace, fanouts, direction
        )

        p = [g.edges[etype].data["mask"] for etype in g.etypes]
1448
        subg = dgl.sampling.sample_etype_neighbors(
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
            h_g,
            seeds,
            h_g_offset,
            fanouts,
            replace=replace,
            edge_dir=direction,
            prob=p,
        )
        check_num(
            h_sg, all_sub_src, all_sub_dst, subg, replace, fanouts, direction
        )


@unittest.skipIf(
    F._default_context_str == "gpu",
    reason="GPU sample neighbors not implemented",
)
@unittest.skipIf(
    F.backend_name == "mxnet", reason="MXNet has problem converting bool arrays"
)
@pytest.mark.parametrize("format_", ["csr", "csc"])
@pytest.mark.parametrize("direction", ["in", "out"])
1471
1472
1473
1474
1475
1476
def test_sample_neighbors_etype_sorted_homogeneous(format_, direction):
    rare_cnt = 4
    g = create_etype_test_graph(100, 30, rare_cnt)
    h_g = dgl.to_homogeneous(g)
    seed_ntype = g.get_ntype_id("u")
    seeds = F.nonzero_1d(h_g.ndata[dgl.NTYPE] == seed_ntype)
1477
    fanouts = F.tensor([6, 5, -1, 3, 2], dtype=F.int64)
1478
    h_g = h_g.formats(format_)
1479
1480
    if (direction, format_) in [("in", "csr"), ("out", "csc")]:
        h_g = h_g.formats(["csc", "csr", "coo"])
1481

1482
1483
    if direction == "in":
        h_g = dgl.sort_csc_by_tag(h_g, h_g.edata[dgl.ETYPE], tag_type="edge")
1484
    else:
1485
        h_g = dgl.sort_csr_by_tag(h_g, h_g.edata[dgl.ETYPE], tag_type="edge")
1486
1487
1488
1489
    # shuffle
    h_g_etype = F.asnumpy(h_g.edata[dgl.ETYPE])
    h_g_offset = np.cumsum(np.insert(np.bincount(h_g_etype), 0, 0)).tolist()
    sg = dgl.sampling.sample_etype_neighbors(
1490
1491
        h_g, seeds, h_g_offset, fanouts, edge_dir=direction, etype_sorted=True
    )
1492

1493
1494

@pytest.mark.parametrize("dtype", ["int32", "int64"])
1495
def test_sample_neighbors_exclude_edges_heteroG(dtype):
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
    d_i_d_u_nodes = F.zerocopy_from_numpy(
        np.unique(np.random.randint(300, size=100, dtype=dtype))
    )
    d_i_d_v_nodes = F.zerocopy_from_numpy(
        np.random.randint(25, size=d_i_d_u_nodes.shape, dtype=dtype)
    )
    d_i_g_u_nodes = F.zerocopy_from_numpy(
        np.unique(np.random.randint(300, size=100, dtype=dtype))
    )
    d_i_g_v_nodes = F.zerocopy_from_numpy(
        np.random.randint(25, size=d_i_g_u_nodes.shape, dtype=dtype)
    )
    d_t_d_u_nodes = F.zerocopy_from_numpy(
        np.unique(np.random.randint(300, size=100, dtype=dtype))
    )
    d_t_d_v_nodes = F.zerocopy_from_numpy(
        np.random.randint(25, size=d_t_d_u_nodes.shape, dtype=dtype)
    )

    g = dgl.heterograph(
        {
            ("drug", "interacts", "drug"): (d_i_d_u_nodes, d_i_d_v_nodes),
            ("drug", "interacts", "gene"): (d_i_g_u_nodes, d_i_g_v_nodes),
            ("drug", "treats", "disease"): (d_t_d_u_nodes, d_t_d_v_nodes),
        }
    ).to(F.ctx())
1522
1523
1524
1525
1526
1527
1528
1529
1530

    (U, V, EID) = (0, 1, 2)

    nd_b_idx = np.random.randint(low=1, high=24, dtype=dtype)
    nd_e_idx = np.random.randint(low=25, high=49, dtype=dtype)
    did_b_idx = np.random.randint(low=1, high=24, dtype=dtype)
    did_e_idx = np.random.randint(low=25, high=49, dtype=dtype)
    sampled_amount = np.random.randint(low=1, high=10, dtype=dtype)

1531
1532
1533
    drug_i_drug_edges = g.all_edges(
        form="all", etype=("drug", "interacts", "drug")
    )
1534
1535
1536
1537
1538
1539
1540
1541
1542
    excluded_d_i_d_edges = drug_i_drug_edges[EID][did_b_idx:did_e_idx]
    sampled_drug_node = drug_i_drug_edges[V][nd_b_idx:nd_e_idx]
    did_excluded_nodes_U = drug_i_drug_edges[U][did_b_idx:did_e_idx]
    did_excluded_nodes_V = drug_i_drug_edges[V][did_b_idx:did_e_idx]

    nd_b_idx = np.random.randint(low=1, high=24, dtype=dtype)
    nd_e_idx = np.random.randint(low=25, high=49, dtype=dtype)
    dig_b_idx = np.random.randint(low=1, high=24, dtype=dtype)
    dig_e_idx = np.random.randint(low=25, high=49, dtype=dtype)
1543
1544
1545
    drug_i_gene_edges = g.all_edges(
        form="all", etype=("drug", "interacts", "gene")
    )
1546
1547
1548
1549
1550
1551
1552
1553
1554
    excluded_d_i_g_edges = drug_i_gene_edges[EID][dig_b_idx:dig_e_idx]
    dig_excluded_nodes_U = drug_i_gene_edges[U][dig_b_idx:dig_e_idx]
    dig_excluded_nodes_V = drug_i_gene_edges[V][dig_b_idx:dig_e_idx]
    sampled_gene_node = drug_i_gene_edges[V][nd_b_idx:nd_e_idx]

    nd_b_idx = np.random.randint(low=1, high=24, dtype=dtype)
    nd_e_idx = np.random.randint(low=25, high=49, dtype=dtype)
    dtd_b_idx = np.random.randint(low=1, high=24, dtype=dtype)
    dtd_e_idx = np.random.randint(low=25, high=49, dtype=dtype)
1555
1556
1557
    drug_t_dis_edges = g.all_edges(
        form="all", etype=("drug", "treats", "disease")
    )
1558
1559
1560
1561
    excluded_d_t_d_edges = drug_t_dis_edges[EID][dtd_b_idx:dtd_e_idx]
    dtd_excluded_nodes_U = drug_t_dis_edges[U][dtd_b_idx:dtd_e_idx]
    dtd_excluded_nodes_V = drug_t_dis_edges[V][dtd_b_idx:dtd_e_idx]
    sampled_disease_node = drug_t_dis_edges[V][nd_b_idx:nd_e_idx]
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
    excluded_edges = {
        ("drug", "interacts", "drug"): excluded_d_i_d_edges,
        ("drug", "interacts", "gene"): excluded_d_i_g_edges,
        ("drug", "treats", "disease"): excluded_d_t_d_edges,
    }

    sg = dgl.sampling.sample_neighbors(
        g,
        {
            "drug": sampled_drug_node,
            "gene": sampled_gene_node,
            "disease": sampled_disease_node,
        },
        sampled_amount,
        exclude_edges=excluded_edges,
    )

    assert not np.any(
        F.asnumpy(
            sg.has_edges_between(
                did_excluded_nodes_U,
                did_excluded_nodes_V,
                etype=("drug", "interacts", "drug"),
            )
        )
    )
    assert not np.any(
        F.asnumpy(
            sg.has_edges_between(
                dig_excluded_nodes_U,
                dig_excluded_nodes_V,
                etype=("drug", "interacts", "gene"),
            )
        )
    )
    assert not np.any(
        F.asnumpy(
            sg.has_edges_between(
                dtd_excluded_nodes_U,
                dtd_excluded_nodes_V,
                etype=("drug", "treats", "disease"),
            )
        )
    )


@pytest.mark.parametrize("dtype", ["int32", "int64"])
1609
def test_sample_neighbors_exclude_edges_homoG(dtype):
1610
1611
1612
1613
1614
1615
    u_nodes = F.zerocopy_from_numpy(
        np.unique(np.random.randint(300, size=100, dtype=dtype))
    )
    v_nodes = F.zerocopy_from_numpy(
        np.random.randint(25, size=u_nodes.shape, dtype=dtype)
    )
1616
    g = dgl.graph((u_nodes, v_nodes)).to(F.ctx())
1617
1618
1619

    (U, V, EID) = (0, 1, 2)

1620
1621
1622
1623
1624
    nd_b_idx = np.random.randint(low=1, high=24, dtype=dtype)
    nd_e_idx = np.random.randint(low=25, high=49, dtype=dtype)
    b_idx = np.random.randint(low=1, high=24, dtype=dtype)
    e_idx = np.random.randint(low=25, high=49, dtype=dtype)
    sampled_amount = np.random.randint(low=1, high=10, dtype=dtype)
1625

1626
    g_edges = g.all_edges(form="all")
1627
1628
1629
1630
1631
    excluded_edges = g_edges[EID][b_idx:e_idx]
    sampled_node = g_edges[V][nd_b_idx:nd_e_idx]
    excluded_nodes_U = g_edges[U][b_idx:e_idx]
    excluded_nodes_V = g_edges[V][b_idx:e_idx]

1632
1633
1634
1635
1636
1637
1638
    sg = dgl.sampling.sample_neighbors(
        g, sampled_node, sampled_amount, exclude_edges=excluded_edges
    )

    assert not np.any(
        F.asnumpy(sg.has_edges_between(excluded_nodes_U, excluded_nodes_V))
    )
1639
1640


1641
@pytest.mark.parametrize("dtype", ["int32", "int64"])
1642
def test_global_uniform_negative_sampling(dtype):
1643
    g = dgl.graph(([], []), num_nodes=1000).to(F.ctx())
1644
1645
1646
    src, dst = dgl.sampling.global_uniform_negative_sampling(
        g, 2000, False, True
    )
1647
1648
    assert len(src) == 2000
    assert len(dst) == 2000
1649

1650
1651
1652
    g = dgl.graph(
        (np.random.randint(0, 20, (300,)), np.random.randint(0, 20, (300,)))
    ).to(F.ctx())
1653
1654
1655
    src, dst = dgl.sampling.global_uniform_negative_sampling(g, 20, False, True)
    assert not F.asnumpy(g.has_edges_between(src, dst)).any()

1656
1657
1658
    src, dst = dgl.sampling.global_uniform_negative_sampling(
        g, 20, False, False
    )
1659
1660
1661
1662
1663
1664
1665
    assert not F.asnumpy(g.has_edges_between(src, dst)).any()
    src = F.asnumpy(src)
    dst = F.asnumpy(dst)
    s = set(zip(src.tolist(), dst.tolist()))
    assert len(s) == len(src)

    g = dgl.graph(([0], [1])).to(F.ctx())
1666
1667
1668
    src, dst = dgl.sampling.global_uniform_negative_sampling(
        g, 20, True, False, redundancy=10
    )
1669
1670
1671
1672
1673
1674
1675
1676
1677
    src = F.asnumpy(src)
    dst = F.asnumpy(dst)
    # should have either no element or (1, 0)
    assert len(src) < 2
    assert len(dst) < 2
    if len(src) == 1:
        assert src[0] == 1
        assert dst[0] == 0

1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
    g = dgl.heterograph(
        {
            ("A", "AB", "B"): (
                np.random.randint(0, 20, (300,)),
                np.random.randint(0, 40, (300,)),
            ),
            ("B", "BA", "A"): (
                np.random.randint(0, 40, (200,)),
                np.random.randint(0, 20, (200,)),
            ),
        }
    ).to(F.ctx())
    src, dst = dgl.sampling.global_uniform_negative_sampling(
        g, 20, False, etype="AB"
    )
    assert not F.asnumpy(g.has_edges_between(src, dst, etype="AB")).any()
1694

1695

1696
if __name__ == "__main__":
1697
    from itertools import product
1698

1699
    test_sample_neighbors_noprob()
1700
    test_sample_labors_noprob()
1701
    test_sample_neighbors_prob()
1702
    test_sample_labors_prob()
1703
    test_sample_neighbors_mask()
1704
    for args in product(["coo", "csr", "csc"], ["in", "out"], [False, True]):
1705
        test_sample_neighbors_etype_homogeneous(*args)
1706
    for args in product(["csr", "csc"], ["in", "out"]):
1707
        test_sample_neighbors_etype_sorted_homogeneous(*args)
1708
    test_non_uniform_random_walk(False)
1709
    test_uniform_random_walk(False)
1710
    test_pack_traces()
1711
    test_pinsage_sampling(False)
1712
1713
1714
    test_sample_neighbors_outedge()
    test_sample_neighbors_topk()
    test_sample_neighbors_topk_outedge()
1715
    test_sample_neighbors_with_0deg()
1716
1717
    test_sample_neighbors_biased_homogeneous()
    test_sample_neighbors_biased_bipartite()
1718
1719
1720
1721
    test_sample_neighbors_exclude_edges_heteroG("int32")
    test_sample_neighbors_exclude_edges_homoG("int32")
    test_global_uniform_negative_sampling("int32")
    test_global_uniform_negative_sampling("int64")