test_radius.py 1.35 KB
Newer Older
rusty1s's avatar
rusty1s committed
1
2
3
4
from itertools import product

import pytest
import torch
rusty1s's avatar
rusty1s committed
5
from torch_cluster import radius, radius_graph
rusty1s's avatar
rusty1s committed
6

rusty1s's avatar
rusty1s committed
7
from .utils import grad_dtypes, devices, tensor
rusty1s's avatar
rusty1s committed
8
9


rusty1s's avatar
no sort  
rusty1s committed
10
11
12
13
14
15
16
def coalesce(index):
    N = index.max().item() + 1
    tensor = torch.sparse_coo_tensor(index, index.new_ones(index.size(1)),
                                     torch.Size([N, N]))
    return tensor.coalesce().indices()


rusty1s's avatar
rusty1s committed
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
@pytest.mark.parametrize('dtype,device', product(grad_dtypes, devices))
def test_radius(dtype, device):
    x = tensor([
        [-1, -1],
        [-1, +1],
        [+1, +1],
        [+1, -1],
        [-1, -1],
        [-1, +1],
        [+1, +1],
        [+1, -1],
    ], dtype, device)
    y = tensor([
        [0, 0],
        [0, 1],
    ], dtype, device)

    batch_x = tensor([0, 0, 0, 0, 1, 1, 1, 1], torch.long, device)
    batch_y = tensor([0, 1], torch.long, device)

    out = radius(x, y, 2, batch_x, batch_y, max_num_neighbors=4)
rusty1s's avatar
no sort  
rusty1s committed
38
    assert coalesce(out).tolist() == [[0, 0, 0, 0, 1, 1], [0, 1, 2, 3, 5, 6]]
rusty1s's avatar
rusty1s committed
39
40
41
42
43
44
45
46
47
48
49


@pytest.mark.parametrize('dtype,device', product(grad_dtypes, devices))
def test_radius_graph(dtype, device):
    x = tensor([
        [-1, -1],
        [-1, +1],
        [+1, +1],
        [+1, -1],
    ], dtype, device)

rusty1s's avatar
no sort  
rusty1s committed
50
51
52
    out = radius_graph(x, r=2)
    assert coalesce(out).tolist() == [[0, 0, 1, 1, 2, 2, 3, 3],
                                      [1, 3, 0, 2, 1, 3, 0, 2]]