test_function.py 2.18 KB
Newer Older
1
2
import dgl
import dgl.function as fn
3
import backend as F
4
5
6

def generate_graph():
    g = dgl.DGLGraph()
Minjie Wang's avatar
Minjie Wang committed
7
    g.add_nodes(10) # 10 nodes.
8
    h = F.astype(F.arange(1, 11), F.float32)
9
    g.ndata['h'] = h
10
11
12
13
14
15
    # create a graph where 0 is the source and 9 is the sink
    for i in range(1, 9):
        g.add_edge(0, i)
        g.add_edge(i, 9)
    # add a back flow from 9 to 0
    g.add_edge(9, 0)
16
    h = F.tensor([1., 2., 1., 3., 1., 4., 1., 5., 1., 6.,\
17
            1., 7., 1., 8., 1., 9., 10.])
18
    g.edata['h'] = h
19
20
    return g

21
def reducer_both(nodes):
22
    return {'out' : F.sum(nodes.mailbox['m'], 1)}
23
24
25
26

def test_copy_src():
    # copy_src with both fields
    g = generate_graph()
Minjie Wang's avatar
Minjie Wang committed
27
28
    g.register_message_func(fn.copy_src(src='h', out='m'))
    g.register_reduce_func(reducer_both)
29
    # test with update_all
30
    g.update_all()
31
32
33
34
35
36
    assert F.allclose(g.ndata.pop('out'),
            F.tensor([10., 1., 1., 1., 1., 1., 1., 1., 1., 44.]))
    # test with send and then recv
    g.send()
    g.recv()
    assert F.allclose(g.ndata.pop('out'),
37
            F.tensor([10., 1., 1., 1., 1., 1., 1., 1., 1., 44.]))
38
39
40
41

def test_copy_edge():
    # copy_edge with both fields
    g = generate_graph()
Minjie Wang's avatar
Minjie Wang committed
42
43
    g.register_message_func(fn.copy_edge(edge='h', out='m'))
    g.register_reduce_func(reducer_both)
44
    # test with update_all
45
    g.update_all()
46
47
48
49
50
51
    assert F.allclose(g.ndata.pop('out'),
            F.tensor([10., 1., 1., 1., 1., 1., 1., 1., 1., 44.]))
    # test with send and then recv
    g.send()
    g.recv()
    assert F.allclose(g.ndata.pop('out'),
52
            F.tensor([10., 1., 1., 1., 1., 1., 1., 1., 1., 44.]))
53
54
55
56

def test_src_mul_edge():
    # src_mul_edge with all fields
    g = generate_graph()
Minjie Wang's avatar
Minjie Wang committed
57
58
    g.register_message_func(fn.src_mul_edge(src='h', edge='h', out='m'))
    g.register_reduce_func(reducer_both)
59
    # test with update_all
60
    g.update_all()
61
62
63
64
65
66
    assert F.allclose(g.ndata.pop('out'),
            F.tensor([100., 1., 1., 1., 1., 1., 1., 1., 1., 284.]))
    # test with send and then recv
    g.send()
    g.recv()
    assert F.allclose(g.ndata.pop('out'),
67
            F.tensor([100., 1., 1., 1., 1., 1., 1., 1., 1., 284.]))
68
69
70
71
72

if __name__ == '__main__':
    test_copy_src()
    test_copy_edge()
    test_src_mul_edge()