Debian Codegraph @

test/test_radius.py

raw symbols SCIP
1 from itertools import product
2
3 import pytest
4 import scipy.spatial
5 import torch
6 from torch_cluster import radius, radius_graph
7 from torch_cluster.testing import devices, grad_dtypes, tensor
8
9
10 def to_set(edge_index):
11 return set([(i, j) for i, j in edge_index.t().tolist()])
12
13
14 @pytest.mark.parametrize('dtype,device', product(grad_dtypes, devices))
15 def test_radius(dtype, device):
16 x = tensor([
17 [-1, -1],
18 [-1, +1],
19 [+1, +1],
20 [+1, -1],
21 [-1, -1],
22 [-1, +1],
23 [+1, +1],
24 [+1, -1],
25 ], dtype, device)
26 y = tensor([
27 [0, 0],
28 [0, 1],
29 ], dtype, device)
30
31 batch_x = tensor([0, 0, 0, 0, 1, 1, 1, 1], torch.long, device)
32 batch_y = tensor([0, 1], torch.long, device)
33
34 edge_index = radius(x, y, 2, max_num_neighbors=4)
35 assert to_set(edge_index) == set([(0, 0), (0, 1), (0, 2), (0, 3), (1, 1),
36 (1, 2), (1, 5), (1, 6)])
37
38 jit = torch.jit.script(radius)
39 edge_index = jit(x, y, 2, max_num_neighbors=4)
40 assert to_set(edge_index) == set([(0, 0), (0, 1), (0, 2), (0, 3), (1, 1),
41 (1, 2), (1, 5), (1, 6)])
42
43 edge_index = radius(x, y, 2, batch_x, batch_y, max_num_neighbors=4)
44 assert to_set(edge_index) == set([(0, 0), (0, 1), (0, 2), (0, 3), (1, 5),
45 (1, 6)])
46
47 # Skipping a batch
48 batch_x = tensor([0, 0, 0, 0, 2, 2, 2, 2], torch.long, device)
49 batch_y = tensor([0, 2], torch.long, device)
50 edge_index = radius(x, y, 2, batch_x, batch_y, max_num_neighbors=4)
51 assert to_set(edge_index) == set([(0, 0), (0, 1), (0, 2), (0, 3), (1, 5),
52 (1, 6)])
53
54
55 @pytest.mark.parametrize('dtype,device', product(grad_dtypes, devices))
56 def test_radius_graph(dtype, device):
57 x = tensor([
58 [-1, -1],
59 [-1, +1],
60 [+1, +1],
61 [+1, -1],
62 ], dtype, device)
63
64 edge_index = radius_graph(x, r=2.5, flow='target_to_source')
65 assert to_set(edge_index) == set([(0, 1), (0, 3), (1, 0), (1, 2), (2, 1),
66 (2, 3), (3, 0), (3, 2)])
67
68 edge_index = radius_graph(x, r=2.5, flow='source_to_target')
69 assert to_set(edge_index) == set([(1, 0), (3, 0), (0, 1), (2, 1), (1, 2),
70 (3, 2), (0, 3), (2, 3)])
71
72 jit = torch.jit.script(radius_graph)
73 edge_index = jit(x, r=2.5, flow='source_to_target')
74 assert to_set(edge_index) == set([(1, 0), (3, 0), (0, 1), (2, 1), (1, 2),
75 (3, 2), (0, 3), (2, 3)])
76
77
78 @pytest.mark.parametrize('dtype,device', product([torch.float], devices))
79 def test_radius_graph_large(dtype, device):
80 x = torch.randn(1000, 3, dtype=dtype, device=device)
81
82 edge_index = radius_graph(x,
83 r=0.5,
84 flow='target_to_source',
85 loop=True,
86 max_num_neighbors=2000)
87
88 tree = scipy.spatial.cKDTree(x.cpu().numpy())
89 col = tree.query_ball_point(x.cpu(), r=0.5)
90 truth = set([(i, j) for i, ns in enumerate(col) for j in ns])
91
92 assert to_set(edge_index.cpu()) == truth