"src/git@developer.sourcefind.cn:OpenDAS/dgl.git" did not exist on "7e30382e4fe2512b03ff0e675ab76505717a72e3"
test_sampling.py 55.4 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

def _test_sample_neighbors_outedge(hypersparse):
    g, hg = _gen_neighbor_sampling_test_graph(hypersparse, True)

    def _test1(p, replace):
688
689
690
        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
691
        assert subg.num_nodes() == g.num_nodes()
692
        u, v = subg.edges()
693
        u_ans, v_ans, e_ans = g.out_edges([0, 1], form="all")
694
695
        if p is not None:
            emask = F.gather_row(g.edata[p], e_ans)
696
697
            if p == "prob":
                emask = emask != 0
698
699
            u_ans = F.boolean_mask(u_ans, emask)
            v_ans = F.boolean_mask(v_ans, emask)
700
701
702
703
        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

704
        for i in range(10):
705
706
707
            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
708
709
            assert subg.num_nodes() == g.num_nodes()
            assert subg.num_edges() == 4
710
711
            u, v = subg.edges()
            assert set(F.asnumpy(F.unique(u))) == {0, 1}
712
713
714
715
            assert F.array_equal(
                F.astype(g.has_edges_between(u, v), F.int64),
                F.ones((4,), dtype=F.int64),
            )
716
717
718
719
720
721
722
723
            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
724
725

    _test1(None, True)  # w/ replacement, uniform
726
    _test1(None, False)  # w/o replacement, uniform
727
728
    _test1("prob", True)  # w/ replacement
    _test1("prob", False)  # w/o replacement
729
730

    def _test2(p, replace):  # fanout > #neighbors
731
732
733
        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
734
        assert subg.num_nodes() == g.num_nodes()
735
        u, v = subg.edges()
736
        u_ans, v_ans, e_ans = g.out_edges([0, 2], form="all")
737
738
        if p is not None:
            emask = F.gather_row(g.edata[p], e_ans)
739
740
            if p == "prob":
                emask = emask != 0
741
742
            u_ans = F.boolean_mask(u_ans, emask)
            v_ans = F.boolean_mask(v_ans, emask)
743
744
745
746
        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

747
        for i in range(10):
748
749
750
            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
751
            assert subg.num_nodes() == g.num_nodes()
752
            num_edges = 4 if replace else 3
Hongzhi (Steve), Chen's avatar
Hongzhi (Steve), Chen committed
753
            assert subg.num_edges() == num_edges
754
755
            u, v = subg.edges()
            assert set(F.asnumpy(F.unique(u))) == {0, 2}
756
757
758
759
            assert F.array_equal(
                F.astype(g.has_edges_between(u, v), F.int64),
                F.ones((num_edges,), dtype=F.int64),
            )
760
761
762
763
764
765
766
            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
767
768

    _test2(None, True)  # w/ replacement, uniform
769
    _test2(None, False)  # w/o replacement, uniform
770
771
    _test2("prob", True)  # w/ replacement
    _test2("prob", False)  # w/o replacement
772
773

    def _test3(p, replace):
774
775
776
777
778
779
780
781
        subg = dgl.sampling.sample_neighbors(
            hg,
            {"user": [0, 1], "game": 0},
            -1,
            prob=p,
            replace=replace,
            edge_dir="out",
        )
782
783
        assert len(subg.ntypes) == 3
        assert len(subg.etypes) == 4
Hongzhi (Steve), Chen's avatar
Hongzhi (Steve), Chen committed
784
785
786
787
        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
788

789
        for i in range(10):
790
791
792
793
794
795
796
797
            subg = dgl.sampling.sample_neighbors(
                hg,
                {"user": [0, 1], "game": 0},
                2,
                prob=p,
                replace=replace,
                edge_dir="out",
            )
798
799
            assert len(subg.ntypes) == 3
            assert len(subg.etypes) == 4
Hongzhi (Steve), Chen's avatar
Hongzhi (Steve), Chen committed
800
801
802
803
            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
804

805
    _test3(None, True)  # w/ replacement, uniform
