Debian Codegraph @

test/test_knn.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 knn, knn_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_knn(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 [1, 0],
28 [-1, 0],
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 = knn(x, y, 2)
35 assert to_set(edge_index) == set([(0, 2), (0, 3), (1, 0), (1, 1)])
36
37 jit = torch.jit.script(knn)
38 edge_index = jit(x, y, 2)
39 assert to_set(edge_index) == set([(0, 2), (0, 3), (1, 0), (1, 1)])
40
41 edge_index = knn(x, y, 2, batch_x, batch_y)
42 assert to_set(edge_index) == set([(0, 2), (0, 3), (1, 4), (1, 5)])
43
44 if x.is_cuda:
45 edge_index = knn(x, y, 2, batch_x, batch_y, cosine=True)
46 assert to_set(edge_index) == set([(0, 2), (0, 3), (1, 4), (1, 5)])
47
48 # Skipping a batch
49 batch_x = tensor([0, 0, 0, 0, 2, 2, 2, 2], torch.long, device)
50 batch_y = tensor([0, 2], torch.long, device)
51 edge_index = knn(x, y, 2, batch_x, batch_y)
52 assert to_set(edge_index) == set([(0, 2), (0, 3), (1, 4), (1, 5)])
53
54
55 @pytest.mark.parametrize('dtype,device', product(grad_dtypes, devices))
56 def test_knn_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 = knn_graph(x, k=2, 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 = knn_graph(x, k=2, 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(knn_graph)
73 edge_index = jit(x, k=2, 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_knn_graph_large(dtype, device):
80 x = torch.randn(1000, 3, dtype=dtype, device=device)
81
82 edge_index = knn_graph(x, k=5, flow='target_to_source', loop=True)
83
84 tree = scipy.spatial.cKDTree(x.cpu().numpy())
85 _, col = tree.query(x.cpu(), k=5)
86 truth = set([(i, j) for i, ns in enumerate(col) for j in ns])
87
88 assert to_set(edge_index.cpu()) == truth