806
    _test3(None, False)  # w/o replacement, uniform
807
808
809
    _test3("prob", True)  # w/ replacement
    _test3("prob", False)  # w/o replacement

810
811
812
813
814

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

    def _test1():
815
        subg = dgl.sampling.select_topk(g, -1, "weight", [0, 1])
Hongzhi (Steve), Chen's avatar
Hongzhi (Steve), Chen committed
816
        assert subg.num_nodes() == g.num_nodes()
817
818
819
820
821
822
        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

823
        subg = dgl.sampling.select_topk(g, 2, "weight", [0, 1])
Hongzhi (Steve), Chen's avatar
Hongzhi (Steve), Chen committed
824
825
        assert subg.num_nodes() == g.num_nodes()
        assert subg.num_edges() == 4
826
827
828
        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])
829
830
        assert edge_set == {(2, 0), (1, 0), (2, 1), (3, 1)}

831
832
833
    _test1()

    def _test2():  # k > #neighbors
834
        subg = dgl.sampling.select_topk(g, -1, "weight", [0, 2])
Hongzhi (Steve), Chen's avatar
Hongzhi (Steve), Chen committed
835
        assert subg.num_nodes() == g.num_nodes()
836
837
838
839
840
841
        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

842
        subg = dgl.sampling.select_topk(g, 2, "weight", [0, 2])
Hongzhi (Steve), Chen's avatar
Hongzhi (Steve), Chen committed
843
844
        assert subg.num_nodes() == g.num_nodes()
        assert subg.num_edges() == 3
845
846
847
        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))))
848
849
        assert edge_set == {(2, 0), (1, 0), (0, 2)}

850
851
852
    _test2()

    def _test3():
853
854
855
        subg = dgl.sampling.select_topk(
            hg, 2, "weight", {"user": [0, 1], "game": 0}
        )
856
857
        assert len(subg.ntypes) == 3
        assert len(subg.etypes) == 4
858
        u, v = subg["follow"].edges()
859
        edge_set = set(zip(list(F.asnumpy(u)), list(F.asnumpy(v))))
860
861
862
863
864
        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()
865
        edge_set = set(zip(list(F.asnumpy(u)), list(F.asnumpy(v))))
866
867
868
869
870
        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()
871
        edge_set = set(zip(list(F.asnumpy(u)), list(F.asnumpy(v))))
872
873
874
875
        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
876
        assert subg["flips"].num_edges() == 0
877

878
879
880
    _test3()

    # test different k for different relations
881
    subg = dgl.sampling.select_topk(
882
883
884
885
886
        hg,
        {"follow": 1, "play": 2, "liked-by": 0, "flips": -1},
        "weight",
        {"user": [0, 1], "game": 0, "coin": 0},
    )
887
888
    assert len(subg.ntypes) == 3
    assert len(subg.etypes) == 4
Hongzhi (Steve), Chen's avatar
Hongzhi (Steve), Chen committed
889
890
891
892
    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
893

894
895
896
897
898

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

    def _test1():
899
        subg = dgl.sampling.select_topk(g, -1, "weight", [0, 1], edge_dir="out")
Hongzhi (Steve), Chen's avatar
Hongzhi (Steve), Chen committed
900
        assert subg.num_nodes() == g.num_nodes()
901
902
903
904
905
906
        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

907
        subg = dgl.sampling.select_topk(g, 2, "weight", [0, 1], edge_dir="out")
Hongzhi (Steve), Chen's avatar
Hongzhi (Steve), Chen committed
908
909
        assert subg.num_nodes() == g.num_nodes()
        assert subg.num_edges() == 4
910
911
912
        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])
913
914
        assert edge_set == {(0, 2), (0, 1), (1, 2), (1, 3)}

915
916
917
    _test1()

    def _test2():  # k > #neighbors
918
        subg = dgl.sampling.select_topk(g, -1, "weight", [0, 2], edge_dir="out")
Hongzhi (Steve), Chen's avatar
Hongzhi (Steve), Chen committed
919
        assert subg.num_nodes() == g.num_nodes()
920
921
922
923
924
925
        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

926
        subg = dgl.sampling.select_topk(g, 2, "weight", [0, 2], edge_dir="out")
Hongzhi (Steve), Chen's avatar
Hongzhi (Steve), Chen committed
927
928
        assert subg.num_nodes() == g.num_nodes()
        assert subg.num_edges() == 3
929
930
931
        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])
932
933
        assert edge_set == {(0, 2), (0, 1), (2, 0)}

934
935
936
    _test2()

    def _test3():
937
938
939
        subg = dgl.sampling.select_topk(
            hg, 2, "weight", {"user": [0, 1], "game": 0}, edge_dir="out"
        )
940
941
        assert len(subg.ntypes) == 3
        assert len(subg.etypes) == 4
942
        u, v = subg["follow"].edges()
943
        edge_set = set(zip(list(F.asnumpy(u)), list(F.asnumpy(v))))
944
945
946
947
948
        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()
949
        edge_set = set(zip(list(F.asnumpy(u)), list(F.asnumpy(v))))
950
951
952
953
954
        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()
955
        edge_set = set(zip(list(F.asnumpy(u)), list(F.asnumpy(v))))
956
957
958
959
        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
960
        assert subg["flips"].num_edges() == 0
961

962
963
    _test3()

964

965
966
def test_sample_neighbors_noprob():
    _test_sample_neighbors(False, None)
967
968
    # _test_sample_neighbors(True)

969
970

def test_sample_neighbors_prob():
971
972
973
    _test_sample_neighbors(False, "prob")
    # _test_sample_neighbors(True)

974
975
976

def test_sample_neighbors_outedge():
    _test_sample_neighbors_outedge(False)
977
978
    # _test_sample_neighbors_outedge(True)

979

980
981
982
983
984
985
986
@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",
)
987
def test_sample_neighbors_mask():
988
    _test_sample_neighbors(False, "mask")
989

990
991
992
993
994

@unittest.skipIf(
    F._default_context_str == "gpu",
    reason="GPU sample neighbors not implemented",
)
995
996
def test_sample_neighbors_topk():
    _test_sample_neighbors_topk(False)
997
998
    # _test_sample_neighbors_topk(True)

999

1000
1001
1002
1003
@unittest.skipIf(
    F._default_context_str == "gpu",
    reason="GPU sample neighbors not implemented",
)
1004
1005
def test_sample_neighbors_topk_outedge():
    _test_sample_neighbors_topk_outedge(False)
1006
1007
    # _test_sample_neighbors_topk_outedge(True)

1008

1009
def test_sample_neighbors_with_0deg():
1010
    g = dgl.graph(([], []), num_nodes=5).to(F.ctx())
1011
1012
1013
    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
1014
    assert sg.num_edges() == 0
1015
1016
1017
    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
1018
    assert sg.num_edges() == 0
1019
1020
1021
    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
1022
    assert sg.num_edges() == 0
1023
1024
1025
    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
1026
    assert sg.num_edges() == 0
1027

1028

1029
1030
def create_test_graph(num_nodes, num_edges_per_node, bipartite=False):
    src = np.concatenate(
1031
1032
        [np.array([i] * num_edges_per_node) for i in range(num_nodes)]
    )
1033
    dst = np.concatenate(
1034
1035
1036
1037
        [
            np.random.choice(num_nodes, num_edges_per_node, replace=False)
            for i in range(num_nodes)
        ]
1038
1039
    )
    if bipartite:
1040
        g = dgl.heterograph({("u", "e", "v"): (src, dst)})
1041
1042
1043
1044
    else:
        g = dgl.graph((src, dst))
    return g

1045

1046
1047
def create_etype_test_graph(num_nodes, num_edges_per_node, rare_cnt):
    src = np.concatenate(
1048
1049
1050
1051
        [
            np.random.choice(num_nodes, num_edges_per_node, replace=False)
            for i in range(num_nodes)
        ]
1052
1053
    )
    dst = np.concatenate(
1054
1055
        [np.array([i] * num_edges_per_node) for i in range(num_nodes)]
    )
1056
1057

    minor_src = np.concatenate(
1058
1059
1060
1061
        [
            np.random.choice(num_nodes, 2, replace=False)
            for i in range(num_nodes)
        ]
1062
    )
1063
    minor_dst = np.concatenate([np.array([i] * 2) for i in range(num_nodes)])
1064
1065

    most_zero_src = np.concatenate(
1066
1067
1068
1069
        [
            np.random.choice(num_nodes, num_edges_per_node, replace=False)
            for i in range(rare_cnt)
        ]
1070
1071
    )
    most_zero_dst = np.concatenate(
1072
1073
        [np.array([i] * num_edges_per_node) for i in range(rare_cnt)]
    )
1074

1075
1076
1077
1078
1079
1080
1081
1082
1083
    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),
        }
    )
1084
1085
1086
    for etype in g.etypes:
        prob = np.random.rand(g.num_edges(etype))
        prob[prob > 0.2] = 0
1087
1088
        g.edges[etype].data["p"] = F.zerocopy_from_numpy(prob)
        g.edges[etype].data["mask"] = F.zerocopy_from_numpy(prob != 0)
1089
1090
1091

    return g

1092
1093
1094
1095
1096

@unittest.skipIf(
    F._default_context_str == "gpu",
    reason="GPU sample neighbors not implemented",
)
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
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
1113
    g_sorted = dgl.sort_csc_by_tag(g, tag)
1114
    for _ in range(5):
1115
1116
1117
        subg = dgl.sampling.sample_neighbors_biased(
            g_sorted, g.nodes(), 5, bias, replace=False
        )
1118
1119
1120
        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
1121
        assert len(edge_set) == subg.num_edges()
1122
1123
1124

    # inedge / with replacement
    for _ in range(5):
1125
1126
1127
        subg = dgl.sampling.sample_neighbors_biased(
            g_sorted, g.nodes(), 5, bias, replace=True
        )
1128
1129
1130
        check_num(subg.edges()[0], tag)

    # outedge / without replacement
1131
    g_sorted = dgl.sort_csr_by_tag(g, tag)
1132
    for _ in range(5):
1133
1134
1135
        subg = dgl.sampling.sample_neighbors_biased(
            g_sorted, g.nodes(), 5, bias, edge_dir="out", replace=False
        )
1136
1137
1138
        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
1139
        assert len(edge_set) == subg.num_edges()
1140
1141
1142

    # outedge / with replacement
    for _ in range(5):
1143
1144
1145
        subg = dgl.sampling.sample_neighbors_biased(
            g_sorted, g.nodes(), 5, bias, edge_dir="out", replace=True
        )
1146
1147
        check_num(subg.edges()[1], tag)

1148
1149
1150
1151
1152

@unittest.skipIf(
    F._default_context_str == "gpu",
    reason="GPU sample neighbors not implemented",
)
1153
1154
1155
1156
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)
1157

1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
    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))
1170
    g_sorted = dgl.sort_csc_by_tag(g, tag)
1171
    for _ in range(5):
1172
1173
1174
        subg = dgl.sampling.sample_neighbors_biased(
            g_sorted, g.dstnodes(), 5, bias, replace=False
        )
1175
1176
1177
        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
1178
        assert len(edge_set) == subg.num_edges()
1179
1180
1181

    # inedge / with replacement
    for _ in range(5):
1182
1183
1184
        subg = dgl.sampling.sample_neighbors_biased(
            g_sorted, g.dstnodes(), 5, bias, replace=True
        )
1185
1186
1187
1188
        check_num(subg.edges()[0], tag)

    # outedge / without replacement
    tag = F.tensor(np.random.choice(4, num_dst))
1189
    g_sorted = dgl.sort_csr_by_tag(g, tag)
1190
    for _ in range(5):
1191
1192
1193
        subg = dgl.sampling.sample_neighbors_biased(
            g_sorted, g.srcnodes(), 5, bias, edge_dir="out", replace=False
        )
1194
1195
1196
        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
1197
        assert len(edge_set) == subg.num_edges()
1198
1199
1200

    # outedge / with replacement
    for _ in range(5):
1201
1202
1203
        subg = dgl.sampling.sample_neighbors_biased(
            g_sorted, g.srcnodes(), 5, bias, edge_dir="out", replace=True
        )
1204
1205
        check_num(subg.edges()[1], tag)

1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216

@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])
1217
def test_sample_neighbors_etype_homogeneous(format_, direction, replace):
1218
1219
1220
    num_nodes = 100
    rare_cnt = 4
    g = create_etype_test_graph(100, 30, rare_cnt)
1221
    h_g = dgl.to_homogeneous(g, edata=["p", "mask"])
1222
1223
    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()
1224
1225
    sg = g.edge_subgraph(g.edata["mask"], relabel_nodes=False)
    h_sg = h_g.edge_subgraph(h_g.edata["mask"], relabel_nodes=False)
1226
1227
1228
    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()

1229
1230
    seed_ntype = g.get_ntype_id("u")
    seeds = F.nonzero_1d(h_g.ndata[dgl.NTYPE] == seed_ntype)
1231
1232
1233
1234
    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()
1235
1236
        all_etype_array = F.asnumpy(h_g.edata[dgl.ETYPE])
        num_etypes = all_etype_array.max() + 1
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
        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 = []
1247
1248
        all_src_per_etype = []
        all_dst_per_etype = []
1249
1250
1251
        for etype in range(num_etypes):
            src_per_etype.append(src[etype_array == etype])
            dst_per_etype.append(dst[etype_array == etype])
1252
1253
            all_src_per_etype.append(all_src[all_etype_array == etype])
            all_dst_per_etype.append(all_dst[all_etype_array == etype])
1254
1255

        if replace:
1256
            if direction == "in":
1257
                in_degree_per_etype = [np.bincount(d) for d in dst_per_etype]
1258
1259
1260
1261
1262
1263
1264
                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)
1265
            else:
1266
                out_degree_per_etype = [np.bincount(s) for s in src_per_etype]
1267
1268
1269
1270
1271
1272
1273
                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)
1274
        else:
1275
            if direction == "in":
1276
1277
1278
1279
1280
1281
1282
1283
                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])
1284
1285
1286
                        assert (len(u_etype) == fanouts[etype]) or (
                            u_etype == all_u_etype
                        )
1287
            else:
1288
1289
1290
1291
1292
1293
1294
1295
                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])
1296
1297
1298
                        assert (len(v_etype) == fanouts[etype]) or (
                            v_etype == all_v_etype
                        )
1299
1300

    all_src, all_dst = h_g.edges()
1301
    all_sub_src, all_sub_dst = h_sg.edges()
1302
    h_g = h_g.formats(format_)
1303
1304
    if (direction, format_) in [("in", "csr"), ("out", "csc")]:
        h_g = h_g.formats(["csc", "csr", "coo"])
1305
1306
    for _ in range(5):
        subg = dgl.sampling.sample_etype_neighbors(
1307
1308
            h_g, seeds, h_g_offset, fanouts, replace=replace, edge_dir=direction
        )
1309
        check_num(h_g, all_src, all_dst, subg, replace, fanouts, direction)
1310

1311
        p = [g.edges[etype].data["p"] for etype in g.etypes]
1312
        subg = dgl.sampling.sample_etype_neighbors(
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
            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]
1326
        subg = dgl.sampling.sample_etype_neighbors(
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
            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"])
1349
1350
1351
1352
1353
1354
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)
1355
    fanouts = F.tensor([6, 5, -1, 3, 2], dtype=F.int64)
1356
    h_g = h_g.formats(format_)
1357
1358
    if (direction, format_) in [("in", "csr"), ("out", "csc")]:
        h_g = h_g.formats(["csc", "csr", "coo"])
1359

1360
1361
    if direction == "in":
        h_g = dgl.sort_csc_by_tag(h_g, h_g.edata[dgl.ETYPE], tag_type="edge")
1362
    else:
1363
        h_g = dgl.sort_csr_by_tag(h_g, h_g.edata[dgl.ETYPE], tag_type="edge")
1364
1365
1366
1367
    # 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(
1368
1369
        h_g, seeds, h_g_offset, fanouts, edge_dir=direction, etype_sorted=True
    )
1370

1371
1372

@pytest.mark.parametrize("dtype", ["int32", "int64"])
1373
def test_sample_neighbors_exclude_edges_heteroG(dtype):
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
    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())
1400
1401
1402
1403
1404
1405
1406
1407
1408

    (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)

1409
1410
1411
    drug_i_drug_edges = g.all_edges(
        form="all", etype=("drug", "interacts", "drug")
    )
1412
1413
1414
1415
1416
1417
1418
1419
1420
    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)
1421
1422
1423
    drug_i_gene_edges = g.all_edges(
        form="all", etype=("drug", "interacts", "gene")
    )
1424
1425
1426
1427
1428
1429
1430
1431
1432
    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)
1433
1434
1435
    drug_t_dis_edges = g.all_edges(
        form="all", etype=("drug", "treats", "disease")
    )
1436
1437
1438
1439
    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]
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
    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"])
1487
def test_sample_neighbors_exclude_edges_homoG(dtype):
1488
1489
1490
1491
1492
1493
    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)
    )
1494
    g = dgl.graph((u_nodes, v_nodes)).to(F.ctx())
1495
1496
1497

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

1498
1499
1500
1501
1502
    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)
1503

1504
    g_edges = g.all_edges(form="all")
1505
1506
1507
1508
1509
    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]

1510
1511
1512
1513
1514
1515
1516
    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))
    )
1517
1518


1519
@pytest.mark.parametrize("dtype", ["int32", "int64"])
1520
def test_global_uniform_negative_sampling(dtype):
1521
    g = dgl.graph(([], []), num_nodes=1000).to(F.ctx())
1522
1523
1524
    src, dst = dgl.sampling.global_uniform_negative_sampling(
        g, 2000, False, True
    )
1525
1526
    assert len(src) == 2000
    assert len(dst) == 2000
1527

1528
1529
1530
    g = dgl.graph(
        (np.random.randint(0, 20, (300,)), np.random.randint(0, 20, (300,)))
    ).to(F.ctx())
1531
1532
1533
    src, dst = dgl.sampling.global_uniform_negative_sampling(g, 20, False, True)
    assert not F.asnumpy(g.has_edges_between(src, dst)).any()

1534
1535
1536
    src, dst = dgl.sampling.global_uniform_negative_sampling(
        g, 20, False, False
    )
1537
1538
1539
1540
1541
1542
1543
    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())
1544
1545
1546
    src, dst = dgl.sampling.global_uniform_negative_sampling(
        g, 20, True, False, redundancy=10
    )
1547
1548
1549
1550
1551
1552
1553
1554
1555
    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

1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
    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()
1572

1573

1574
if __name__ == "__main__":
1575
    from itertools import product
1576

1577
1578
1579
    test_sample_neighbors_noprob()
    test_sample_neighbors_prob()
    test_sample_neighbors_mask()
1580
    for args in product(["coo", "csr", "csc"], ["in", "out"], [False, True]):
1581
        test_sample_neighbors_etype_homogeneous(*args)
1582
    for args in product(["csr", "csc"], ["in", "out"]):
1583
        test_sample_neighbors_etype_sorted_homogeneous(*args)
1584
    test_non_uniform_random_walk(False)
1585
    test_uniform_random_walk(False)
1586
    test_pack_traces()
1587
    test_pinsage_sampling(False)
1588
1589
1590
    test_sample_neighbors_outedge()
    test_sample_neighbors_topk()
    test_sample_neighbors_topk_outedge()
1591
    test_sample_neighbors_with_0deg()
1592
1593
    test_sample_neighbors_biased_homogeneous()
    test_sample_neighbors_biased_bipartite()
1594
1595
1596
1597
    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")